Sub topic 6
Public APIs and module boundaries
This chapter assumes you can write React components and hooks, and that you know ES module syntax (import, export) and basic TypeScript. It also assumes you have already grouped code by feature, as in the earlier chapters on feature modules. Here you will decide which parts of a feature other code may use, and which parts stay private.
What a module boundary is
A feature folder groups files, but grouping alone does not stop other code from reaching into it. If any file can import features/cart/components/CartRow, then every file in the cart feature is effectively public. Renaming or moving one of them can break code anywhere in the app.
A module boundary is a rule about which files outside a feature may import from it. The usual rule is that outside code imports from the feature's index.ts file and nothing else. That file is the feature's public API: the list of components, hooks, and types the feature promises to keep stable. Everything not listed there is internal and free to change.
The index file as the public API
Here is a cart feature with a small public API:
// src/features/cart/types.ts
export type CartItem = {
productId: string;
name: string;
quantity: number;
unitPrice: number;
};// src/features/cart/index.ts
export { CartList } from "./components/CartList";
export { useCart } from "./hooks/useCart";
export type { CartItem } from "./types";Other code uses only these three names:
// src/features/header/components/CartBadge.tsx
import { useCart } from "@/features/cart";
export function CartBadge() {
const { items } = useCart();
const count = items.reduce((sum, item) => sum + item.quantity, 0);
return <span aria-label="Items in cart">{count}</span>;
}The @/ prefix is a path alias, covered in the previous chapter. The important part is the path @/features/cart, which ends at the feature folder and resolves to its index.ts.
Now compare the two import styles.
// Allowed: goes through the public API
import { CartList } from "@/features/cart";
// Not allowed: reaches into internals
import { CartList } from "@/features/cart/components/CartList";
import { calculateTotals } from "@/features/cart/utils/totals";The second style works at runtime, so nothing fails until the cart team moves totals.ts and the build breaks in an unrelated feature.
Why the boundary reduces cost
The boundary limits how much code a change can affect.
| Import style | What the importer depends on | Effect of refactoring cart internals |
|---|---|---|
| Through `index.ts` | Three exported names | Safe if the names and their behavior stay the same |
| Deep import | Specific file paths and file contents | Can break any file that imports the path |
With a boundary, the cart team can split CartList into smaller components, rename helpers, or replace the state implementation. They only need to preserve what index.ts exports. This is also how you review a change: a diff that touches only internals needs no review from other teams, and a diff that touches index.ts is an API change.
Deciding what to export
Start with an empty index and add a name only when another feature needs it. Removing an export later is a breaking change, while adding one is cheap.
Usually export:
- Components that other features or pages render, such as
CartList. - Hooks that expose the feature's data or actions, such as
useCart. - Types that appear in those components' props or hooks' return values.
Usually keep private:
- Subcomponents that only the feature's own components use.
- The raw
api.tsfunctions. If other code needs the data, export a hook, so callers do not depend on how it is fetched. - Helper functions, constants, and internal state shapes.
- Test files and test utilities.
A useful check: if you could delete an export and tell the other team only "use the hook instead", it probably did not need to be public.
Direction of dependencies
A boundary also needs a direction. A common rule set is:
sharedimports from nothing else in the app.featuresimport fromsharedand, sparingly, from other features' public APIs.pagesandappimport fromfeaturesandshared.
Feature-to-feature imports are the weak point. If cart imports from orders and orders imports from cart, you have a circular dependency, and the two features cannot be understood or moved separately. When two features need to cooperate, compose them one level up. A page can render CartList next to OrderSummary and pass data between them as props, so neither feature imports the other.
Common errors
Using `export *` in the index
export * from "./components/CartList" is shorter, but it exports everything the file exports, including helpers added later by accident. The public API then grows without anyone deciding it should. Use named exports in the index so every public name is a deliberate line in the file.
Importing the feature's own index from inside the feature
Inside the cart feature, files should import each other with relative paths (../types), not through @/features/cart. If CartList imports from the index, and the index imports CartList, you create a cycle. Depending on bundler order, you then get undefined values at runtime that are hard to trace.
Re-exporting types without `export type`
When isolatedModules is on (the default in Vite projects), the compiler handles each file alone and cannot tell that CartItem is only a type. Write export type { CartItem } from "./types" as shown above. A plain export { CartItem } can fail at build time or leave a broken reference at runtime.
Large index files that defeat code splitting
Importing a feature's index loads every module the index re-exports, including components the importing code does not use. Bundlers can drop unused exports (tree shaking), but only when the modules have no side effects, and that is not guaranteed. For a feature that you load lazily, this matters. In the routing chapter, lazy(() => import("@/features/settings/SettingsPage")) imports a file directly, which skips the boundary on purpose. You have two options:
- Let the index export the lazy component itself, so the dynamic import lives inside the feature:
// src/features/settings/index.ts
import { lazy } from "react";
export const SettingsPage = lazy(() => import("./SettingsPage"));This requires SettingsPage.tsx to use export default. Consumers import SettingsPage from @/features/settings and the boundary stays intact.
- Or allow a documented exception in your lint rules for route entry files.
The first option is simpler to enforce, because it needs no exceptions.
Relying on convention alone
A boundary that exists only in a wiki page decays. Someone in a hurry uses the deep import, the reviewer misses it, and the next person copies it. The enforcement chapter shows an ESLint no-restricted-imports rule that reports any import matching @/features/*/*. Add it when you introduce the boundary, so the rule never has to catch up with existing violations.
Checking your boundary
Before you merge a change to a feature, ask three questions:
- Did I add or remove a name in
index.ts? If so, treat this as an API change and tell consumers. - Does any file outside the feature import a path longer than
@/features/<name>? - Does the feature import from another feature, and could a page compose them instead?
Exercise
The orders feature has api.ts with fetchOrders, a useOrders hook that wraps it, an OrderTable component, and a private formatOrderStatus helper. The account page needs to show the user's orders. Write the index.ts for orders, and explain why fetchOrders is not in it.
Show answer
The index should contain export { OrderTable } from "./components/OrderTable";, export { useOrders } from "./hooks/useOrders";, and export type { Order } from "./api";. fetchOrders stays private because callers only need the data, and useOrders already provides it. If fetchOrders were public, other features could call it directly, and moving to a different fetching approach would then break them. formatOrderStatus stays private because only orders components use it.
Exercise
A teammate adds import { totals } from "@/features/cart/utils/totals" to the checkout page. Name two ways to fix this, and say which one you would choose if checkout needs the totals for display only.
Show answer
One fix is to export totals (or a hook that returns the computed totals) from features/cart/index.ts and import it from @/features/cart. The other is to have the cart feature expose a component, such as CartSummary, that renders the totals, so checkout does not need the function. For display only, the component is better, because the cart keeps ownership of the calculation and the public API stays small.