Next.js Tutorial
Learn Next.js
The React framework for production — routing, rendering, and full-stack apps.
01
Getting Started
02
Routing
03
Rendering: Server & Client
04
Data Fetching
05
Server Actions & Mutations
06
Route Handlers & Middleware
07
Styling & Assets
09
Rendering Strategies & Caching
10
Configuration & Deployment
11
Advanced Routing
12
Caching & Rendering Mastery
Next.js Reference
123 pages · 11 groups · syntax, parameters and worked examples
Routing File Conventions21
page.jsDefines the unique UI for a route segment and makes that URL publicly accessible.layout.jsWraps a segment and its children in shared UI that survives navigation without re-rendering.loading.jsShows instant fallback UI while a route segment streams in, via an automatic Suspense boundary.error.jsCatches runtime errors in a route segment and renders recoverable fallback UI in their place.global-error.jsCatches errors thrown by the root layout by replacing the entire document with its own markup.not-found.jsRenders custom 404 UI when notFound() is thrown, and for unmatched URLs at the app root.forbidden.jsRenders 403 UI when forbidden() is thrown, for users authenticated but lacking permission.unauthorized.jsRenders 401 UI when unauthorized() is thrown, typically a login prompt for an absent session.route.jsCreates HTTP endpoints for a URL by exporting handlers that take a Request and return a Response.template.jsWraps a segment like a layout but remounts on navigation, resetting state and re-firing effects.default.jsRenders a fallback in a parallel route slot when a hard load cannot recover the slot's active state.proxy.jsRuns server code before a request is routed, to rewrite, redirect or modify headers and cookies.instrumentation.jsRuns setup code once when the server boots and reports server errors to an observability provider.instrumentation-client.jsRuns monitoring and analytics code in the browser before React hydrates the page.mdx-components.jsMaps MDX elements to React components and is required by @next/mdx in the App Router.Dynamic Segments — [slug]Captures a URL path segment and passes its value to the route through the params Promise.Route Groups — (folder)Groups routes under a shared folder and layout without adding a segment to the URL.Parallel Routes — @slotRenders several routes side by side in one layout, each passed to it as a named prop.Intercepting Routes — (.)(..)Loads another route inside the current layout while leaving the browser URL masked.public/Serves static files from the project root at URL paths starting with a slash.src/Holds app or pages one level down, separating application code from root config files.
Metadata File Conventions6
sitemap.xml / sitemap.tsServe /sitemap.xml from a static XML file or a default-exported function returning URL entries.robots.txt / robots.tsServe /robots.txt from a static file or a function returning crawl rules, sitemap and host.opengraph-imageSet a route segment's Open Graph image from a static file or a server-rendered ImageResponse.twitter-imageSet a route segment's X card image from a static file or a server-rendered ImageResponse.favicon, icon, apple-iconSet browser and home-screen icons from files in app, or generate them with ImageResponse.manifest.json / manifest.tsDescribe the app to browsers with a static web manifest or a function returning one.
Built-in Components5
<Link>Navigates between routes on the client, prefetching the target route before the user clicks.<Image>Serves optimized, correctly sized images with reserved space so layout does not shift while loading.<Script>Loads a third-party script at a chosen point in the page lifecycle instead of blocking rendering.<Form>Submits a form through client-side navigation, prefetching the destination and working without JavaScript.next/fontSelf-hosts Google or local fonts at build time and generates a matched fallback to prevent layout shift.
Client Hooks9
useRouter()Navigate, refresh, and prefetch routes programmatically from a Client Component.usePathname()Read the current URL pathname inside a Client Component.useSearchParams()Read the current URL's query string as a read-only URLSearchParams object on the client.useParams()Read the current route's filled-in dynamic segments from a Client Component.useSelectedLayoutSegment()Read the active route segment one level below the layout the hook is called from.useSelectedLayoutSegments()Read every active route segment below the layout the hook is called from.useLinkStatus()Track the pending state of a parent Link component for inline navigation feedback.useOffline()Report whether the app has lost connectivity so Client Components can render offline UI.useReportWebVitals()Receive Core Web Vitals metrics on the client and forward them to an analytics endpoint.
Request & Runtime Functions11
cookies()Reads incoming request cookies and writes outgoing ones from Server Components, Server Functions and Route Handlers.headers()Reads the incoming HTTP request headers as a read-only Web Headers object on the server.draftMode()Enables, disables and checks Draft Mode so editors can preview unpublished CMS content.connection()Pauses rendering until a real user request arrives, excluding the code after it from prerendering.io()Marks that a synchronous non-deterministic read follows, keeping it out of the static shell without blocking prefetch.after()Schedules a callback to run once the response has finished streaming, without delaying the user.fetch() extensionsExtends the Web fetch API with server-side caching and tag-based revalidation options.userAgent()Parses the request's User-Agent header into device, browser, engine, os and cpu details.NextRequestExtends the Web Request with cookie helpers and a nextUrl object for proxy and Route Handlers.NextResponseExtends the Web Response with next(), redirect(), rewrite(), json() and a cookies helper.ImageResponseRenders JSX and a CSS subset to a PNG on the server for Open Graph and social card images.
Navigation & Error Functions8
redirect()Interrupts rendering and sends the user to another URL with a 307, or 303 after a Server Function.permanentRedirect()Sends the user to a new URL with a 308 status for content that has permanently moved.notFound()Throws a 404 interrupt that renders the nearest not-found.js boundary and stops the route segment.forbidden()Throws a 403 interrupt that renders the nearest forbidden.js boundary for authorization failures.unauthorized()Throws a 401 interrupt rendering the nearest unauthorized.js boundary when a request is not signed in.unstable_rethrow()Re-throws Next.js internal control-flow errors so a catch block does not swallow them.refresh()Refetches the current route's RSC Payload from inside a Server Action without invalidating caches.catchError()Wraps a fallback into an error boundary component with retry and reset for component-level recovery.
Caching & Revalidation10
revalidatePath()Purge the cached render of a specific route path so the next visit regenerates it.revalidateTag()Mark every cache entry carrying a tag as stale, across all routes that use it.updateTag()Expire a cache tag from a Server Action so the caller immediately sees their own write.unstable_cache()Cache the result of a non-fetch async function, such as a database query, across requests.unstable_noStore()Opt a component out of static rendering so its data is fetched on every request.cacheLife()Set how long a 'use cache' scope stays fresh, stale and valid, by profile or inline object.cacheTag()Label a cached entry so tag-based invalidation can purge it on demand.'use cache'Cache a file, component, or async function's output keyed on its inputs.'use cache: private'Cache per-user output that reads cookies, headers, or searchParams, in the browser only.'use cache: remote'Store a cached result in a remote cache handler so all server instances share it.
Metadata Functions6
generateMetadataCompute a route's title, description and social tags from params, search params or fetched data.generateStaticParamsList the param values of a dynamic segment so Next.js prerenders those routes at build time.generateSitemapsSplit one route's sitemap into numbered files so each stays under the 50,000 URL limit.generateImageMetadataProduce several images from one icon or opengraph-image file, each with its own id, size and alt.generateViewportReturn viewport and theme-color settings that depend on route params or fetched data.export const metadataDeclare a segment's static title, description and social tags as a plain exported object.
Route Segment Config10
export const dynamicForces a route segment to render fully statically or fully per request under the previous caching model.export const revalidateSets the default revalidation interval, in seconds, for a layout, page, or route handler.export const fetchCacheOverrides the default cache option applied to every fetch request inside a route segment.export const dynamicParamsControls whether params missing from generateStaticParams render on demand or return a 404.export const runtimeSelects the JavaScript runtime used to render a route segment.export const maxDurationSets the maximum execution time in seconds for server-side logic in a route segment.export const preferredRegionNames the deployment region or regions a route segment should be deployed to (deprecated).export const prefetchCaps how much of a route a link preloads before navigation, per segment.export const instantDeclares that navigations into a segment should render immediately, and validates that they do.export const experimental_pprOpted a route into experimental Partial Prerendering in Next.js 15; removed in Next.js 16.
next.config Options30
imagesConfigures the built-in Image Optimization API: allowed hosts, widths, formats and cache TTL.redirects()Sends an incoming path to a different URL with a 307 or 308 before the filesystem is checked.rewrites()Proxies an incoming path to another path or origin while the browser's URL stays unchanged.headers()Attaches custom response headers to paths matching a pattern, before the filesystem is checked.outputSwitches the build between a minimal self-contained server and a fully static site.basePathServes the whole application under a sub-path of a domain, such as /docs.assetPrefixPoints the /_next/ JavaScript and CSS URLs at a CDN origin instead of the app server.trailingSlashRedirects URLs to add or remove a trailing slash, and changes exported filenames.envInlines fixed string values into the bundle at build time via webpack DefinePlugin substitution.distDirSets the directory next build writes to, instead of the default .next folder.pageExtensionsSets which file extensions Next.js treats as routable pages and convention files.reactStrictModeControls React Strict Mode's development-only double invocation and legacy API warnings.typedRoutesType-check href values against your app's real routes at compile time.serverExternalPackagesKeep a dependency out of the server bundle so Node loads it with require at runtime.serverActionsTune the body size limit and the origins allowed to invoke Server Functions.transpilePackagesCompile dependencies that ship raw TypeScript or JSX instead of leaving them as-is.optimizePackageImportsLoad only the modules you actually import from barrel-file packages.cacheComponentsEnable the 'use cache' model: dynamic by default, static shells, streamed dynamic holes.cacheHandlersBack 'use cache' with your own storage so entries survive restarts and are shared across instances.cacheLifeDefine named cache profiles that set stale, revalidate and expire in one call.staleTimesSet how long the client router reuses a prefetched segment before refetching it.loggingControl what the dev server prints: fetches, requests, Server Functions and browser output.devIndicatorsMove or hide the on-screen development route indicator.turbopackConfigure Turbopack loader rules, module aliases and resolvable extensions.webpack()Extends the webpack config Next.js generates, returning the modified object.typescriptControls whether type errors fail production builds and which tsconfig file is used.reactCompilerTurns on automatic memoization so components re-render less without manual useMemo calls.allowedDevOriginsLists extra origins allowed to request the development server's assets and endpoints.expireTimeSets the stale-while-revalidate window CDNs receive in Cache-Control for ISR pages.poweredByHeaderRemoves the x-powered-by response header when set to false.
Server Actions & Directives7
'use server'Marks a function or a whole file as server-only, turning its exports into callable Server Functions.'use client'Declares a module as a client entry point so its components render with browser JavaScript.useActionState()Runs an action through a reducer and returns its result, a dispatch function, and a pending flag.useFormStatus()Reads the submission state of the enclosing form from a component rendered inside it.useOptimistic()Renders a predicted state while an action is in flight, then falls back to the real value.<form action={serverFn}>Submits a form straight to a Server Function as FormData, with or without client JavaScript.Server Action security modelTreats every Server Action as a public POST endpoint that must authenticate and validate its own input.
All Next.js reference pages A–Z
E
G
I
R
S
U
unauthorized.jsuseRouter()usePathname()useSearchParams()useParams()useSelectedLayoutSegment()useSelectedLayoutSegments()useLinkStatus()useOffline()useReportWebVitals()userAgent()unauthorized()unstable_rethrow()updateTag()unstable_cache()unstable_noStore()'use cache''use cache: private''use cache: remote''use server''use client'useActionState()useFormStatus()useOptimistic()