Skip to content
Tutorials Center
My learning

Topics

Lesson 72 of 72 ยท Practice and Interviews

Next.js Cheat Sheet

A compact Next.js App Router cheat sheet: commands, special files, nesting order, directives, navigation hooks, caching APIs, Server Actions, metadata and config options.

This is the page to keep open in a second tab. It does not replace the lessons: every section links to the one that explains the idea in full. Think of it as a map. You will already know most entries, and when you do not, you will know where to read.

It targets the App Router in Next.js 15 and 16. Where the two versions differ, the table says so. Everything here is read-only reference, and two small runnable stand-ins at the end show how special files nest and how to choose a revalidation API.

What is on this page

Files Special files and nesting order.
Directives use client, use server, use cache.
Caching Functions that store and clear data.
Config Commands, next.config, env files.

Scan the tables, then follow the links.

1 / 2

Commands

Command What it does
npx create-next-app@latest my-app Creates a project and asks about TypeScript, linting, Tailwind, src/ and the import alias
next dev Development server with fast refresh and the error overlay
next build Production build. Prints each route with its rendering type
next start Starts the production server after a build
next typegen Generates route and props types without a full build
next info Prints versions and environment details for bug reports
npx @next/codemod@latest upgrade latest Upgrades Next.js and runs the codemods for breaking changes

Turbopack is the default bundler in version 16 (--webpack opts out). The old next lint command was removed in 16: run ESLint directly. See Creating a Next.js App and Building and Deploying.

Special files and folders

File or folder Purpose
page.tsx Makes a segment publicly reachable
layout.tsx Shared UI that persists across navigations. The root layout contains <html> and <body>
template.tsx Like a layout, but a new instance on every navigation
loading.tsx Fallback shown through a Suspense boundary while the segment loads
error.tsx Error boundary for the segment (a Client Component with reset)
global-error.tsx Last-resort boundary that replaces the root layout
not-found.tsx UI for notFound() and unmatched URLs
default.tsx Fallback for a parallel-route slot after a hard navigation
route.ts Route Handler (HTTP endpoint). Cannot sit next to page.tsx
proxy.ts Runs before routing, in the project root or src/ (middleware.ts before version 16)
instrumentation.ts Runs once at server start: tracing, monitoring
sitemap.ts, robots.ts, manifest.ts Generate those files
icon, apple-icon, opengraph-image, twitter-image Icon and share-image files
Folder syntax Meaning
blog/ URL segment /blog
[slug] One dynamic segment
[...slug] One or more segments
[[...slug]] Zero or more segments
(marketing) Route group: no effect on the URL
_components Private folder: ignored by routing
@modal Named slot for a parallel route
(.)photo, (..)photo, (...)photo Intercepting route: same level, one level up, from the root

More in Project Structure, Route Groups and Private Folders and Parallel and Intercepting Routes.

How the files nest

In each segment, Next.js wraps the segment's children in this order, outermost first:

Order Wrapper File
1 Layout layout.tsx
2 Template template.tsx
3 Error boundary error.tsx
4 Suspense boundary loading.tsx
5 Not-found boundary not-found.tsx
6 Page or the next segment page.tsx

An error.tsx catches errors from its own page and the segments below it, but not from the layout in the same segment: put a boundary one level up for that. See loading.tsx, error.tsx and not-found.tsx.

Directives

Directive Where Meaning
'use client' Top of a file Boundary: this file and its imports go in the client bundle
'use server' Top of a file, or first line of a function Marks Server Actions: public endpoints that run on the server
'use cache' Top of a file, component or function Caches the result (needs Cache Components, cacheComponents: true)
import 'server-only' Inside a module Build error if a Client Component imports it
import 'client-only' Inside a module Build error if server code imports it

Rules of thumb: add 'use client' only for state, effects, event handlers and browser APIs. Only serializable props cross from server to client. See Client Components and "use client" and Keeping Server Code on the Server.

API Import from Notes
<Link href> next/link Client navigation and prefetching, renders a real <a>
useRouter() next/navigation push, replace, back, refresh, prefetch. Client only
usePathname() next/navigation Current path, for active links
useSearchParams() next/navigation Read-only query string in Client Components
useParams() next/navigation Dynamic route params in Client Components
useSelectedLayoutSegment(s) next/navigation Active child segment below a layout
useLinkStatus() next/link Pending state of a <Link> navigation
redirect(url) next/navigation Throws. Do not wrap it in try/catch
permanentRedirect(url) next/navigation Same, with a 308 status
notFound() next/navigation Throws and renders the nearest not-found
cookies(), headers() next/headers Async since 15. Reading them makes a route dynamic
draftMode() next/headers Preview unpublished content
connection() next/server Waits for a real request before continuing
after(callback) next/server Runs work after the response is sent

See Linking and Navigation, Search Params and Navigation Hooks and Cookies and Headers.

Data and caching

API Use it for
await fetch(url) Uncached by default since version 15
fetch(url, { cache: 'force-cache' }) Store the response in the data cache
fetch(url, { next: { revalidate: 60, tags: ['posts'] } }) Time-based refresh and tagging
cache(fn) from react Deduplicate calls within one request (memoization)
'use cache' Cache a function, component or file (Cache Components)
cacheLife('hours') Lifetime profile: seconds, minutes, hours, days, weeks, max, or a custom one
cacheTag('posts') Label cached data so it can be cleared
revalidatePath('/blog') Invalidate a route
revalidateTag('posts', 'max') Invalidate by tag. Version 16 wants a cache profile and refreshes in the background
updateTag('posts') Expire a tag so the next read is fresh. Server Actions only
refresh() Refresh uncached data after an action. Server Actions only
export const dynamic = 'force-dynamic' Segment config. Not allowed when Cache Components is on
export const revalidate = 3600 Segment config. Not allowed when Cache Components is on
generateStaticParams() Prerender dynamic routes at build time

The classic cache layers are request memoization, the data cache, the full route cache and the router cache. See Caching in Next.js, The use cache Directive and Revalidating Data.

Mutations, handlers and proxy

Task Pattern
Form that mutates data <form action={serverAction}> with FormData
Pending state useFormStatus() inside the form, or the third value of useActionState
Field errors from an action const [state, formAction, pending] = useActionState(action, initial)
Instant feedback useOptimistic(value, reducer)
After a successful action revalidatePath / updateTag, then redirect
HTTP endpoint export async function GET(request: Request) { ... } in route.ts
Handler params { params }: { params: Promise<{ id: string }> } and await params
Redirect or rewrite early NextResponse.redirect(url) / NextResponse.rewrite(url) in proxy.ts
Limit where proxy runs export const config = { matcher: ['/admin/:path*'] }

Always authenticate, authorize and validate inside every action and handler. See Server Actions, Route Handlers and Middleware and the Proxy File.

Metadata and typing

Need API
Static metadata export const metadata: Metadata = { title, description }
Dynamic metadata export async function generateMetadata({ params })
Title pattern `title: { template: '%s
Canonical URL alternates: { canonical: '/path' } with metadataBase set
Social cards openGraph, twitter, or an opengraph-image file
Typed page props PageProps<'/blog/[slug]'> (generated by next dev, next build or next typegen)
Typed layout props LayoutProps<'/'>
Typed links typedRoutes: true in the config

See Metadata and SEO and TypeScript, ESLint and Typed Routes.

Configuration and environment

next.config.ts option Purpose
cacheComponents: true Turns on use cache and the Cache Components model
reactCompiler: true Enables the React Compiler (needs its Babel plugin installed)
images: { remotePatterns: [...] } Allow-list for remote images used with next/image
redirects(), rewrites(), headers() Rules applied before your routes
output: 'standalone' Minimal server folder for Docker
output: 'export' Fully static site in out/ (with limits)
basePath, assetPrefix Serve under a sub-path or a CDN
typedRoutes: true Type-checked href values
transpilePackages: [...] Compile dependencies that ship untranspiled code
cacheHandler Custom shared cache for several servers
experimental.serverActions Allowed origins and body size limit for actions
Env file Loaded
.env Always
.env.development, .env.production For the matching mode
.env.local, .env.development.local Local overrides. Keep them out of Git

Real process variables win over files. Only names starting with NEXT_PUBLIC_ reach the browser, and they are inlined at build time. See Configuring Next.js and Environment Variables and Secrets.

Two runnable stand-ins

The real framework cannot run here, so these show the logic. The first prints how the special files of a route wrap each other.

Node.js How special files wrap a route

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The second picks a revalidation API from the situation, following the table above. It is a decision aid, not Next.js code.

Node.js Which revalidation API?

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

When several choices fit, prefer tags over paths: a tag follows the data wherever it appears, a path only clears one route.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In what order does Next.js wrap a segment's children, outermost first?

    The layout is outermost, then the template, the error boundary, the loading Suspense boundary and the not-found boundary, with the page innermost.
  2. 2. Which helper expires a tag so the very next read is fresh, and only works inside Server Actions?

    updateTag gives read-your-own-writes behavior inside a Server Action. refresh() only refreshes uncached data, and revalidatePath clears a route.
  3. 3. Which variables reach the browser bundle?

    Only NEXT_PUBLIC_ variables are replaced in the client code during the build. Everything else stays on the server.
  4. 4. Where is the file for a Route Handler, and what can it not share a folder with?

    A segment is either a page or an endpoint. route.ts and page.tsx cannot live in the same folder.

Summary

  • Know the commands, the special files and their nesting order: layout, template, error, loading, not-found, page.
  • Three directives matter most: 'use client' (boundary), 'use server' (public action) and 'use cache' (explicit caching).
  • Fetching is uncached by default. Use cacheLife and cacheTag, then revalidatePath, revalidateTag, updateTag or refresh to clear.
  • Every action and handler must authenticate, authorize and validate its own input.
  • next.config.ts holds rewrites, redirects, headers, images, output mode and cacheComponents. Only NEXT_PUBLIC_ variables reach the browser.

You have reached the end of this tutorial. Review the exercises and interview questions again, or build the login project from scratch without looking at the solution.