Team conventions for Next.js App Router apps: Server Components and the client boundary, page and layout data loading, feature folders and layer order, interrupts, error boundaries and route handler errors. Use when writing, fixing or reviewing a page, layout, route handler or service. Server actions, logging and env have their own skills. Background knowledge that agents preload; not a command.
Installs into .claude/skills of the current project.
Sponsors
SSkills DirectorySkills Directory
Know which skills are safe — weekly.
SSkills DirectorySkills Directory
Is that skill safe to install?
Are you the author of Nextjs Rules?
Add the live security badge to your README. It updates with every re-scan.
[](https://www.skillsdirectory.com/skills/janszewczyk-nextjs-rules)
---
name: nextjs-rules
description: "Team conventions for Next.js App Router apps: Server Components and the client boundary, page and layout data loading, feature folders and layer order, interrupts, error boundaries and route handler errors. Use when writing, fixing or reviewing a page, layout, route handler or service. Server actions, logging and env have their own skills. Background knowledge that agents preload; not a command."
user-invocable: false
---
<!-- generated by knowledge.mjs from 38 note(s) (sha256 ea8ec607a1b7); edit the notes in knowledge/, then run build -->
# Next.js rules
Apply these rules to every Next.js file you write or review. TypeScript style and error handling ([error, data] tuples, ServiceError) are in `typescript-rules`, React in `react-rules`. Server actions are in `nextjs-server-action-rules`, logging in `loglayer-rules`, environment variables in `env-rules`: load the one the task touches with the Skill tool if it is not preloaded. The first section is always in force; open a rule from the table when the task touches it. Procedures to set up env validation, logging, the ServiceError class or toasts are in `setup-app-infrastructure`.
## Always apply (critical)
### Mark server modules with import "server-only" and never import server/ from client code
_critical · typescript, react, nextjs_
**Rule.** Start every module in `features/{domain}/server/` that is not a `"use server"` action file (services, db, api, `permissions.ts`) with `import "server-only"`. Never import anything from `server/` in a `"use client"` file or in a module a client file imports; client code takes types from `types/` and actions as props.
**Why.** A server module reached from client code ships its queries, internal rules and whatever it reads to the browser bundle, and without the `server-only` marker the build succeeds, so the leak is found only by someone reading the shipped JavaScript.
**Incorrect:**
```ts
"use client";
import { InvoiceStatus } from "~/features/invoices/server/db/schema";
import { formatTotal } from "~/features/invoices/server/services/invoice.service";
```
**Correct:**
```ts
// features/invoices/server/services/invoice.service.ts
import "server-only";
// features/invoices/components/invoice-row.tsx ("use client")
import { InvoiceStatus, type ClientInvoiceListItem } from "~/features/invoices/types";
```
### Return a fixed user-safe message to the client, never the internal error text
_critical · typescript, react, nextjs_
**Rule.** Put only a message you wrote for the user in an action's `error`, a route handler's JSON body or a toast. Log the caught error on the server with `log.withError(error)` and its ids; never send `error.message`, a stack, an error code from a driver, or record ids and roles in the message.
**Why.** A raw message leaks table names, SQL fragments, internal hostnames or another user's data to whoever submits the form, and the toast cookie is readable by any script on the page.
**Incorrect:**
```ts
if (error) {
return { success: false, error: error.message }; // 'duplicate key value violates "budgets_name_key"'
}
```
**Correct:**
```ts
if (error) {
log.withError(error).withMetadata({ userId, operation: "createBudget" }).error("Budget creation failed");
return { success: false, error: "Could not create the budget" };
}
```
**Exceptions.** A `ServiceError` built by your own code for a validation or business rule (`ServiceError.validation("You can have at most 20 budgets")`) carries a message written for the user and may be returned as is.
### Check the session first in the loadData of every protected page
_critical · typescript, react, nextjs_
**Rule.** Make the session check the first statement of the `loadData` of every protected page, and of any layout `loadData` that reads user data, before any read. Do not count a guard in a parent layout or in `proxy.ts` as the page's guard.
**Why.** A page that relies on its layout's guard serves its data to a signed-out user: layouts do not re-render on client navigation and do not stop child segments from rendering, and a proxy check only reads the cookie optimistically.
**Incorrect:**
```tsx
// app/(app)/layout.tsx guards the group, so the page skips it
async function loadData(invoiceId: string) {
const [error, invoice] = await getInvoice(invoiceId);
if (error?.isNotFound) notFound();
if (error) throw new Error("Failed to load the invoice", { cause: error });
return { invoice };
}
```
**Correct:**
```tsx
async function loadData(invoiceId: string) {
const { isAuthenticated, userId } = await auth();
if (!isAuthenticated) unauthorized();
const [error, invoice] = await getInvoice(userId, invoiceId);
if (error?.isNotFound || error?.isPermissionDenied) notFound();
if (error) throw new Error("Failed to load the invoice", { cause: error });
return { invoice };
}
```
**Exceptions.** A public page (one `proxy.ts` lets through) has no guard unless the data it reads belongs to a user. Without `experimental.authInterrupts`, call `redirect("/sign-in")` instead of `unauthorized()`.
## Read when the task touches it
| Impact | Rule | Applies to |
| --- | --- | --- |
| high | [Guard a service mutation in a fixed order: role, profile, permission, then write](references/rules.md#guard-a-service-mutation-in-a-fixed-order-role-profile-permission-then-write) — Each guard returns its error tuple at once, so the write runs only after every check passed. | typescript, react, nextjs |
| high | [Write every component as a Server Component unless it needs the browser](references/rules.md#write-every-component-as-a-server-component-unless-it-needs-the-browser) — No directive by default; a component becomes a Client Component only for state, effects, event handlers or browser APIs. | typescript, react, nextjs |
| high | [Fetch data in a Server Component and pass it down, not in a client effect](references/rules.md#fetch-data-in-a-server-component-and-pass-it-down-not-in-a-client-effect) — The server parent awaits the data and passes it as props; no useEffect plus fetch in a Client Component. | typescript, react, nextjs |
| high | [Structure a Next.js app as feature folders with a server-only core](references/rules.md#structure-a-nextjs-app-as-feature-folders-with-a-server-only-core) — features/{domain}/ per business area; server/ layered action, service, permissions, db; types/ the only bridge. | typescript, react, nextjs |
| high | [Import feature layers in one direction: action, then service, then db or api](references/rules.md#import-feature-layers-in-one-direction-action-then-service-then-db-or-api) — Each server layer imports only the layers below it; types/ is importable everywhere and imports nothing. | typescript, react, nextjs |
| high | [Put each domain's code in one features/{domain} folder, layered inside](references/rules.md#put-each-domains-code-in-one-featuresdomain-folder-layered-inside) — features/{domain}/ holds components, schemas, types, server and test builders; app/ routes only import from it. | typescript, react, nextjs |
| high | [Give a Client Component a server action, never a plain function, from the server](references/rules.md#give-a-client-component-a-server-action-never-a-plain-function-from-the-server) — A callback that crosses from a Server to a Client Component is a 'use server' function; plain functions cannot cross. | typescript, react, nextjs |
| high | [Pass server-rendered content into a Client Component as children, not as an import](references/rules.md#pass-server-rendered-content-into-a-client-component-as-children-not-as-an-import) — A client wrapper takes children or slot props; the server parent fills them, so the content stays on the server. | typescript, react, nextjs |
| high | [Write a feature's access checks as canDoX functions in a server-only permissions.ts](references/rules.md#write-a-features-access-checks-as-candox-functions-in-a-server-only-permissionsts) — permissions.ts holds every canDoX guard as a tuple; services and actions call it, nobody rewrites the rule. | typescript, react, nextjs |
| high | [Put 'use client' on the smallest interactive component, not on its parent](references/rules.md#put-use-client-on-the-smallest-interactive-component-not-on-its-parent) — Extract the button, input or toggle into its own client file; the page or layout around it stays on the server. | typescript, react, nextjs |
| high | [Open transactions in the service and pass the client into db functions](references/rules.md#open-transactions-in-the-service-and-pass-the-client-into-db-functions) — Db functions take one object argument with an optional client; the service owns the transaction and the rollback. | typescript, react, nextjs |
| high | [Share types with client code only through the feature's types/ folder](references/rules.md#share-types-with-client-code-only-through-the-features-types-folder) — DTOs, view, filter and closed-set types live in types/; persistence row types stay in server/db/schema.ts. | typescript, react, nextjs |
| high | [Add a root app/error.tsx that reports the error with its digest and offers retry](references/rules.md#add-a-root-apperrortsx-that-reports-the-error-with-its-digest-and-offers-retry) — The boundary reports the error with its digest and shows a generic message and a retry button. | typescript, react, nextjs |
| high | [Deny access with notFound in pages, forbidden in actions, unauthorized when signed out](references/rules.md#deny-access-with-notfound-in-pages-forbidden-in-actions-unauthorized-when-signed-out) — A page hides that the resource exists; an action refuses with 403; a missing session gets unauthorized(). | typescript, react, nextjs |
| high | [Call redirect, notFound, forbidden and unauthorized outside try, or rethrow them](references/rules.md#call-redirect-notfound-forbidden-and-unauthorized-outside-try-or-rethrow-them) — These interrupts work by throwing; a surrounding catch swallows them and the navigation never happens. | typescript, react, nextjs |
| high | [Throw an unexpected loadData failure to error.tsx; keep notFound() for missing or hidden](references/rules.md#throw-an-unexpected-loaddata-failure-to-errortsx-keep-notfound-for-missing-or-hidden) — In a page's loadData only a missing or hidden resource is a 404; an outage throws so the error boundary shows it. | typescript, react, nextjs |
| high | [Choose how a Next.js route loads data, guards access and renders chrome](references/rules.md#choose-how-a-nextjs-route-loads-data-guards-access-and-renders-chrome) — Pages own guard, reads and failure responses in loadData; layouts render chrome and read only what it needs. | typescript, react, nextjs |
| high | [Keep page.tsx and layout.tsx Server Components, never "use client"](references/rules.md#keep-pagetsx-and-layouttsx-server-components-never-use-client) — Routes stay on the server so they can guard and load data; interactivity moves into a client leaf they render. | typescript, react, nextjs |
| high | [Load only chrome data in a layout's loadData; page data stays in the page](references/rules.md#load-only-chrome-data-in-a-layouts-loaddata-page-data-stays-in-the-page) — A layout reads what its navigation, header and sidebar show; anything one page needs is read by that page. | typescript, react, nextjs |
| high | [Load a page's or layout's data in one loadData function, never in the component body](references/rules.md#load-a-pages-or-layouts-data-in-one-loaddata-function-never-in-the-component-body) — A module-level async loadData holds the guard, the reads and the failure responses; the component awaits it once. | typescript, react, nextjs |
| high | [Return a fallback title from generateMetadata instead of throwing or redirecting](references/rules.md#return-a-fallback-title-from-generatemetadata-instead-of-throwing-or-redirecting) — loadData owns the guard and every failure response; generateMetadata only reads, through the same cached call. | typescript, react, nextjs |
| high | [Parse and validate search params in loadData, never in components](references/rules.md#parse-and-validate-search-params-in-loaddata-never-in-components) — loadData turns raw query strings into typed, defaulted values; components only receive the parsed result. | typescript, react, nextjs |
| medium | [Wrap service reads in React cache and give them primitive arguments](references/rules.md#wrap-service-reads-in-react-cache-and-give-them-primitive-arguments) — loadData, generateMetadata and layouts then share one read per request; an object argument misses the cache. | typescript, react, nextjs |
| medium | [Do one read or one write per db function and compose them in the service](references/rules.md#do-one-read-or-one-write-per-db-function-and-compose-them-in-the-service) — queries.ts and mutations.ts hold single operations that never call each other; multi-step work is a service's job. | typescript, react, nextjs |
| medium | [Import feature code from its sub-path, never from a feature-root barrel](references/rules.md#import-feature-code-from-its-sub-path-never-from-a-feature-root-barrel) — No features/{domain}/index.ts and no server/index.ts; only components/, types/ and server/db/ have an index. | typescript, react, nextjs |
| medium | [Put a db operation that several features need in features/shared, not in each feature](references/rules.md#put-a-db-operation-that-several-features-need-in-featuresshared-not-in-each-feature) — An entity with no single owner gets one set of operations in features/shared/server/db/{entity}/. | typescript, react, nextjs |
| medium | [Answer a route handler failure with a JSON error body and the matching status](references/rules.md#answer-a-route-handler-failure-with-a-json-error-body-and-the-matching-status) — Map the ServiceError code to an HTTP status and return { error } as JSON; never let the handler throw. | typescript, react, nextjs |
| medium | [Await params and searchParams once at the top and pass plain values down](references/rules.md#await-params-and-searchparams-once-at-the-top-and-pass-plain-values-down) — The page or layout awaits the route promises itself; loadData and components receive strings, never a promise. | typescript, react, nextjs |
| medium | [Compose a page from feature components, with no PageContent wrapper](references/rules.md#compose-a-page-from-feature-components-with-no-pagecontent-wrapper) — Page JSX only arranges components from features/{domain}/components; no business logic, no route-local components. | typescript, react, nextjs |
| medium | [Keep a layout that reads no data synchronous, with no loadData](references/rules.md#keep-a-layout-that-reads-no-data-synchronous-with-no-loaddata) — A layout only wraps children unless its chrome needs data; auth for its pages is checked in each page, not here. | typescript, react, nextjs |
| medium | [Let non-critical chrome data fail silently, with the chrome degrading](references/rules.md#let-non-critical-chrome-data-fail-silently-with-the-chrome-degrading) — A badge or counter that fails to load is logged and left out; it never sends the whole route to an error page. | typescript, react, nextjs |
| medium | [Wire server actions into client components from the page, as props](references/rules.md#wire-server-actions-into-client-components-from-the-page-as-props) — The page or layout imports the action and passes it down; a client component never imports from server/actions. | typescript, react, nextjs |
| medium | [Render chrome inline in page.tsx when it depends on the page's own data](references/rules.md#render-chrome-inline-in-pagetsx-when-it-depends-on-the-pages-own-data) — Skip layout.tsx for a lone route or chrome built from the page's resource; the page renders header and footer itself. | typescript, react, nextjs |
| medium | [Type pages and layouts with the generated PageProps and LayoutProps helpers](references/rules.md#type-pages-and-layouts-with-the-generated-pageprops-and-layoutprops-helpers) — Route-generated helpers keep params, searchParams and slots in step with the folders; no hand-written prop types. | typescript, react, nextjs |
| medium | [Export static metadata unless the title needs data from the route](references/rules.md#export-static-metadata-unless-the-title-needs-data-from-the-route) — List and fixed pages export a metadata object; only detail pages under a [param] segment use generateMetadata. | typescript, react, nextjs |