Next.js
Next.js 16 and the App Router — the file-system router, layouts and navigation, Server and Client Components as the framework applies them, data fetching and caching (including Cache Components and use cache), mutations with Server Actions and route handlers, rendering strategies, styling and assets, authentication, the proxy layer, optimization, testing, and deployment. React's own component model stays in react, the language in javascript, types in typescript, and Node itself in nodejs. Fifty-eight lessons.
What Next.js is and why it existsReact gives you components; Next.js adds the router, server rendering, bundler and deployment story a real site needs. What it decides and what it costs.Creating a Next.js projectScaffold an app with create-next-app, read its prompts and defaults, and run the dev, build and start scripts on a current Next.js 16 install.The project structureWhat each file and folder in a Next.js 16 project does, how a route becomes public, and how to colocate code with private folders and an optional src directory.The App Router and the Pages RouterNext.js has two routers that can coexist. How the Pages Router worked, what the App Router changed, and why new projects should start with the App Router.Turbopack and the dev serverWhat a bundler does, why Next.js 16 made Turbopack the default for dev and build, how it works, and when you might still pass the --webpack flag.The file-system routerHow folders become URL segments in the App Router, why a page or route file makes a segment public, and what Next.js does with a URL that matches nothing.Pages and layoutsPages render the UI for a URL, layouts wrap it and persist across navigation. The required root layout, nesting, templates, and the generated LayoutProps type.Dynamic routes and paramsSquare-bracket segments, catch-all and optional catch-all routes, awaiting params and searchParams in Next.js 16, and the typed PageProps helper.Route groups and private foldersParenthesized folders organize routes and layouts without changing URLs; underscore folders opt out of routing. Caveats: root layouts and path clashes.Linking and moving between pagesThe Link component, prefetching, client-side transitions, useRouter and usePathname, and what makes a Next.js navigation feel instant or slow.Loading UI and streamingHow loading.tsx wraps a page in Suspense, why streaming improves perceived speed, and how to stream parts of a page with your own Suspense boundaries.Error handling and not-foundExpected errors versus uncaught exceptions, error.tsx and global-error.tsx boundaries, notFound() with not-found.tsx, and the status code streaming changes.Parallel and intercepting routesNamed @slots that render several pages in one layout, default.tsx fallbacks, and intercepting routes with (.) and (..) for modals that keep deep-linkable URLs.Redirects and rewritesredirect(), permanentRedirect, next.config redirects and rewrites, and proxy.ts. Which one to use, which status codes they send, and how a rewrite differs.Server Components in Next.jsWhy layouts and pages are Server Components by default in Next.js, what that lets you do, what it forbids, and how the RSC payload reaches the browser.The use client boundaryWhat "use client" actually declares, why it marks a boundary in the module graph rather than one component, and how to keep client JavaScript small.Composing Server and Client ComponentsWhich nestings of server and client components work, why importing a Server Component into a Client Component fails, and the children slot that fixes it.Environment variables and server-only codeHow .env files load, why only NEXT_PUBLIC_ variables reach the browser, and how the server-only package turns an accidental client import into a build error.Third-party components and context providersWhy context and some libraries break in Server Components, and how to wrap them in a small Client Component, place providers deep, and author libraries.Fetching data in Server ComponentsAwait a fetch right inside an async Server Component, stream slow data behind Suspense, and see why uncached fetches need a boundary under Cache Components.Querying a database directlyCall an ORM or database client from a Server Component, keep the data layer server-only, deduplicate with React.cache, and handle synchronous drivers.Request memoization and parallel fetchingHow Next.js deduplicates identical fetches in one render, when React.cache is needed instead, and how to avoid request waterfalls with Promise.all.The four cachesRequest memoization, the Data Cache, the Full Route Cache, and the Router Cache: what each did, and what replaced it in Next.js 16 with Cache Components.Cache Components and use cacheOpt in to caching with the use cache directive and cacheLife, mix static, cached and streamed content on one page, and learn what a cached function cannot read.Revalidation and cache tagsTag cached data with cacheTag, then refresh it with updateTag, revalidateTag, revalidatePath, or refresh, and pick the right one after a mutation.Dynamic APIs: cookies, headers, and searchParamsRequest-time data is async in Next.js 16. How cookies(), headers(), params and searchParams work, why they need Suspense, and how to feed cached code.Client-side data fetchingWhen a Client Component should fetch for itself, how use() with a server-started promise compares with SWR and TanStack Query, and how to seed a library.Server Actions basicsDefine a Server Action with use server, call it from a form, pass extra arguments with bind, and treat it as a public POST endpoint that needs auth checks.Forms and pending statesShow a pending state with useActionState or useFormStatus, bind a form to a Server Action, and use the Form component for GET search forms.Validation and error handling in actionsValidate FormData on the server with a schema, return expected errors as state with useActionState, and leave unexpected failures to error boundaries.Optimistic updatesUse useOptimistic to show a Server Action's result immediately, roll back on failure, and know when waiting for the server is the better choice.Route handlersBuild HTTP endpoints with route.ts, read params and the request, and see how GET handlers are cached, static, or dynamic with and without Cache Components.The proxy fileproxy.ts replaces middleware.ts in Next.js 16. Redirect, rewrite, and set headers before a request finishes, scope it with a matcher, and know its limits.Static and dynamic renderingStatic rendering builds HTML once at build time, dynamic rendering per request. See what triggers each in Next.js 16 and how Cache Components changes it.Partial prerenderingPartial prerendering serves a prebuilt static shell and streams dynamic holes into it. In Next.js 16 it is the default with Cache Components.Generating static paramsUse generateStaticParams to prerender dynamic routes at build time, handle nested segments, and see what changes under Cache Components.Incremental static regenerationISR updates static pages without a full rebuild. See the classic revalidate model and how Cache Components replaces it with cacheLife and tags.Metadata and SEOSet titles and social tags with the metadata object and generateMetadata, add sitemap, robots and OG image files, and understand streaming metadata.CSS Modules and global CSSStyle Next.js App Router pages with CSS Modules for scoped classes and global CSS for the truly global, and learn how import order decides CSS order.Tailwind CSS in Next.jsInstall Tailwind CSS v4 in a Next.js 16 app with the PostCSS plugin, import it once in your root layout, and know where it fits next to CSS Modules.Fonts with next/fontLoad Google and local fonts with next/font so they are self-hosted at build time, cause no layout shift, and connect to Tailwind through CSS variables.Optimizing imagesUse next/image for correctly sized, lazy-loaded images with no layout shift, and configure remote images, sizes, quality, and preloading in Next.js 16.Scripts and third-party codeLoad analytics, tag managers, and widgets with next/script and its loading strategies, run code after load, and use @next/third-parties for common embeds.Authentication concepts and sessionsSeparate authentication, sessions, and authorization, then build a cookie session in Next.js 16 with signed JWTs, the cookies API, and the right cookie flags.Protecting routes and dataWhere to put auth checks in Next.js 16: a proxy for fast optimistic redirects, a data access layer for real checks, and a check inside every Server Action.Auth.js and auth librariesChoosing between hosted auth, self-run libraries and session toolkits, what happened to Auth.js, and how a library plugs into a Data Access Layer.Security headers and CSPThe browser-enforced headers worth setting, how to build a nonce-based Content Security Policy in proxy.ts, and why nonces force dynamic rendering.Bundle analysis and lazy loadingFind heavy client code with next analyze, split it out with next/dynamic and dynamic import(), and know where bundle growth usually comes from.Core Web Vitals in Next.jsWhat LCP, INP and CLS measure, which Next.js features target each, the difference between lab and field data, and how to report vitals with a hook.Unit and component testingSet up Vitest or Jest for a Next.js app, write a component test, and learn why async Server Components belong in end-to-end tests instead.End-to-end testing with PlaywrightDrive a real browser against a production build with Playwright, reuse a logged-in state, and test the flows unit tests cannot reach.TypeScript in Next.jsThe Next.js-specific TypeScript features: generated route types, PageProps and LayoutProps, typed links with typedRoutes, and typed config.Build output and next buildRead the route table next build prints, know what each symbol means, what lands in .next, and which flags help when a build fails or a route is not static.Deploying to VercelDeploy a Next.js app to Vercel from Git or the CLI, tell preview from production deployments, scope environment variables, and see what each feature runs on.Self-hosting with Node.js and DockerRun Next.js with next start or the standalone output, package it in a multi-stage Docker image, and handle the caches, env vars, and proxy settings.Static exportsSet output: 'export' to turn a Next.js app into plain HTML, CSS, and JavaScript for any static host, and learn what the build rejects, allows, and costs you.Upgrading and the codemodsMove a Next.js app to version 16 with next upgrade and the official codemods, know the breaking changes the codemods miss, and verify with a checklist.The Pages Router for legacy appsRead and maintain a Pages Router app: its data functions and special files, how it coexists with the App Router, and a page-by-page path for migrating it.
Getting started
- What Next.js is and why it existsReact gives you components; Next.js adds the router, server rendering, bundler and deployment story a real site needs. What it decides and what it costs.
- Creating a Next.js projectScaffold an app with create-next-app, read its prompts and defaults, and run the dev, build and start scripts on a current Next.js 16 install.
- The project structureWhat each file and folder in a Next.js 16 project does, how a route becomes public, and how to colocate code with private folders and an optional src directory.
- The App Router and the Pages RouterNext.js has two routers that can coexist. How the Pages Router worked, what the App Router changed, and why new projects should start with the App Router.
- Turbopack and the dev serverWhat a bundler does, why Next.js 16 made Turbopack the default for dev and build, how it works, and when you might still pass the --webpack flag.
Routing
- The file-system routerHow folders become URL segments in the App Router, why a page or route file makes a segment public, and what Next.js does with a URL that matches nothing.
- Pages and layoutsPages render the UI for a URL, layouts wrap it and persist across navigation. The required root layout, nesting, templates, and the generated LayoutProps type.
- Dynamic routes and paramsSquare-bracket segments, catch-all and optional catch-all routes, awaiting params and searchParams in Next.js 16, and the typed PageProps helper.
- Route groups and private foldersParenthesized folders organize routes and layouts without changing URLs; underscore folders opt out of routing. Caveats: root layouts and path clashes.
- Linking and moving between pagesThe Link component, prefetching, client-side transitions, useRouter and usePathname, and what makes a Next.js navigation feel instant or slow.
- Loading UI and streamingHow loading.tsx wraps a page in Suspense, why streaming improves perceived speed, and how to stream parts of a page with your own Suspense boundaries.
- Error handling and not-foundExpected errors versus uncaught exceptions, error.tsx and global-error.tsx boundaries, notFound() with not-found.tsx, and the status code streaming changes.
- Parallel and intercepting routesNamed @slots that render several pages in one layout, default.tsx fallbacks, and intercepting routes with (.) and (..) for modals that keep deep-linkable URLs.
- Redirects and rewritesredirect(), permanentRedirect, next.config redirects and rewrites, and proxy.ts. Which one to use, which status codes they send, and how a rewrite differs.
Server and Client Components
- Server Components in Next.jsWhy layouts and pages are Server Components by default in Next.js, what that lets you do, what it forbids, and how the RSC payload reaches the browser.
- The use client boundaryWhat "use client" actually declares, why it marks a boundary in the module graph rather than one component, and how to keep client JavaScript small.
- Composing Server and Client ComponentsWhich nestings of server and client components work, why importing a Server Component into a Client Component fails, and the children slot that fixes it.
- Environment variables and server-only codeHow .env files load, why only NEXT_PUBLIC_ variables reach the browser, and how the server-only package turns an accidental client import into a build error.
- Third-party components and context providersWhy context and some libraries break in Server Components, and how to wrap them in a small Client Component, place providers deep, and author libraries.
Data fetching and caching
- Fetching data in Server ComponentsAwait a fetch right inside an async Server Component, stream slow data behind Suspense, and see why uncached fetches need a boundary under Cache Components.
- Querying a database directlyCall an ORM or database client from a Server Component, keep the data layer server-only, deduplicate with React.cache, and handle synchronous drivers.
- Request memoization and parallel fetchingHow Next.js deduplicates identical fetches in one render, when React.cache is needed instead, and how to avoid request waterfalls with Promise.all.
- The four cachesRequest memoization, the Data Cache, the Full Route Cache, and the Router Cache: what each did, and what replaced it in Next.js 16 with Cache Components.
- Cache Components and use cacheOpt in to caching with the use cache directive and cacheLife, mix static, cached and streamed content on one page, and learn what a cached function cannot read.
- Revalidation and cache tagsTag cached data with cacheTag, then refresh it with updateTag, revalidateTag, revalidatePath, or refresh, and pick the right one after a mutation.
- Dynamic APIs: cookies, headers, and searchParamsRequest-time data is async in Next.js 16. How cookies(), headers(), params and searchParams work, why they need Suspense, and how to feed cached code.
- Client-side data fetchingWhen a Client Component should fetch for itself, how use() with a server-started promise compares with SWR and TanStack Query, and how to seed a library.
Mutations and APIs
- Server Actions basicsDefine a Server Action with use server, call it from a form, pass extra arguments with bind, and treat it as a public POST endpoint that needs auth checks.
- Forms and pending statesShow a pending state with useActionState or useFormStatus, bind a form to a Server Action, and use the Form component for GET search forms.
- Validation and error handling in actionsValidate FormData on the server with a schema, return expected errors as state with useActionState, and leave unexpected failures to error boundaries.
- Optimistic updatesUse useOptimistic to show a Server Action's result immediately, roll back on failure, and know when waiting for the server is the better choice.
- Route handlersBuild HTTP endpoints with route.ts, read params and the request, and see how GET handlers are cached, static, or dynamic with and without Cache Components.
- The proxy fileproxy.ts replaces middleware.ts in Next.js 16. Redirect, rewrite, and set headers before a request finishes, scope it with a matcher, and know its limits.
Rendering strategies
- Static and dynamic renderingStatic rendering builds HTML once at build time, dynamic rendering per request. See what triggers each in Next.js 16 and how Cache Components changes it.
- Partial prerenderingPartial prerendering serves a prebuilt static shell and streams dynamic holes into it. In Next.js 16 it is the default with Cache Components.
- Generating static paramsUse generateStaticParams to prerender dynamic routes at build time, handle nested segments, and see what changes under Cache Components.
- Incremental static regenerationISR updates static pages without a full rebuild. See the classic revalidate model and how Cache Components replaces it with cacheLife and tags.
- Metadata and SEOSet titles and social tags with the metadata object and generateMetadata, add sitemap, robots and OG image files, and understand streaming metadata.
Styling and assets
- CSS Modules and global CSSStyle Next.js App Router pages with CSS Modules for scoped classes and global CSS for the truly global, and learn how import order decides CSS order.
- Tailwind CSS in Next.jsInstall Tailwind CSS v4 in a Next.js 16 app with the PostCSS plugin, import it once in your root layout, and know where it fits next to CSS Modules.
- Fonts with next/fontLoad Google and local fonts with next/font so they are self-hosted at build time, cause no layout shift, and connect to Tailwind through CSS variables.
- Optimizing imagesUse next/image for correctly sized, lazy-loaded images with no layout shift, and configure remote images, sizes, quality, and preloading in Next.js 16.
- Scripts and third-party codeLoad analytics, tag managers, and widgets with next/script and its loading strategies, run code after load, and use @next/third-parties for common embeds.
Authentication and security
- Authentication concepts and sessionsSeparate authentication, sessions, and authorization, then build a cookie session in Next.js 16 with signed JWTs, the cookies API, and the right cookie flags.
- Protecting routes and dataWhere to put auth checks in Next.js 16: a proxy for fast optimistic redirects, a data access layer for real checks, and a check inside every Server Action.
- Auth.js and auth librariesChoosing between hosted auth, self-run libraries and session toolkits, what happened to Auth.js, and how a library plugs into a Data Access Layer.
- Security headers and CSPThe browser-enforced headers worth setting, how to build a nonce-based Content Security Policy in proxy.ts, and why nonces force dynamic rendering.
Optimization and testing
- Bundle analysis and lazy loadingFind heavy client code with next analyze, split it out with next/dynamic and dynamic import(), and know where bundle growth usually comes from.
- Core Web Vitals in Next.jsWhat LCP, INP and CLS measure, which Next.js features target each, the difference between lab and field data, and how to report vitals with a hook.
- Unit and component testingSet up Vitest or Jest for a Next.js app, write a component test, and learn why async Server Components belong in end-to-end tests instead.
- End-to-end testing with PlaywrightDrive a real browser against a production build with Playwright, reuse a logged-in state, and test the flows unit tests cannot reach.
- TypeScript in Next.jsThe Next.js-specific TypeScript features: generated route types, PageProps and LayoutProps, typed links with typedRoutes, and typed config.
Deployment and beyond
- Build output and next buildRead the route table next build prints, know what each symbol means, what lands in .next, and which flags help when a build fails or a route is not static.
- Deploying to VercelDeploy a Next.js app to Vercel from Git or the CLI, tell preview from production deployments, scope environment variables, and see what each feature runs on.
- Self-hosting with Node.js and DockerRun Next.js with next start or the standalone output, package it in a multi-stage Docker image, and handle the caches, env vars, and proxy settings.
- Static exportsSet output: 'export' to turn a Next.js app into plain HTML, CSS, and JavaScript for any static host, and learn what the build rejects, allows, and costs you.
- Upgrading and the codemodsMove a Next.js app to version 16 with next upgrade and the official codemods, know the breaking changes the codemods miss, and verify with a checklist.
- The Pages Router for legacy appsRead and maintain a Pages Router app: its data functions and special files, how it coexists with the App Router, and a page-by-page path for migrating it.