Lesson 20 of 27Shipping
Next.js Project Structure
Lay out a real Next.js app: route groups or feature folders, a server-only data layer, env validation, linting and monorepos.
Your app now has routes, data, actions and auth. Before you ship it, it needs a layout a team can work in. Next.js only cares about a few folders (app/, public/) and a few files (next.config.ts, proxy.ts). Everything else is up to you, which is why two Next.js codebases can look nothing alike. A clear structure is how a team finds things, keeps secrets on the server, and avoids circular imports. "How would you structure a Next.js app?" is also a favourite system design warm-up.
A real app, top to bottom
Here is a layout used by many production apps: a marketing site and a logged-in product in one codebase, with a typed data layer.
- acme/
- src/
- app/
- layout.tsxroot layout: <html>, fonts, providers
- globals.css
- (marketing)/public pages, own layout (big header, footer)
- layout.tsx
- page.tsx/
- pricing/page.tsx/pricing
- blog/[slug]/page.tsx/blog/:slug
- (app)/logged-in product, own layout (sidebar)
- layout.tsx
- dashboard/
- page.tsx/dashboard
- loading.tsx
- _components/
- RevenueChart.tsxused only by this route
- settings/page.tsx/settings
- api/
- webhooks/stripe/route.ts
- sitemap.ts
- robots.ts
- components/
- ui/design-system primitives (Button, Dialog, Input)
- site-header.tsxshared across routes
- server/data access layer: server-only
- auth.tsverifySession(), getCurrentUser()
- invoices.tsgetInvoices(), createInvoice()
- actions/
- invoices.ts"use server": thin wrappers over server/
- db/
- schema.tsDrizzle or Prisma schema
- index.tsthe database client
- migrations/
- lib/
- utils.tscn(), formatMoney(): safe anywhere
- env.tsvalidated environment variables
- proxy.tsoptimistic redirects, headers
- public/
- logo.svgserved at /logo.svg
- .env.localsecrets for local dev (gitignored)
- next.config.ts
- tsconfig.json"@/*" -> "./src/*"
- package.json
What each part is for:
src/app/holds routing only: pages, layouts, loading and error files, route handlers. Two route groups,(marketing)and(app), give the public site and the product different layouts without changing URLs._components/inside a route keeps components that only that route uses right next to it (colocation). The underscore makes the folder private, so it is never routable.components/holds components shared by many routes.components/ui/is where generated primitives (for example from shadcn/ui) usually live.server/(some teams call itdata/ordal/) is the data access layer: every function that reads or writes the database, each starting with an auth check. Every file imports"server-only".actions/holds Server Actions. Keep them thin: parse theFormData, callserver/, revalidate, redirect.db/holds the schema, the client and migrations. Onlyserver/imports it.lib/holds pure helpers that are safe on both server and client.public/holds static files served from the root URL.
Where does each file belong?
Imports flow one way
The structure works because dependencies point in one direction. Routes depend on components and actions; actions depend on the data layer; only the data layer touches the database.
Pages call server/ directly for reads. They never import db/.
An alternative is feature folders: src/features/invoices/ containing its components, actions and queries together. It scales well for large teams. Either way, keep app/ thin and keep the data layer server-only.
db from @/db to load data on click. What is the best fix?Feature folders, or folders by route?
The tree above organises by layer: all actions together, all data functions together. That is easy to learn and works well up to a few dozen routes. As the app grows, a change to invoices touches app/, actions/, server/ and components/, and four teams edit the same four folders. That is when teams move to feature folders.
- src/
- app/
- (app)/
- invoices/
- page.tsximports from @/features/invoices
- [id]/page.tsx
- _components/
- InvoicesEmptyState.tsxonly this route uses it
- customers/[id]/page.tsxalso shows an invoice list
- features/
- invoices/
- components/
- InvoiceTable.tsxused by two routes
- actions.ts"use server": thin adapters
- queries.tsimport "server-only"
- schema.tsZod schemas, safe anywhere
- customers/
- ...
- components/ui/design system only
The rule that keeps this tidy builds on the colocation habit from App Router Routing: something used by one route lives in that route's _components; something that belongs to a business concept lives in features/<name>, however many routes use it. Routes are URLs, and URLs get renamed in redesigns. Features like "invoices" outlive any URL, so their code should not move when a page does.
Two rules stop feature folders turning into a tangle:
- Features do not reach into each other's internals. If
customersneeds invoice data, it calls a functioninvoicesexports, not a file deep inside it. Some teams add anindex.tsper feature as its public surface; others prefer a lint rule (shown below) so there are no barrel files to slow the bundler. app/stays a thin shell. A page fetches through a feature's query, renders feature components, and passes a feature's action to a form. If a page file is 300 lines, logic has leaked into routing.
Neither layout is "correct". Pick one, write it in the README or AGENTS.md, and enforce it with lint, because a structure only one person remembers is not a structure.
Where server-only code lives
Every module that touches secrets, the database or internal services should start with one line:
import "server-only";
import { db } from "@/db";
import { verifySession } from "@/server/auth";
export async function getInvoicesForCurrentUser() {
const session = await verifySession(); // auth check first
const rows = await db.invoice.findMany({ where: { ownerId: session.userId } }); // Prisma-style
return rows.map(({ id, number, totalCents, status }) => ({ id, number, totalCents, status })); // a DTO, not the raw row
}import "server-only" is a build-time guard. If any Client Component imports this file, even indirectly through three other modules, the build fails with an error naming the chain. Without it, the import would quietly pull your query code, and anything it closes over, into the browser bundle. The mirror image, import "client-only", marks code that touches window or localStorage. Next.js handles both imports itself, so installing the packages is optional (do it if your linter flags unknown imports).
Do not confuse it with "use server". They sound alike and do opposite things:
import "server-only" | "use server" | |
|---|---|---|
| What it does | Fails the build if the module reaches the client | Turns every exported async function into a Server Action |
| Who can call the functions | Only other server code | Anyone who can send a POST to your site |
| Where it belongs | The data access layer, queries, secrets, SDK clients | Thin action files that validate input, then call the data layer |
The classic mistake is putting "use server" at the top of the data layer "to keep it on the server". That publishes every exported function, including deleteAllInvoicesForTenant, as a callable endpoint. The data layer gets server-only; only the action files get "use server". What goes inside the data layer (DTOs, transactions, auth checks per query) is covered in Databases and the Data Access Layer, and the attack side in Securing a Next.js App.
One more file deserves the guard: your validated env.ts. If it parses server secrets and a Client Component imports it for NEXT_PUBLIC_SITE_URL, the secrets are in the bundle. Split it into env.server.ts (with server-only) and env.client.ts (public values only).
"use server" to the top of src/server/invoices.ts, the data access layer, so that it never runs in the browser. What is the real effect?next.config.ts
The config file is TypeScript, typed with NextConfig. Most apps only set a handful of options:
import type { NextConfig } from "next";
const nextConfig: NextConfig = {
cacheComponents: true, // use cache, partial prerendering (on in new apps)
images: {
remotePatterns: [new URL("https://cdn.acme.dev/**")],
},
async redirects() {
return [{ source: "/docs/old", destination: "/docs/new", permanent: true }];
},
output: "standalone", // for Docker; see the deploying lesson
};
export default nextConfig;Environment variables
Next.js loads .env files automatically. When the same variable is defined in several places, the first one found wins, in this order:
Order these sources from highest priority (checked first) to lowest, for next dev.
- Tap the steps below in the right order.
The most important rule: only variables prefixed with NEXT_PUBLIC_ reach the browser, and they are inlined into the JavaScript at build time. Everything else exists only on the server.
Press Run (⌘ Enter) to see what happens.Two consequences. Never put a secret in a NEXT_PUBLIC_ variable: it ships to every visitor. And because public values are baked in at build time, changing NEXT_PUBLIC_SITE_URL on a running server (or a promoted Docker image) does nothing until you rebuild. Server-only variables can be read at runtime.
NEXT_PUBLIC_API_URL differently in each. What does browser code see in production?Validate them once
A missing DATABASE_URL should fail at startup, not on a user's request. Validate the environment in one module with Zod and import the typed result everywhere:
import * as z from "zod";
const schema = z.object({
DATABASE_URL: z.url(),
AUTH_SECRET: z.string().min(32),
NEXT_PUBLIC_SITE_URL: z.url(),
});
export const env = schema.parse(process.env); // throws with a clear message if anything is wrongLibraries such as @t3-oss/env-nextjs add a split between server and client variables so you cannot accidentally read a secret in client code.
TypeScript path aliases
Deep relative imports like ../../../../components/ui/button break whenever files move. create-next-app configures an alias in tsconfig.json, and Next.js (Turbopack) understands it without extra setup:
{
"compilerOptions": {
"strict": true,
"paths": { "@/*": ["./src/*"] }
}
}Press Run (⌘ Enter) to see what happens.What does this print?
const key = "@/*", target = "./src/*";
const spec = "@/lib/utils";
const prefix = key.slice(0, -1);
console.log(target.replace("*", spec.slice(prefix.length)));Linting with the ESLint CLI
Next.js 16 removed the next lint command, and next build no longer runs a linter. If your CI only runs next build, nothing is linting your code any more. Projects now call ESLint (or another linter such as Biome) directly, using ESLint's flat config file:
import { defineConfig, globalIgnores } from "eslint/config";
import nextVitals from "eslint-config-next/core-web-vitals";
import nextTs from "eslint-config-next/typescript";
export default defineConfig([
...nextVitals, // Next.js, React and Hooks rules; CWV issues are errors
...nextTs, // typescript-eslint rules
{
// Enforce the layers: routes and UI never touch the database client
files: ["src/app/**", "src/components/**", "src/features/*/components/**"],
rules: {
"no-restricted-imports": ["error", {
patterns: [{ group: ["@/db", "@/db/*"], message: "Read data through the data access layer." }],
}],
},
},
globalIgnores([".next/**", "out/**", "build/**", "next-env.d.ts"]),
]);eslint-config-next is the base set; /core-web-vitals upgrades rules that hurt loading performance (like a raw <img> or a synchronous script) from warnings to errors; /typescript adds typescript-eslint. Each export is an array of config objects, which is why you spread them. Later objects override earlier ones, so your own rules go after the presets.
Then add the commands to package.json and run them in CI:
{
"scripts": {
"lint": "eslint .",
"typecheck": "next typegen && tsc --noEmit"
}
}Migrating an older repo? There is a codemod, npx @next/codemod@canary next-lint-to-eslint-cli ., and you can delete the eslint key from next.config.ts, which no longer does anything. A legacy .eslintrc.json should become eslint.config.mjs; check the ESLint migration guide for plugins that have not moved to flat config.
The no-restricted-imports block is the most valuable part of the file. It turns the arrows in the layer diagram from a team agreement into a build error. Here is the same idea as a tiny checker:
Press Run (⌘ Enter) to see what happens.What does this print?
const allowed = ["src/server/"]; const files = ["src/server/a.ts", "src/app/page.tsx", "src/serverless/x.ts"]; console.log(files.filter((f) => !allowed.some((d) => f.startsWith(d))).length);
Monorepo layout
Once a company has a second Next.js app (an admin panel, a docs site) or wants one design system across products, the repo becomes a monorepo: several apps and shared packages in one git repository, linked by the package manager's workspaces and usually driven by Turborepo or Nx.
- acme/
- apps/
- web/the product
- next.config.ts
- package.json"@acme/ui": "workspace:*"
- src/app/...
- admin/a second Next.js app
- packages/
- ui/shared components
- package.json"name": "@acme/ui"
- src/button.tsx"use client" at the top
- db/schema, client, import "server-only"
- eslint-config/shared flat config arrays
- typescript-config/shared tsconfig bases
- pnpm-workspace.yamlapps/*, packages/*
- pnpm-lock.yamlone lockfile: the repo root
- turbo.jsontask graph and caching
Each app imports shared code by package name (import { Button } from "@acme/ui"), exactly as it would a package from npm. Turborepo runs tasks in dependency order and caches their outputs, so CI only rebuilds and retests what a change actually affected:
{
"tasks": {
"build": { "dependsOn": ["^build"], "outputs": [".next/**", "!.next/cache/**"] },
"lint": {},
"typecheck": {}
}
}The Next.js specifics that bite people:
- Compiling shared packages. Turbopack compiles workspace packages for you, so
packages/uican ship plain.tsxsource. You only needtranspilePackagesfor a package innode_modulesthat ships raw TypeScript, or for some webpack setups. Shipping source also keeps each file's"use client"directive intact; a bundler that pre-builds the package into one file can strip or merge those directives. - One React. If two packages resolve different copies of
react, you get "Invalid hook call" errors at runtime. Keep React as apeerDependencyof shared packages and installed once by the apps. - No app aliases in packages.
@/means "this app'ssrc/". Insidepackages/uiit would point somewhere different in every app. Use relative imports or the package's own name. - Boundaries still apply.
packages/dbgetsimport "server-only". A shared UI package must never import it, and the lint rule above works across packages too. - Roots and tracing. Next.js finds the workspace root from the lockfile, which is why it should live at the repo root. For
output: "standalone"builds, setoutputFileTracingRootto the repo root so files frompackages/are included in the output. - Per-app commands. Run
next typegen ./apps/webor filter tasks to one app (pnpm --filter web dev) rather than building everything.
A monorepo is not free. Install times, CI configuration and tooling upgrades are now shared problems, and one broken package can block every app. It pays off when code is truly shared and teams release together; two unrelated apps are often simpler as two repos.
packages/ui/src/card.tsx imports @/lib/utils. It works in apps/web but breaks in apps/admin. Why?Fail fast on bad environment variables
Apps validate process.env once at startup (often in env.ts with Zod) so a missing variable fails the build, not a user's request. Write validateEnv(env) that returns a list of error messages, in this order:
DATABASE_URL: missing →"DATABASE_URL is required"; present but not starting withpostgres://orpostgresql://→"DATABASE_URL must be a Postgres URL"AUTH_SECRET: missing or shorter than 32 characters →"AUTH_SECRET must be at least 32 characters"NEXT_PUBLIC_SITE_URL: missing →"NEXT_PUBLIC_SITE_URL is required"; present but not starting withhttps://orhttp://localhost→"NEXT_PUBLIC_SITE_URL must use https"- Then, for every key that starts with
NEXT_PUBLIC_and containsSECRET, in alphabetical order:"<KEY> would leak a secret to the browser"
An empty string counts as missing. Return [] when everything is fine.
Resolve TypeScript path aliases
create-next-app sets "paths": { "@/*": ["./src/*"] } in tsconfig.json, so import { db } from "@/lib/db" works from any folder. Write resolveAlias(specifier, paths).
- A key ending in
/*matches any specifier that starts with the part before*; the rest replaces the*in the first target. - A key without
*matches only that exact specifier. - If several keys match, use the one with the longest prefix.
- Strip a leading
./from the result. Returnnullwhen nothing matches (a package such asreact).
paths = { "@/*": ["./src/*"], "@ui/*": ["./src/components/ui/*"] }
resolveAlias("@/lib/db", paths) → "src/lib/db"
resolveAlias("@ui/button", paths) → "src/components/ui/button"
resolveAlias("react", paths) → null- colocation
- Keeping files that only one route uses inside that route's folder, often in a private
_componentsfolder. - data access layer
- A
server-onlymodule that owns every database read and write and checks auth in each function. - NEXT_PUBLIC_
- The prefix that exposes an environment variable to browser code by inlining its value at build time.
- .env.local
- A gitignored file for local secrets. It overrides
.envand.env.developmentbut not real environment variables. - path alias
- A
tsconfig.jsonpathsentry like@/*that maps short import specifiers to folders. - feature folder
- A folder per business concept (
features/invoices) holding its components, actions, queries and schemas together. - server-only
- An import that fails the build if a module reaches client code. Different from
"use server", which creates public Server Actions. - flat config
- ESLint's
eslint.config.mjsformat: an array of config objects, later ones overriding earlier ones. - monorepo
- One repository holding several apps and shared packages, linked by workspaces and usually run with Turborepo or Nx.