The production checklist kept one app safe and observable. This chapter is about the other way apps fail at scale: not at runtime, but in the codebase. Forty engineers, six teams, three years of features. Nobody can say what a change will break, the "shared" folder has become a junk drawer, two teams built the same date picker, and the build takes twenty minutes.
None of that is a React problem, exactly. React gives you components and leaves structure to you. But React interviews at senior level almost always reach "how would you structure a large React codebase?", and the good answers have the same shape: draw boundaries, give each one a small public surface, make dependencies point one way, enforce it with tools instead of code review, and match the boundaries to teams. This chapter builds that answer piece by piece, and takes positions on folders, design systems, monorepos, micro-frontends and API contracts, with the trade-offs.
The problem: everything can import everything#
JavaScript modules have no access control. Any file can import any other file it can name. In a small app that's freedom. In a large one, the import graph becomes the real architecture, whatever the folder names say.
Here's the reading-list app organized the way most apps start: by technical layer. pages/, components/, hooks/, utils/. The sandbox walks the import graph backwards to find everything that depends on a file, which is the set of things a change to that file can break.
// file -> files it imports
type Graph = Record<string, string[]>;
const byLayer: Graph = {
"pages/BooksPage.tsx": ["components/BookList.tsx", "components/CartBadge.tsx", "hooks/useBooks.ts"],
"pages/CartPage.tsx": ["components/CartList.tsx", "hooks/useCart.ts"],
"pages/AccountPage.tsx": ["components/ProfileForm.tsx", "hooks/useUser.ts"],
"components/BookList.tsx": ["components/BookCard.tsx"],
"components/BookCard.tsx": ["hooks/useCart.ts", "utils/format.ts"],
"components/CartList.tsx": ["components/BookCard.tsx", "utils/format.ts"],
"components/CartBadge.tsx": ["hooks/useCart.ts"],
"components/ProfileForm.tsx": ["hooks/useCart.ts", "utils/format.ts"],
"hooks/useBooks.ts": ["utils/api.ts"],
"hooks/useCart.ts": ["utils/api.ts", "hooks/useUser.ts"],
"hooks/useUser.ts": ["utils/api.ts"],
"utils/format.ts": [],
"utils/api.ts": [],
};
function dependents(graph: Graph, target: string): string[] {
const importedBy = new Map<string, string[]>();
for (const [from, tos] of Object.entries(graph)) {
for (const to of tos) importedBy.set(to, [...(importedBy.get(to) ?? []), from]);
}
const seen = new Set<string>();
const queue = [target];
while (queue.length) {
for (const parent of importedBy.get(queue.shift()!) ?? []) {
if (!seen.has(parent)) {
seen.add(parent);
queue.push(parent);
}
}
}
return [...seen].sort();
}
const changed = "hooks/useCart.ts";
const hit = dependents(byLayer, changed);
console.log(`Changing ${changed} can affect ${hit.length} files:`);
console.log(hit.join("\n"));
console.log("Folders involved:", [...new Set(hit.map((f) => f.split("/")[0]))].join(", "));Change the cart hook and eight of the twelve other files are in play, spread over both pages/ and components/, including the account page, because someone made ProfileForm show the cart count. Nothing in the folder structure warned you. The folders group files by what they are (a hook, a component), while changes happen by what they're for (the cart). So every feature change touches four folders, every folder is touched by every team, and "who owns components/?" has no answer.
That's the pattern to fix: coupling you can't see, can't control and can't assign.
Feature folders and colocation#
The first move is to group by feature (sometimes called vertical slices or domains): everything for the cart lives in features/cart/, whatever kind of file it is.
src/
pages/ BooksPage, CartPage, AccountPage
components/ BookList, BookCard, CartList, CartBadge, ProfileForm
hooks/ useBooks, useCart, useUser
utils/ format, apiColocation is the same idea at file level: keep a component's test, styles, story and small helpers next to it, and keep state as close as possible to where it's used. Things that change together live together, and deleting a feature is deleting a folder.
My position: layer-based is fine for a small app or a prototype, where the whole graph fits in one head. Past a handful of screens or more than one team, go feature-based, because it's the only structure where folder boundaries line up with the way work arrives. Don't over-nest either: three levels (features/cart/components/) is usually the most you need. And don't move files to the shared layer until a second feature actually needs them; premature sharing is how shared/ becomes the new junk drawer.
In a Next.js App Router project, app/ is the routing tree, so it holds routes and composition, and features live beside it (src/features/). The App Router helps with colocation: files that aren't special route files (page, layout, route and so on) aren't routable, folders starting with an underscore (_components) are explicitly private, and route groups ((shop)) organize routes without changing URLs.
A `useBookSearch` hook is used only by the search box in the books feature. A teammate wants to put it in `shared/hooks/` because hooks go in a hooks folder. What's the best home?
A public API for every feature#
Moving files into feature folders doesn't change the graph by itself. If features/account/ProfileForm.tsx can still import features/cart/useCart.ts, you've renamed the folders and kept the coupling. The second move is to give each feature a public API: one file, usually index.ts, that exports what other code may use. Everything else in the folder is private by convention, and then by tooling.
Each feature is a folder with private internals (components, hooks, data calls) and one public file, index.ts, that says what the rest of the app may use.
// The cart's contract with the rest of the app. Small on purpose.
export { CartBadge } from "./CartBadge";
export { CartPage } from "./CartPage";
export { useCartCount } from "./useCartCount";
export type { CartLine } from "./cart.types";
// Not exported: useCart internals, cart.api.ts, CartList, pricing helpers.Two rules make this work.
- The app layer composes; features don't import each other by default. If the books page needs a cart badge, the route renders both features side by side, or passes the badge into the book list as a prop or slot. When a feature genuinely needs another (checkout needs the cart's lines), it imports only from that feature's
index.ts, and the import graph between features must stay acyclic. - No deep imports.
import { applyDiscount } from "../cart/pricing"from outside the cart is a violation, even if it compiles.
Enforce it with tools, not review#
A boundary that's enforced only in code review lasts until the first deadline. The tools, from lightest to strongest:
- ESLint
no-restricted-importswith patterns such asfeatures/*/*(and an exception forindex). Cheap and good enough for many teams. - Boundary plugins and graph checkers:
eslint-plugin-boundariesor dependency-cruiser describe layers and allowed edges as rules; Nx's@nx/enforce-module-boundariesdoes it with project tags (type:featuremay depend ontype:ui, not the reverse). - Package boundaries. In a monorepo, make a feature its own workspace package with an
exportsfield inpackage.json. Node and modern bundlers (and TypeScript withmoduleResolution: "bundler"or"nodenext") refuse to resolve paths the package doesn't export, so a deep import is a resolution error, not a lint warning.
In the next exercise you'll build the core of such a checker.
The dependency rule#
Boundaries give you the boxes. The dependency rule gives the arrows a direction: a module may only import from layers below it. Routes import features, features import shared code, shared code imports nothing above it. The same rule draws the server and client split from Server Components: data access is a server-only layer that client code can't import at all.
Three layers. The rule is one sentence: a module may import only from layers below it. Nothing imports upward.
Why insist on direction? Because a graph with no upward edges has no cycles between layers, and that buys three things. Shared code stays reusable (a Button that imports the cart can't be used without the cart). Changes ripple in a predictable direction: editing a feature can't break the design system. And build tools can cache and test layers independently, which matters once you're in a monorepo.
Implement checkImports(edges) in boundaries.ts. Each edge is [from, to], two paths like "features/cart/useCart.ts". Return a violation for each edge that breaks a rule, in input order:
"upward": the layers areapp(top),features,shared(bottom), given by the first path segment. Importing from a higher layer is upward. Imports within the same layer are fine as far as this rule goes."deep-import":tois inside somefeatures/<name>/but isn't that feature'sindex.ts, andfromis outside that feature.
If an edge breaks both rules, report only "upward".
export type Edge = [from: string, to: string];
export type Violation = { from: string; to: string; rule: "upward" | "deep-import" };
export function checkImports(edges: Edge[]): Violation[] {
// TODO
return [];
}Design systems and component libraries#
A design system is the shared layer most visible to users: the components, tokens and rules that make forty engineers' screens look like one product. It has layers of its own:
- Tokens: colors, spacing, type scale, radii, motion, as CSS variables (or a Tailwind theme). Themes and dark mode are token swaps.
- Primitives: behavior without styling. Focus management, keyboard navigation and ARIA for dialogs, menus, comboboxes and tooltips. This is hard to get right, which is why headless libraries exist (Radix Primitives, React Aria, Base UI).
- Components: your
Button,Dialog,Select, styled with your tokens on top of primitives. - Patterns: compositions like a data table with filters, or a form layout, documented with examples.
My position: build the styling, buy the behavior. Wrap a headless library with your tokens and API instead of writing your own focus trap. That's the shadcn/ui model too: it copies component source (built on headless primitives) into your repository, so you own and edit it, rather than installing a styled library you can only configure. Owning the source fits a product with its own brand; installing a full library (MUI, Mantine, Chakra) fits internal tools where speed matters more than distinctiveness.
API design decides whether teams use the system or fork it:
- Compose, don't configure.
<Dialog><Dialog.Title /><Dialog.Body /></Dialog>(compound components) ages better than aDialogwith thirty props. Slots andasChild-style props let teams render aLinkwith button styling without a new variant. - Variants are named decisions:
variant="danger" size="sm", mapped to tokens, rather than arbitraryclassNameoverrides that drift. - Pass through what the platform has. Spread remaining props onto the underlying element, accept
ref(a normal prop since React 19), and keep native semantics (a button is a<button>). - Accessibility is built in, not documented. If the
IconButtonrequires alabelprop, nobody ships an unlabeled icon button.
Treat it as a product: versioned with semver if it's a package, changelogs, codemods for breaking changes, Storybook (or similar) for documentation, and visual regression tests so a token change doesn't silently restyle the app. A design system team that only builds and never supports adoption ends up with each feature team keeping its own copy.
Monorepos#
A monorepo puts several projects (apps and packages) in one repository, with tooling that understands the dependencies between them. It's a repository decision, separate from deployment: three apps in a monorepo still deploy independently.
The pieces you'll be asked about:
- pnpm workspaces (or npm, Yarn and Bun workspaces) link local packages together.
pnpm-workspace.yamllists the folders, and a dependency like"@acme/ui": "workspace:*"resolves to the local package instead of the registry. - Turborepo runs tasks across packages in dependency order and caches results by hashing inputs. If nothing that
@acme/uidepends on changed, itsbuildandtestare replayed from cache, locally or from a shared remote cache, so CI only does new work. - Nx does the same and more: a project graph, "affected" commands that run only what a change can impact, code generators, and module boundary rules with tags.
packages:
- "apps/*"
- "packages/*""^build" means "build my dependencies first". The exports map is the package's public API, enforced by module resolution: @acme/ui/src/internal/focus doesn't resolve. Internal packages often export TypeScript source directly and let the app's bundler compile it (Next.js has transpilePackages for this), which avoids a build step per package at the cost of every app compiling it.
When is a monorepo worth it? When you have several deployables that share code: a web app, an admin app, a marketing site and a design system, or a frontend and a backend sharing types. You get atomic changes across packages (change the Button and every caller in one PR), one version of React everywhere, and shared tooling. You pay with CI that needs caching and affected-only runs to stay fast, tooling to learn, and a repository everyone shares. For a single app, feature folders and lint rules give you the boundaries without the machinery. Don't adopt a monorepo to get structure; adopt it when you have more than one thing to ship.
Micro-frontends#
Micro-frontends split one user-facing product into frontends that separate teams build and deploy independently, composed into one experience. That last part is the definition: a monorepo with shared packages isn't micro-frontends, because everything still ships together.
There are three ways to compose them, from simplest to most coupled at runtime:
| Approach | How | Costs |
|---|---|---|
| Route-level split | Each app owns a set of URL paths behind one domain. Next.js calls these Multi-Zones: separate apps, routed by rewrites or a proxy | Moving between zones is a full page load; shared layout must be duplicated or packaged |
| Runtime composition | One host page loads remote components at runtime, usually with Module Federation (webpack 5, Rspack) | Shared singletons (React itself), version skew between remotes, harder testing and debugging |
| Isolation | iframes or Web Components wrapping independent apps | Strong isolation, but awkward sizing, routing, styling and accessibility; heavy |
When they're worth it: many teams (think dozens) whose release schedules block each other, organizational boundaries that really are independent (a separately run business unit), or migrating a legacy app incrementally by routing one path at a time to the new stack (the strangler pattern).
When they hurt, which is most of the time:
- Performance. Each frontend ships its own bundles. Without careful sharing you download React twice; with sharing you're coordinating versions at runtime.
- Two Reacts. A component from one remote rendered with another remote's copy of React fails with React's invalid hook call error, because hooks are tied to one React instance. Module Federation's shared singletons exist for this, and they reintroduce the version coupling you were escaping.
- Consistency. Design, accessibility and UX drift between teams unless the design system is shared, which is again a coupling.
- Cross-cutting state (auth, cart count, feature flags) needs a contract between apps instead of a hook.
- Framework support. The Module Federation maintainers announced in late 2024 that they intend to end-of-life their Next.js plugin (
nextjs-mf), which targets the Pages Router and refuses App Router builds. App Router federation exists only as experiments and third-party projects. In Next.js, the documented micro-frontend path is Multi-Zones.
My position: reach for organizational problems' solutions in order. Feature boundaries and ownership first. A monorepo with independently built packages next. Route-level split (Multi-Zones) if teams truly must deploy separately, splitting along paths users rarely cross. Runtime federation last, when you've measured that independent deployment is worth the runtime cost. Micro-frontends solve a people problem; if your problem is code structure, they make it worse.
A 12-engineer team on one Next.js app says builds are slow and teams step on each other. A tech lead proposes Module Federation micro-frontends. What's the best first response?
Data-layer boundaries#
The most important boundary in a modern React app isn't between features; it's between the server and the client, and between your components and your data.
On the server, a data access layer (DAL). The production checklist introduced it for security; it's also an architecture rule. One server-only folder (src/data/ or server/) owns the database client, secret reads and authorization, and exports functions that return DTOs: plain objects with only the fields callers may see. Server Components and Server Functions call it; nothing else imports the database. The Next.js security guide recommends exactly this for new projects, and recommends choosing one data approach per app (an existing HTTP API, a DAL, or ad hoc component queries for prototypes) rather than mixing them, so reviewers know what to expect.
import "server-only";
import { cache } from "react";
import { db } from "./db";
import { getViewer } from "./auth";
export type BookDTO = { id: string; title: string; author: string; read: boolean };
export const getReadingList = cache(async (): Promise<BookDTO[]> => {
const viewer = await getViewer(); // throws if signed out
const rows = await db.book.findMany({ where: { listOwnerId: viewer.id } });
return rows.map((r) => ({ id: r.id, title: r.title, author: r.author, read: r.readAt !== null }));
});On the client, one way to talk to the server. Client Components get data as props from Server Components, call Server Functions for mutations, or use a server-state library (TanStack Query, SWR) against an HTTP API for highly interactive screens. Whatever you choose, wrap it in each feature's API module (books.api.ts) so components don't know URLs or response shapes, and validate responses at that boundary. The type annotations on a fetch result are a promise nobody checks; a schema check turns API drift into one clear error at the edge instead of undefined three components deep:
The second call simulates a backend deploy that renamed year to publishedYear. Without the schema, the UI would render "undefined". With it, the failure is caught at the boundary, with the exact path.
import { z } from "zod";
import { fakeFetch } from "guide-tools";
const Book = z.object({
id: z.number(),
title: z.string(),
author: z.string(),
year: z.number().int(),
tags: z.array(z.string()),
});
const BookList = z.array(Book);
type Book = z.infer<typeof Book>; // the type comes from the schema
async function getBooks(simulateDrift = false): Promise<Book[]> {
let data: any = await fakeFetch("/books");
if (simulateDrift) data = data.map(({ year, ...rest }: any) => ({ ...rest, publishedYear: year }));
const result = BookList.safeParse(data);
if (!result.success) {
const first = result.error.issues[0];
throw new Error(`Books API contract broken at [${first.path.join(".")}]: ${first.message}`);
}
return result.data;
}
async function main() {
const books = await getBooks();
console.log("OK:", books.length, "books, first from", books[0].year);
try {
await getBooks(true);
} catch (e) {
console.log((e as Error).message);
}
}
main();API contracts: tRPC, GraphQL, OpenAPI#
That schema was a contract written on the client side only. At scale you want one contract that both sides share, so the compiler catches drift before deploy. The three common options differ in where the contract lives and who can consume it:
| tRPC | GraphQL | OpenAPI (REST) | |
|---|---|---|---|
| Contract | The server's TypeScript router; the client infers types from it | A schema in SDL; clients query fields | A YAML or JSON spec for HTTP endpoints |
| Type safety | End to end, no codegen, TypeScript only | Codegen from schema plus your queries | Codegen of types or clients from the spec |
| Who can call it | Your own TypeScript clients | Any client, any language | Any client, any language |
| Caching | Through TanStack Query on the client | Normalized client caches (Relay, Apollo); HTTP caching is harder because queries are POSTed | Plain HTTP caching and CDNs work naturally |
| Best fit | One team, one monorepo, full-stack TypeScript | Many clients with different data needs over one graph (web, mobile, partners) | Public or cross-team APIs, polyglot backends |
| Watch out for | Coupling client and server deploys; not a public API | Resolver N+1 queries, query cost limits, persisted queries for security | Spec drifting from the implementation unless generated from code |
My positions. Inside one TypeScript monorepo where the same team owns both ends, tRPC (or plain Server Functions in a Next.js app) is the least ceremony with the best type safety. When several clients in different languages consume the API, or it's public, use OpenAPI and generate the client (for example with openapi-typescript). Choose GraphQL when many clients need different shapes of a large, connected domain and you can invest in the server side; don't choose it to avoid writing a few endpoints.
And keep Server Functions in their lane: they're an internal transport between your own React UI and your own server. Their IDs change with every build and their arguments are whatever your component sends, so they're not an API for other teams, mobile apps or partners. Put a real contract (HTTP plus OpenAPI, or GraphQL) in front of anything others consume, and let your Server Functions call the same data layer.
Ownership#
Architecture at scale is mostly about people, so the last boundary is ownership. Every boundary you drew should have a team attached:
- CODEOWNERS maps folders or packages to teams, so the cart team reviews changes to
features/cart/and a change toshared/ui/pulls in the design system owners. - Errors, alerts and performance budgets are tagged by feature, so the cart team gets paged for cart errors. The release tags from the last chapter plus a feature tag (from the route or a boundary) make that possible.
- Architecture decision records (ADRs): short dated notes on why you chose feature folders, tRPC or Multi-Zones, and what would make you change your mind. Six months later they stop the same debate from restarting.
Conway's law says systems end up shaped like the organizations that build them. Use it on purpose: draw code boundaries where team boundaries are, and when the org chart changes, expect to move them.
Pitfalls#
Check your understanding#
The team moves the blast-radius app to feature folders. ProfileForm now gets the cart count through the route, which renders <ProfileForm cartBadge={<CartBadge />} />, and BookCard no longer imports the cart hook: BookList receives an onAddToCart prop from the route. Using the sandbox at the top of the chapter, which files now depend on the cart hook? Edit byLayer to check.
"How would you structure a React codebase that 40 engineers in six teams work on?"
"Your company is adding a mobile app next to the React web app. How do you choose the API contract?"
Interview angle
At scale, the import graph is the architecture, so I make it deliberate. Group code by feature and colocate what changes together. Give each feature a small public API and forbid deep imports. Make dependencies point one way: routes compose features, features use shared code like the design system, and a server-only data access layer returns DTOs. Enforce all of it in CI with lint rules or package exports. Add a monorepo when several apps share code, micro-frontends only when independent deploys are worth the runtime cost, choose API contracts by who consumes them, and attach an owner to every boundary.
Feature-based or layer-based folders? Defend your choice.
How do you keep module boundaries from eroding in a large codebase?
When are micro-frontends worth it, and when do they hurt?
What does a monorepo tool like Turborepo or Nx actually give you?
Where should data access live in a Next.js App Router app?
tRPC, GraphQL or OpenAPI: how do you choose?
Recap#
- Group code by feature, colocate what changes together, and keep a small
shared/that's promoted into only when a second consumer exists. - Give every feature a narrow public API (
index.tsor packageexports) and forbid deep imports, enforced by lint rules or module resolution, not review. - Make dependencies point one way: app composes features, features use shared code, and a server-only data access layer returns DTOs. No upward imports, no cycles.
- Build the design system's styling and API, buy accessible behavior from headless primitives, and treat it as a versioned product.
- Monorepos (pnpm workspaces plus Turborepo or Nx) pay off with several deployables; micro-frontends pay off only when independent deployment is worth real runtime cost, and route-level splits come before runtime federation.
- Choose API contracts by consumer: tRPC or Server Functions inside one TypeScript team, OpenAPI for cross-team and public APIs, GraphQL for many clients over a connected graph. Attach an owner to every boundary.
Sources#
- nextjs.org: Data security (data access layer, DTOs,
server-only) - nextjs.org: Multi-Zones and Project structure (private folders, route groups, colocation)
- Module Federation: Next.js support status
- Turborepo: Configuring tasks
- pnpm: Workspaces
- Nx: Enforce module boundaries
- Node.js: Package entry points (exports)
- tRPC: Documentation, GraphQL: Learn, OpenAPI: Specification
- Zod: Documentation
- Facts checked November 24, 2026.