Skip to content

    Frontend System Design

    Module Boundaries and Public APIs

    Define a module's public API, stop deep imports and circular dependencies, and enforce boundaries with ESLint, package exports and a dependency graph check.

    By Published 12 min read

    • frontend-system-design
    • module-boundaries
    • public-api
    • architecture
    Share

    Standard lessonintermediateTypeScript labFrontend System Design

    Before this: Feature-Based and Modular Folder Structure

    What you'll learn: By the end of this lesson you will be able to say what a module boundary is and what belongs in a public API, explain why an index.ts is a convention and not yet a boundary, describe how circular imports arise and what they break, choose between ESLint rules, graph checks and package exports (with what each documented tool does not see), weigh the cost of barrel files, and read the output of a small boundary checker.

    A flat in a block has a front door and a bell. Visitors use the door. The wall is thick, and behind it the owner can move the kitchen or replace the pipes without telling anyone. That freedom exists only because nobody else walks through the wall. If a neighbour has quietly drilled a hole to borrow a cupboard, every renovation becomes a negotiation.

    A front-end module is the same. A feature folder can reorganise its hooks and swap its state library as long as the rest of the app uses the door. The running example is the storefront from Feature-Based and Modular Folder Structure: features such as cart and search, a shared folder and an app layer.

    The core idea

    1. A module boundary is a line around code that changes together, with a small set of names allowed to cross it. What crosses is the public API. Everything else is internal.
    2. The value of a boundary is the freedom behind it. The narrower the public API, the more the owners can change without breaking anyone. This is a design argument, not a language rule.
    3. An unchecked boundary decays. An index.ts is a request. A lint rule, a graph check or a package exports map is what a build can fail on.

    Three illustrations: a minimal one (one deep import), a realistic one (the lab's layered storefront) and a failure (a cycle).

    What a public API is

    Here a module is a unit someone owns: a feature folder, a layer slice or a workspace package. That is wider than the language's meaning (a single file). A public API is, in Feature-Sliced Design's words, "a contract between a group of modules, like a slice, and the code that uses it". In practice it is an index file that re-exports a few names (features/cart/index.ts), or, for a package, the exports field of its package.json.

    Illustration 1 (minimal): one door, one deep import.

    // in features/search/SearchResult.tsx
    
    // uses the door: fine
    import { CartBadge } from "@/features/cart";
    
    // reaches through the wall: search now depends on cart's folder layout
    import { applyDiscount } from "@/features/cart/pricing/applyDiscount";

    Nothing stops the second import, and the app works today. But the cart team can no longer move applyDiscount, and nobody wrote down that search needs it. This is a deep import: one that goes past the public API. FSD's page says it plainly: with an index file, "you don't actually forbid anyone from not using it and importing directly".

    Figure 1. The door and the hole in the wall

    Search imports the cart through its index file, and a deep import bypasses itsearch to cart/index.ts (imports); cart/index.ts to cart internals (re-exports); search to cart internals (deep import)FEATURES/CARTsearch: another featuresearchanother featurecart/index.ts: public APIcart/index.tspublic APIcart internals: hooks, pricing, apicart internalshooks, pricing,apiimportsre-exportsdeep import

    How to read this: arrows point from importer to imported. The first path is the contract; the red arrow ties search to cart's folder layout.

    What belongs in it. What another module needs to use the feature: a component, a hook, a few types; helpers and state slices stay inside. In the index, list names (export { CartBadge } from "./CartBadge") rather than export * from: MDN warns that export * re-exports everything except the default, so you "may accidentally expose things".

    Where the boundary is checked

    Between folders in one app. The language gives nothing: any file can import any file. Tools read the import statements:

    • ESLint no-restricted-imports disallows modules or gitignore-style patterns (patterns with group) and appends your message to the error. It covers static import only, "not dynamic ones", so import() slips past. An illustrative pattern, not run here: group: ["@/features/*/*"].
    • import/no-restricted-paths (eslint-plugin-import) defines zones: a target (files the zone applies to), a from (folders they may not import), optional except and message. Its example forbids ./client from importing ./server and allows the reverse, a one-way rule of the kind layering needs.
    • eslint-plugin-boundaries classifies files into elements and lets you write policies for what may depend on what (policy rule boundaries/dependencies in its current README; rule names depend on the version).
    • dependency-cruiser validates the whole graph against forbidden rules with from and to conditions and a severity of error, warn, info or ignore. The error severity makes some reporters return a non-zero exit code, which fails a pipeline. A to condition can match circular dependencies.

    Between packages. Node's exports field prevents "any other entry points besides those defined", letting authors "clearly define the public interface". An import of an unlisted subpath throws ERR_PACKAGE_PATH_NOT_EXPORTED; * patterns expose a family of files and a null target hides a private subfolder. Node also says this "is not a strong encapsulation": a direct require of the absolute file path still loads it.

    Between TypeScript projects. Project references list better "enforcement of the logical groupings of your program" among their benefits, and imports from a referenced project load its output .d.ts. That is a boundary per project and says nothing about which files inside one are public.

    Figure 2. Three places to enforce a boundary

    An import meets ESLint in the editor, a graph check in CI and the exports map at runtimeA new import to ESLint (edit time); ESLint to CI graph check (per change); A new import to Package exports (if a package)A new import: one lineA new importone lineESLint: per fileESLintper fileCI graph check: whole graphCI graph checkwhole graphPackage exports: at runtimePackageexportsat runtimeedit timeper changeif a package

    How to read this: ESLint sees one file; the graph check sees the whole project, so only it can find cycles; the exports map applies only when the module is a package.

    Mechanism Stops Misses
    Index file alone Nothing (a convention) Deep imports
    ESLint restricted imports or zones Matching imports, at edit time Dynamic import() (core rule); cycles
    import/no-cycle Cycles, per file Cost ("comparatively computationally expensive"); ignores type-only imports
    Graph tool in CI Forbidden edges and cycles project-wide Anything the config does not describe
    Package exports Unlisted subpaths Direct file paths; non-package folders
    TS project references Cross-project imports load declarations Which files inside a project are public

    Circular dependencies

    A cycle exists when A imports B and B, directly or through others, imports A. MDN's module-graph guide says "cycles are often inevitable" but "you should usually avoid cyclic imports in your project, because they make your code more error-prone".

    At runtime the engine does not loop forever: an already-evaluating module is not visited again, so one module in the cycle runs before the other has finished. MDN's example reads a const at the top level of a module still being evaluated and gets ReferenceError: Cannot access 'a' before initialization. The same cycle can work when the value is read later, so whether it breaks can depend on load order, which makes such failures hard to reproduce.

    In the design, two modules in a cycle cannot be understood, tested or moved alone (an inference, not a measurement). MDN's ways out: merge the two modules, move the shared code into a third module, or move code from one to the other. In front-end terms the middle one is usual: two features that import each other share a concept (the cart contents), which moves to shared code or up to the layer that composes both.

    Barrel files and what they cost

    A barrel file only re-exports; MDN calls it a "barrel module" because it "doesn't do anything other than aggregating exports". An index used as a public API is one.

    • It enforces nothing, as shown above.
    • It can widen what tools load. Marvin Hagemeister's article says importing a barrel can mean you "end up importing every single file in your project through a spiderweb of import statements", because modules are not loaded lazily, and that removing barrels "makes many tasks 60-80% faster". That is one author's measurement on his own setups, not a rule.
    • Others document the pressure. FSD says "some bundlers might have a hard time tree-shaking" index files, and Next.js offers the experimental optimizePackageImports because "some packages can export hundreds or thousands of modules".

    The module-graph lab behind Code Splitting, Lazy Loading and Tree Shaking models the bundler side: in its golden output the entry chunk is 83 abstract units when components come through a barrel ui module and 23 when imported directly (a model with invented sizes, not a bundler). So: a thin index at feature boundaries, direct relative imports inside the module, and no barrel per folder by habit.

    Build it: a boundary checker over an import graph

    Illustration 2 (realistic): a layered storefront. The lab's graph has five layers (app, pages, features, entities, shared), slices inside three, and an index as each slice's public API.

    Setup. The lab is examples/frontend/labs/module-boundary-checker. It is a model of an architecture linter, not a linter: it reads no files, parses no TypeScript and knows nothing about path aliases, type-only or dynamic imports, or exports. The rule names in its output are its own.

    cd examples/frontend/labs/module-boundary-checker
    ../../node_modules/.bin/vitest run    # 26 tests
    ../../node_modules/.bin/tsc -p tsconfig.json
    node src/demo.ts

    Steps.

    1. Read the configuration, an excerpt of the lab's graphs.ts:

      export const storefrontConfig: Config = {
        layers: ["app", "pages", "features", "entities", "shared"],
        sliceLayers: ["pages", "features", "entities"],
        publicApi: ["index.ts"],
        crossSlice: "forbid",
      };
    2. Read the rules in check.ts: layer-direction (own layer or lower only), cross-slice, public-api (from outside a slice only the listed files), own-public-api (inside a slice use a relative path, not the slice's index), plus unknown-file and unknown-import.

    3. Run the demo. Scenario 1 is clean; 2 adds "a year of shortcuts"; 3 sets crossSlice to allow; 4 adds one deep import to the clean graph.

    Expected output, captured from a real run (Node 26.12.1, 2026-11-08):

    === 1. The clean storefront
    16 modules, 21 imports examined, 0 violation(s)
    
    === 2. The drifted storefront
    17 modules, 26 imports examined, 6 violation(s)
      own-public-api: entities/cart/model/cartStore.ts -> entities/cart/index.ts
          a file inside entities/cart imports its own public API (use a relative import)
      layer-direction: entities/product/ui/ProductPrice.tsx -> features/add-to-cart/index.ts
          entities must not import from features, which is above it
      public-api: features/add-to-cart/ui/AddToCart.tsx -> entities/cart/model/cartStore.ts
          entities/cart is imported by a file outside it, but model/cartStore.ts is not its public API
      cross-slice: features/wishlist/ui/WishlistButton.tsx -> features/add-to-cart/index.ts
          slice wishlist must not import slice add-to-cart of the same layer
      unknown-file: scripts/seed.ts
          the file is in no layer (or in a sliced layer without a slice folder)
      layer-direction: shared/lib/money.ts -> entities/product/index.ts
          shared must not import from entities, which is above it
      by rule: unknown-file=1, layer-direction=2, cross-slice=1, public-api=1, own-public-api=1
    
    === 3. The drifted storefront with sideways imports between features allowed
    17 modules, 26 imports examined, 5 violation(s)
      own-public-api: entities/cart/model/cartStore.ts -> entities/cart/index.ts
          a file inside entities/cart imports its own public API (use a relative import)
      layer-direction: entities/product/ui/ProductPrice.tsx -> features/add-to-cart/index.ts
          entities must not import from features, which is above it
      public-api: features/add-to-cart/ui/AddToCart.tsx -> entities/cart/model/cartStore.ts
          entities/cart is imported by a file outside it, but model/cartStore.ts is not its public API
      unknown-file: scripts/seed.ts
          the file is in no layer (or in a sliced layer without a slice folder)
      layer-direction: shared/lib/money.ts -> entities/product/index.ts
          shared must not import from entities, which is above it
      by rule: unknown-file=1, layer-direction=2, public-api=1, own-public-api=1
    
    === 4. The clean storefront plus one new import that reaches into another slice
    16 modules, 22 imports examined, 1 violation(s)
      public-api: pages/cart/ui/CartPage.tsx -> features/add-to-cart/ui/AddToCart.tsx
          features/add-to-cart is imported by a file outside it, but ui/AddToCart.tsx is not its public API
      by rule: public-api=1

    Scenario 4 is Illustration 1 in miniature: one new line, one public-api violation naming importer, imported file and reason. The own-public-api line in scenario 2 is the barrel hazard: a file inside entities/cart imports the index that re-exports it.

    Illustration 3 (failure): cycles. The lab has no cycle rule and reports none (adding one is its stretch exercise). But a depth-first walk of the import lists in graphs.ts, done separately from the lab as a check on this lesson, finds three cycles in the drifted graph and none in the clean one. Each runs through a violating import: entities/cart/index.ts and cartStore.ts (the own-public-api line); the product index, ProductPrice.tsx and money.ts (the layer-direction line for money.ts); and a ring between features/add-to-cart and entities/product (the other layer-direction line). A cycle across layers needs one upward import and a cycle across slices needs a sideways one, so forbidding those prevents most cycles without a cycle search; cycles inside one slice are caught by no rule, so a graph check is still worth having.

    Figure 3. A cycle that passes through a violating import

    flowchart LR accTitle: A cycle in the drifted storefront closed by an upward import accDescr: The features add-to-cart index imports AddToCart, which imports the entities product index, which imports ProductPrice, which imports the features add-to-cart index again. The last edge goes up a layer and is a layer-direction violation. F1["features/add-to-cart/index.ts"] --> F2["AddToCart.tsx"] F2 --> E1["entities/product/index.ts"] E1 --> E2["ProductPrice.tsx"] E2 -->|"upward import
    (layer-direction violation)"| F1

    How to read this: every edge but the last goes down or stays in a slice, which the rules allow. The last edge goes up, closes the ring and is the line the checker reports.

    Break it. In src/check.ts change if (toRank < fromRank) { to if (toRank <= fromRank) {: imports inside one layer now count as upward and the clean graph reports violations. Revert it and re-run the tests. Stretch. Add a cycle rule, or a severity per rule with an exit code (dependency-cruiser's model).

    In practice: protecting feature folders and a shared UI package

    NOTE

    This is a realistic scenario, not a case history. It is a composite built from common production patterns. It describes no specific company or product, and every number in it is an illustrative assumption.

    The situation

    A storefront has six feature folders and a shared UI package, @shop/ui, in one workspace (illustrative). Three teams own features. Pull requests that "just move a file" keep breaking another team's build, because features import internal paths such as @/features/cart/pricing/applyDiscount and @shop/ui/dist/icons/cart.js.

    Starting architecture

    Figure 4. Starting point: imports go wherever the files are

    Starting architecture: features import each other's internals and the UI package's build outputsearch to cart internals (deep import); checkout to cart internals (deep import); checkout to @shop/ui dist (dist path); cart internals to @shop/ui distsearch: team Bsearchteam Bcheckout: team Ccheckoutteam Ccart internals: team Acart internalsteam A@shop/ui dist: no exports map@shop/ui distno exports mapdeep importdeep importdist path

    How to read this: the cart team's folder layout and the UI package's build layout became public by accident, so changing either breaks someone.

    The decision

    Field Decision record
    Context Internal layout is relied on by others, so moving files breaks them.
    Decision Each feature gets an index.ts with named exports. A restricted-imports rule for deep feature paths starts at warn, then error. @shop/ui gets an exports map of supported subpaths. CI runs a cycle check.
    Consequences, good Teams move internals freely; deep imports show in review; cycles are found by a tool.
    Consequences, bad Index files are barrels with the costs above; exports breaks anyone using unlisted paths.
    Revisit when Many violations say "needs a name that is not exported" (API too small).

    Rollout and verification

    1. Count first. Run rules at warn, record the violations, lower the count weekly, promote to error at zero.
    2. Search the whole repository for deep imports of @shop/ui, including scripts, tests and config, before adding exports. Node's documentation says adding it to an existing package "will likely be a breaking change".
    3. Export the names consumers really use; anything with no stated reason stays private.
    4. Fail the build on a new cycle.

    The 2 a.m. failure

    The nightly job that regenerates icon sprites fails right after the exports map ships. It is a plain Node script, outside the app's lint rules, importing @shop/ui/dist/icons/cart.js, and Node throws ERR_PACKAGE_PATH_NOT_EXPORTED (illustrative).

    First three checks: (1) read the error code and the subpath it names; (2) search the repository, including scripts/, for other @shop/ui/dist imports; (3) compare subpaths in use with the map. Mitigation: add the subpath, or import from the supported entry. Follow-up: run the lint rule on every folder that can import the package, and announce exports changes like any breaking change.

    Architect's notes

    • Design the public API before the folder, and keep it small: a name that is not exported is a name you can change.
    • Make the rule fail the build. Measure at warn, then error, or it is advice.
    • Check the whole graph as well as each file, and know each tool's blind spots (dynamic imports, type-only imports, files outside lint scope).

    Common mistakes

    • Believing an index.ts is a boundary. It marks a door; it does not close the wall.
    • Exporting everything from the index, so every refactor is a breaking change.
    • Importing your own index from inside the module, an easy cycle.
    • Adding exports without searching scripts, tests and tooling.

    Key takeaways

    • A module boundary surrounds code that changes together; its public API is what may cross it.
    • A deep import goes past the API; an index file alone does not stop it.
    • Enforce with ESLint rules, a graph check, package exports or project references, as fits the module.
    • A cycle means modules cannot be understood or moved alone, and may fail depending on load order.
    • Forbidding upward and sideways imports prevents most cycles; a graph check catches the rest.
    • Barrel files carry costs: no enforcement, wider module graphs, easy cycles. Keep them at boundaries.

    Practice exercises

    Exercise 1 (Starter, 30 min): For one feature you know, write the names it should export. Count how many other modules import something not on your list.

    Exercise 2 (Intermediate, 2 hours): In the lab, add a file to the clean storefront that imports across two slices of features. Predict the violations, then run the demo and explain any difference.

    Exercise 3 (Advanced, half day): Implement the stretch cycle rule. Show that it finds the three cycles in the drifted graph and none in the clean one, and decide whether to report a cycle once or once per edge.

    In this course:

    Official documentation

    Tools and further reading

    Ask about this article

    Get answers grounded in this post. AI-generated — based on this article, and may be imperfect.

    Scaled AI Weekly

    Enjoyed this? Get more like it every Monday.

    Real architecture decisions, LLMOps patterns that survive production, and engineering leadership advice — from 12+ years of building at enterprise scale. Free. No spam. Unsubscribe anytime.

    Get new articles by email

    Free. We email a confirmation link first, and you can unsubscribe from any email.

    Join engineers building production AI systems

    Comments