Skip to content

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.

24 min read0/8 questions

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.

A SaaS app
  • 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 it data/ or dal/) 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 the FormData, call server/, revalidate, redirect.
  • db/ holds the schema, the client and migrations. Only server/ imports it.
  • lib/ holds pure helpers that are safe on both server and client.
  • public/ holds static files served from the root URL.
Match the pairs0/5 matched

Where does each file belong?

Choose an item, then its match on the other side.

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.

Layers of a Next.js app
  1. app/ (routes, layouts, route handlers)Server Components render pages and call the data layer
  2. components/ (UI)Mostly presentational; Client Components only where needed
  3. actions/ ("use server")Parse input, call server/, revalidate, redirect
  4. server/ (data access layer)import "server-only"; verify session; authorize; return DTOs
  5. db/ (schema + client)Only server/ imports this

Pages call server/ directly for reads. They never import db/.

1/4

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.

Quick check
A Client Component imports db from @/db to load data on click. What is the best fix?
Need a nudge? A hint rules out a wrong answer.

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.

Feature folders with a thin app/
  • 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 customers needs invoice data, it calls a function invoices exports, not a file deep inside it. Some teams add an index.ts per 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:

src/features/invoices/queries.ts
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 doesFails the build if the module reaches the clientTurns every exported async function into a Server Action
Who can call the functionsOnly other server codeAnyone who can send a POST to your site
Where it belongsThe data access layer, queries, secrets, SDK clientsThin 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).

Quick check
A teammate adds "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?
Need a nudge? A hint rules out a wrong answer.

next.config.ts

The config file is TypeScript, typed with NextConfig. Most apps only set a handful of options:

next.config.ts
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:

Put it in order5 steps

Order these sources from highest priority (checked first) to lowest, for next dev.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

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.

TypeScriptpublic-inlining.ts
// What `next build` effectively does to client codeconst env = { NEXT_PUBLIC_SITE_URL: "https://acme.dev", STRIPE_SECRET_KEY: "sk_live_123" };const clientSource = `fetch(process.env.NEXT_PUBLIC_SITE_URL + "/api"); key = process.env.STRIPE_SECRET_KEY;`; const built = clientSource.replace(/process\.env\.(\w+)/g, (_, name: string) => name.startsWith("NEXT_PUBLIC_") ? JSON.stringify(env[name as keyof typeof env]) : '""',);console.log(built);
Output
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.

Quick check
You build one Docker image and deploy it to staging and production, setting NEXT_PUBLIC_API_URL differently in each. What does browser code see in production?
Need a nudge? A hint rules out a wrong answer.

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:

src/env.ts
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 wrong

Libraries 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:

tsconfig.json
{
  "compilerOptions": {
    "strict": true,
    "paths": { "@/*": ["./src/*"] }
  }
}
TypeScriptalias.ts
const paths: Record<string, string> = { "@/*": "./src/*" }; function resolve(spec: string) { for (const [key, target] of Object.entries(paths)) { const prefix = key.slice(0, -1); // "@/" if (spec.startsWith(prefix)) return target.replace("*", spec.slice(prefix.length)); } return `${spec} (a package from node_modules)`;} console.log(resolve("@/components/ui/button"));console.log(resolve("@/server/invoices"));console.log(resolve("react"));
Output
Press Run (⌘ Enter) to see what happens.
Predict the outputTypeScript

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)));
Need a nudge? Hints walk you through it.

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:

eslint.config.mjs
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:

package.json
{
  "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:

TypeScriptlayer-check.ts
// Which folders may import each layerconst allowed: Record<string, string[]> = { "@/db": ["src/server/", "src/features/"], "@/server": ["src/app/", "src/actions/", "src/server/", "src/features/"],}; const imports: [string, string][] = [ ["src/server/invoices.ts", "@/db"], ["src/app/(app)/dashboard/page.tsx", "@/server/invoices"], ["src/app/(app)/dashboard/page.tsx", "@/db"], ["src/components/InvoiceRow.tsx", "@/server/invoices"], ["src/actions/invoices.ts", "@/server/invoices"],]; for (const [file, spec] of imports) { const layer = Object.keys(allowed).find((l) => spec === l || spec.startsWith(l + "/")); if (!layer) continue; const ok = allowed[layer].some((dir) => file.startsWith(dir)); console.log(ok ? "ok " : "FAIL", file, "->", spec);}
Output
Press Run (⌘ Enter) to see what happens.
Predict the outputTypeScript

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);
Need a nudge? Hints walk you through it.

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.

A pnpm + Turborepo monorepo
  • 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:

turbo.json
{
  "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/ui can ship plain .tsx source. You only need transpilePackages for a package in node_modules that 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 a peerDependency of shared packages and installed once by the apps.
  • No app aliases in packages. @/ means "this app's src/". Inside packages/ui it would point somewhere different in every app. Use relative imports or the package's own name.
  • Boundaries still apply. packages/db gets import "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, set outputFileTracingRoot to the repo root so files from packages/ are included in the output.
  • Per-app commands. Run next typegen ./apps/web or 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.

Quick check
packages/ui/src/card.tsx imports @/lib/utils. It works in apps/web but breaks in apps/admin. Why?
Need a nudge? A hint rules out a wrong answer.
ChallengeMedium

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:

  1. DATABASE_URL: missing → "DATABASE_URL is required"; present but not starting with postgres:// or postgresql:// → "DATABASE_URL must be a Postgres URL"
  2. AUTH_SECRET: missing or shorter than 32 characters → "AUTH_SECRET must be at least 32 characters"
  3. NEXT_PUBLIC_SITE_URL: missing → "NEXT_PUBLIC_SITE_URL is required"; present but not starting with https:// or http://localhost → "NEXT_PUBLIC_SITE_URL must use https"
  4. Then, for every key that starts with NEXT_PUBLIC_ and contains SECRET, in alphabetical order: "<KEY> would leak a secret to the browser"

An empty string counts as missing. Return [] when everything is fine.

TypeScript
function validateEnv(env: Record<string, string>): string[] { const errors: string[] = []; return errors;}
ChallengeEasy

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. Return null when nothing matches (a package such as react).
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
TypeScript
function resolveAlias(specifier: string, paths: Record<string, string[]>): string | null { return null;}
Key terms
colocation
Keeping files that only one route uses inside that route's folder, often in a private _components folder.
data access layer
A server-only module 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 .env and .env.development but not real environment variables.
path alias
A tsconfig.json paths entry 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.mjs format: 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.