PrepStack › Frontend › Next.js

Next.js interview cheat sheet

App Router, Server Components, rendering, caching and production (v15/v16)

Next.js interviews test whether you understand where code runs (server or client), when HTML is produced (build time, request time, or streamed) and how data is cached and revalidated. Expect questions on the App Router file conventions, Server vs Client Components, Server Actions, Proxy (formerly Middleware), and the caching changes in v15 and v16. Read the 15-minute list first, then use Quiz mode and answer out loud. Code here targets Next.js 16 with the App Router unless a section says otherwise.

15-minute revision

  1. App Router (app/) is the modern default: React Server Components, nested layouts, streaming, Server Actions. Pages Router (pages/) is older but still supported, with getStaticProps / getServerSideProps.
  2. A folder is a route segment; it becomes public only when it has a page.tsx (UI) or route.ts (API). Other files can be colocated safely.
  3. Special files: layout (persists, keeps state), template (remounts on every navigation), loading (Suspense fallback), error (client error boundary), not-found, default (parallel-route fallback).
  4. [id] = dynamic segment, [...slug] = catch-all (1+ parts), [[...slug]] = optional catch-all (0+). (group) folders organise code without changing the URL. _folder is private.
  5. Since v15, params, searchParams, cookies(), headers() and draftMode() are async. In v16 the sync fallback is removed: always await them.
  6. Every component in app/ is a Server Component by default. Add 'use client' at the top of a file to make it (and everything it imports) part of the client bundle.
  7. Props crossing the server→client boundary must be serializable. You can pass Server Components to Client Components as children, but you cannot import a Server Component into a Client file.
  8. Rendering: SSG (build time), ISR (static + revalidate in background), SSR (per request), CSR (in the browser), streaming (send HTML in chunks via Suspense), PPR (static shell + dynamic holes).
  9. v15 caching flip: fetch, GET Route Handlers and the client Router Cache for pages are not cached by default. Opt in with cache: 'force-cache', next.revalidate, or 'use cache'.
  10. v16 Cache Components (cacheComponents: true): caching is fully opt-in with 'use cache' + cacheLife() + cacheTag(). Uncached or runtime data must sit inside <Suspense>. This is how PPR ships now.
  11. Revalidate on demand with revalidatePath(path) or revalidateTag(tag, 'max') (v16 needs a profile). updateTag(tag) gives read-your-writes inside a Server Action.
  12. Server Actions ('use server') are async functions callable from forms and client code. They are public POST endpoints, so always validate input and check auth inside them.
  13. Route Handlers (app/api/x/route.ts) export GET, POST and so on, using Web Request/Response. A folder cannot have both page and route.
  14. v16 renamed middleware.ts to proxy.ts (export proxy); it runs on Node.js. Use it for redirects, rewrites and cheap optimistic auth checks, not as the only security layer.
  15. Only NEXT_PUBLIC_* env vars reach the browser, and they are inlined at build time. Everything else is server-only.
  16. Hydration errors mean server HTML ≠ first client render: Date.now(), Math.random(), window checks, locale formatting, invalid HTML nesting. Fix with useEffect, stable data, or suppressHydrationWarning for single text nodes.

Routing fundamentals

App Router vs Pages Router & file-based routing

The folder tree under app/ is your URL tree; the App Router is built on React Server Components.

  • Next.js is a React framework that adds routing, server rendering, data fetching, bundling and optimisation on top of React.
  • App Router lives in app/. Folders are URL segments, and page.tsx makes a segment public. It supports layouts, streaming, Server Components and Server Actions.
  • Pages Router lives in pages/. Each file is a route (pages/about.tsx → /about). Data comes from getStaticProps, getStaticPaths and getServerSideProps; API routes live in pages/api.
  • Both routers can live in one project during migration, but a given URL must belong to only one of them; a clash is a build error.
  • Because only page and route files are routable, you can colocate components, tests and styles inside app/ safely. Prefix a folder with _ to mark it private.
  • Navigation uses <Link> (client-side transitions with prefetching) and useRouter() from next/navigation in the App Router (next/router is Pages-only).

Interview questions

  • What is the difference between the App Router and the Pages Router?
  • How does file-based routing work in the App Router?
  • Can you use both routers in one app?

Layouts, templates, loading, error & not-found

Special files in each segment build a fixed tree of layouts, boundaries and the page.

  • layout.tsx wraps a segment and its children. It persists across navigations, keeps state and does not re-render when you move between sibling pages.
  • template.tsx is like a layout but remounts on every navigation (new key). Use it for enter animations or per-page effects such as logging page views.
  • loading.tsx becomes a <Suspense> fallback around the page. It shows instantly during navigation and enables streaming.
  • error.tsx is a React error boundary and must be a Client Component. It receives error and a reset() function to re-render the segment (v16.2 also added an unstable_retry prop that re-fetches). It does not catch errors in the layout of the same segment.
  • global-error.tsx catches errors in the root layout and must render its own <html> and <body>.
  • not-found.tsx renders when you call notFound() or a URL matches nothing. default.tsx is the fallback for parallel-route slots.

Interview questions

  • What is the difference between layout.tsx and template.tsx?
  • How does loading.tsx work?
  • Why must error.tsx be a Client Component?
  • How do you show a 404 for a missing record?

Dynamic, catch-all routes & route groups

Square brackets capture URL parts; parentheses group folders without touching the URL.

  • app/blog/[slug]/page.tsx matches /blog/hello with params = { slug: 'hello' }.
  • [...slug] is a catch-all: /shop/a/b gives { slug: ['a','b'] } and /shop does not match. [[...slug]] is optional and also matches /shop.
  • In v15+ params and searchParams are Promises: const { slug } = await params. In Client Components use React's use(params) or the useParams() hook.
  • generateStaticParams() returns the param values to prerender at build time. export const dynamicParams = false makes other values 404 (previous model).
  • Route groups (name) let you share a layout between some routes, split the app into sections, or create multiple root layouts, without adding to the URL.
  • Two groups must not resolve to the same URL ((a)/about and (b)/about is an error).

Interview questions

  • Difference between [...slug] and [[...slug]]?
  • What are route groups used for?
  • What does generateStaticParams do?
  • Why are params and searchParams Promises since v15?

Parallel & intercepting routes

Slots (@name) render several pages in one layout; (.) folders show another route in the current context, like a modal.

  • Parallel routes: a folder named @team is a slot. It is passed to the parent layout as a prop (team) next to children. Slots are not URL segments.
  • Each slot can have its own loading and error files, so dashboard panels stream and fail independently.
  • On a hard reload, Next.js cannot know the slot's state for an unmatched URL, so it renders default.tsx. Since v16 every slot must have a default.tsx or the build fails.
  • Intercepting routes load a route from another part of the app inside the current layout during client navigation. (.) = same level, (..) = one level up, (..)(..) = two levels, (...) = from app root. Levels are route segments, not folders.
  • The classic use is a modal: clicking a photo in a feed opens /photo/1 in a modal (intercepted), while a refresh or shared link opens the full photo page.
  • Use parallel routes for conditional UI too, for example showing @admin or @user based on role in the layout.

Interview questions

  • What are parallel routes and when would you use them?
  • How do intercepting routes enable a shareable modal?
  • Why is default.tsx needed for slots?

Components & rendering

Server Components vs Client Components

Server Components render only on the server and ship no JS; Client Components add interactivity and are hydrated in the browser.

  • In app/, every component is a Server Component by default. It can be async, read the DB or file system directly, use secrets, and its code is never sent to the browser.
  • A Client Component starts with 'use client'. It can use state, effects, event handlers, browser APIs and context. It is still prerendered to HTML on the server, then hydrated.
  • Server Components cannot use useState, useEffect, onClick or browser APIs. Client Components cannot be async or read server secrets.
  • The server sends an RSC payload: a compact description of the rendered Server Component tree, with placeholders and JS references for Client Components.
  • Keep Client Components small and at the leaves (a like button, a search box) so most of the page stays server-only and the bundle stays small.

Interview questions

  • What is the difference between Server and Client Components?
  • Are Client Components rendered on the server?
  • What are the benefits of Server Components?
  • What is the RSC payload?

The 'use client' boundary rules

'use client' marks an entry point into the client bundle; everything it imports becomes client code too.

  • 'use client' goes at the top of a file, before imports. It marks a boundary: that module and all modules it imports are bundled for the client.
  • You only need it on the entry file. Children imported by a client file are already client code.
  • A Client Component cannot import a Server Component. Instead, pass Server Components as children or other props (the donut or slot pattern).
  • Props from server to client must be serializable: primitives, plain objects, arrays, Date, Map, Set, Promises, JSX, and Server Actions. Plain functions and class instances are not allowed.
  • Context providers must be Client Components. Wrap them in a small providers.tsx with 'use client' and render it in the root layout around children.
  • Third-party components that use hooks but lack 'use client' need a tiny wrapper file that re-exports them with the directive.

Interview questions

  • Can a Client Component render a Server Component?
  • What can you pass as props from a Server to a Client Component?
  • Where should you put 'use client'?
  • Difference between 'use client' and 'use server'?

Rendering strategies: CSR, SSR, SSG, ISR

Choose when HTML is produced: in the browser, per request, at build time, or at build time with background refresh.

  • CSR (client-side rendering): the server sends a shell and JS renders content in the browser. In Next.js this means data fetched in a Client Component (with useEffect, SWR or TanStack Query).
  • SSR (dynamic rendering): HTML is generated per request. Triggered by runtime data such as cookies(), headers(), searchParams, or uncached data.
  • SSG (static rendering): HTML is generated at build time and served from a CDN. This is the default when a route uses no request data.
  • ISR: static pages that regenerate in the background after a time (revalidate) or on demand (revalidatePath / revalidateTag). Users get the cached page while the new one builds (stale-while-revalidate).
  • In the App Router you do not pick a mode per page. Next.js decides per route (or per component with PPR) based on the data and APIs you use.
  • Pages Router equivalents: getStaticProps (SSG), getStaticProps + revalidate (ISR), getServerSideProps (SSR).

Interview questions

  • Explain SSR vs SSG vs ISR.
  • How does Next.js decide if a route is static or dynamic?
  • A product page must be fast and show live stock. What do you do?

Streaming, Suspense & Partial Prerendering

Streaming sends HTML in chunks as Suspense boundaries resolve; PPR serves a static shell instantly and streams the dynamic holes.

  • Streaming splits the response into chunks. The shell and fallbacks are sent first; each <Suspense> boundary is sent when its data is ready, with a small inline script that swaps it in.
  • This improves TTFB and FCP: slow data no longer blocks the whole page. Boundaries can also hydrate independently (selective hydration).
  • loading.tsx is a route-level Suspense boundary. Use <Suspense> inside the page for finer control.
  • Partial Prerendering (PPR) combines static and dynamic in one route. At build time Next.js prerenders everything it can into a static shell, including Suspense fallbacks; at request time only the dynamic parts render and stream in.
  • In v16, PPR ships as Cache Components (cacheComponents: true). The old experimental.ppr flag and experimental_ppr export were removed.
  • With Cache Components, code that reads runtime data or uncached data must be inside <Suspense>, or marked with 'use cache'; otherwise dev shows a "blocking route" error.

Interview questions

  • What is streaming and why does it help?
  • What is Partial Prerendering?
  • How does PPR relate to Cache Components in Next.js 16?
  • Why can't a streamed page return a 404 status after it started?

Data, caching & mutations

Data fetching patterns

Fetch on the server in async components, start requests in parallel, and pass promises down when it helps streaming.

  • In Server Components, just await your data: fetch, an ORM, or a DB client. No useEffect and no API route needed.
  • Sequential vs parallel: awaiting one call after another creates a waterfall. Start independent requests first and await Promise.all([...]).
  • The same fetch (same URL and options) is memoized within one render pass, so a layout and a page can both call getUser() without double requests. For non-fetch calls, wrap them in React cache().
  • You can pass a promise from a Server Component to a Client Component and read it with React's use() inside <Suspense>; the data streams in.
  • Client-side fetching (SWR, TanStack Query) is still right for polling, infinite scroll or user-triggered queries.
  • Do not call your own Route Handlers from Server Components; call the underlying function directly. The HTTP hop is wasted work and fails at build time.

Interview questions

  • How do you fetch data in the App Router?
  • What is a request waterfall and how do you avoid it?
  • Two components need the same user data. Will it be fetched twice?
  • Should a Server Component call /api/... Route Handlers?

Caching layers & revalidation (v14 → v15 → v16)

Next.js 15 made caching opt-in; Next.js 16 adds the explicit Cache Components model. Revalidate by time, path or tag.

  • Layers to know: request memoization (one render), Data Cache (fetch results across requests), Full Route Cache (prerendered HTML + RSC payload), and the client Router Cache (RSC payloads in the browser).
  • v15 changes: fetch is no longer cached by default (no-store unless you opt in), GET Route Handlers are not cached by default, and the Router Cache uses staleTime 0 for pages (layouts and back/forward still reuse cache).
  • Previous model opt-ins: fetch(url, { cache: 'force-cache' }), { next: { revalidate: 3600 } }, { next: { tags: ['posts'] } }, unstable_cache for non-fetch, and segment config export const revalidate = 60 / dynamic = 'force-static'.
  • On-demand: revalidatePath('/blog') clears a route; revalidateTag('posts', 'max') marks tagged data stale (v16 requires the second cacheLife profile argument; the one-arg form is deprecated).
  • v16 adds updateTag(tag) (Server Actions only, expire and read fresh data in the same request: read-your-writes) and refresh() (Server Actions only, re-render uncached data without touching the cache).
  • Client side, router.refresh() re-fetches the current route's RSC payload without losing client state.

Interview questions

  • What changed about caching in Next.js 15?
  • Difference between revalidatePath and revalidateTag?
  • Difference between revalidateTag and updateTag in v16?
  • Name the caching layers in Next.js.

'use cache', cacheLife & cacheTag (Cache Components)

With cacheComponents: true, nothing is cached unless you mark a function, component or file with 'use cache'.

  • Enable with cacheComponents: true in next.config.ts (this replaced experimental.dynamicIO and the PPR flags).
  • 'use cache' can go at the top of a file (all exports cached), a component, or an async function. Cached functions must be async.
  • The cache key is built automatically from the build ID, a function ID, and the serialized arguments and captured closure variables. Different inputs get separate entries.
  • cacheLife('hours') sets the lifetime. Built-in profiles: default, seconds, minutes, hours, days, weeks, max; or custom profiles in config. cacheTag('posts') labels the entry for revalidateTag / updateTag.
  • Cached scopes cannot read cookies(), headers() or searchParams. Read them outside and pass the values in as arguments (they become part of the key).
  • Arguments and return values must be serializable. children and Server Actions can be passed through as long as the cached function does not inspect them.

Interview questions

  • What does 'use cache' do?
  • How is 'use cache' different from unstable_cache or fetch caching?
  • Why can't a cached function call cookies()?
  • How do you invalidate a 'use cache' entry?

Server Actions & forms

'use server' functions run on the server and can be called from forms or client code without writing an API route.

  • Mark a function (or a whole file) with 'use server'. Next.js gives it a hidden action ID and an endpoint; the client calls it with a POST request.
  • Pass it to <form action={createTodo}>: it receives FormData. This works even before JavaScript loads (progressive enhancement) when the form is rendered by a Server Component.
  • Pair with React 19 hooks: useActionState (result + pending state), useFormStatus (pending state inside the form), and useOptimistic for instant UI.
  • After a mutation, call revalidatePath / revalidateTag / updateTag to refresh data, and redirect() to navigate. The updated UI comes back in the same round trip.
  • Actions are public endpoints. Validate input (Zod), check authentication and authorisation inside every action, and never trust hidden form fields.
  • Built-in CSRF protection: only POST is allowed, and Next.js compares the Origin and Host headers. Add experimental.serverActions.allowedOrigins if a reverse proxy changes the host.

Interview questions

  • What are Server Actions?
  • Are Server Actions secure by default?
  • Server Action or Route Handler: which do you choose?
  • How do you show a pending state and errors for a form?

Route Handlers (API routes)

route.ts exports HTTP-method functions that take a Web Request and return a Response.

  • Create app/api/users/route.ts and export GET, POST, PUT, PATCH, DELETE, HEAD or OPTIONS. Unsupported methods get 405.
  • Handlers use standard Web APIs plus NextRequest / NextResponse helpers (req.nextUrl.searchParams, Response.json(), cookies).
  • Dynamic segments work the same: the second argument is { params }, which is a Promise in v15+.
  • A route.ts and a page.tsx cannot be in the same folder.
  • Since v15, GET handlers are dynamic by default. Opt into static output with export const dynamic = 'force-static' (previous model); with Cache Components they prerender like pages unless they use runtime or uncached data.
  • Good uses: webhooks (Stripe, CMS), public APIs, OAuth callbacks, file downloads, streaming responses, and endpoints for mobile clients.

Interview questions

  • How do you create an API endpoint in the App Router?
  • Difference between App Router Route Handlers and Pages Router API routes?
  • Are GET Route Handlers cached?

Requests, auth & runtimes

Proxy (formerly Middleware)

proxy.ts runs before a request is routed and can redirect, rewrite, set headers or cookies, or respond directly.

  • Next.js 16 renamed middleware.ts to proxy.ts and the exported function to proxy (named or default export). The logic is the same; middleware.ts is deprecated.
  • proxy.ts sits in the project root (or src/), one per project. It runs on the Node.js runtime. The old middleware.ts remains only for Edge-runtime use cases.
  • Use export const config = { matcher: [...] } to limit paths. Without a matcher it runs on every request, including _next/static and images.
  • Typical uses: auth redirects (optimistic cookie check), locale detection, A/B test rewrites, bot blocking, adding security headers.
  • Keep it fast: it runs on every matched request. Directives like 'use cache' do not work there and fetch caching options are ignored.
  • Pass data to the app through request headers, cookies, rewrites or the URL; do not rely on shared globals.

Interview questions

  • What is Middleware / Proxy in Next.js?
  • Why was middleware renamed to proxy?
  • Should you do authorization only in Proxy?
  • Difference between a redirect and a rewrite?

Authentication & authorization patterns

Check sessions in a Data Access Layer close to the data; use Proxy only for fast optimistic redirects.

  • Common libraries: Auth.js (NextAuth), Clerk, Better Auth, Supabase Auth, or your own sessions with iron-session / jose.
  • Sessions are either stateless (signed/encrypted JWT in an httpOnly, secure, sameSite cookie) or database sessions (cookie holds an ID).
  • Create a Data Access Layer (DAL): a server-only module with verifySession() (wrapped in React cache()) and functions that check permissions before reading data.
  • Check auth in every Server Action and Route Handler, and in pages/components that read protected data. Layouts are not a safe place for the only check, because they do not re-render on every navigation.
  • Return DTOs: only the fields the UI needs, never the full user row with password hash.
  • Cookies are set in Server Actions or Route Handlers ((await cookies()).set(...)), not during a Server Component render.

Interview questions

  • How do you implement authentication in the App Router?
  • Why shouldn't you rely on a layout for auth checks?
  • What is a Data Access Layer and why use it?

Edge vs Node.js runtime

Node.js is the default with full APIs; Edge is a lightweight Web-API runtime with limits.

  • Node.js runtime (default): all Node APIs and npm packages, ISR support, used for rendering the app.
  • Edge runtime: a V8 isolate with Web-standard APIs (fetch, Request, Response, Web Crypto, streams). Fast cold starts, but no fs, no native modules, limited package support, and no ISR.
  • Opt a route into Edge with the segment config export const runtime = 'edge' (default 'nodejs').
  • In v16, proxy.ts runs on Node.js; Edge remains available through the deprecated middleware.ts.
  • "Edge" does not mean faster overall: if your database is in one region, rendering near the user adds latency on every query. Put compute close to the data.

Interview questions

  • Difference between the Edge and Node.js runtimes?
  • When would you choose the Edge runtime?

Optimisation, SEO & production

Metadata & SEO

Export a metadata object or a generateMetadata function from a layout or page; Next.js renders the <head> tags.

  • Static: export const metadata: Metadata = { title, description, openGraph, ... } in layout.tsx or page.tsx (Server Components only).
  • Dynamic: export async function generateMetadata({ params }) for per-record titles. Fetches are memoized, so it can share data with the page.
  • Metadata merges from root layout down to the page; deeper segments override keys. title: { template: '%s | Shop', default: 'Shop' } sets a pattern.
  • File conventions: favicon.ico, icon.png, opengraph-image.tsx (generated with ImageResponse), robots.ts, sitemap.ts, manifest.ts.
  • Viewport and theme colour go in a separate viewport export / generateViewport.
  • SEO wins come from server-rendered HTML, correct status codes (notFound()), canonical URLs (alternates.canonical), and fast Core Web Vitals.

Interview questions

  • How do you set page titles and meta tags in the App Router?
  • How does Next.js help with SEO compared to a plain React SPA?

next/image, next/font, next/link & performance

Built-in components fix the usual Core Web Vitals problems: image size, font layout shift and slow navigation.

  • next/image: resizes and converts to modern formats (WebP/AVIF) on demand, lazy-loads by default, reserves space with width/height or fill to prevent CLS, and serves srcset via sizes. Remote hosts must be allowed with images.remotePatterns.
  • Mark the LCP hero image with preload (v16; priority is now deprecated) or loading="eager" so it is not lazy-loaded.
  • next/font (next/font/google or next/font/local) downloads fonts at build time, self-hosts them (no request to Google at runtime), and uses size-adjusted fallbacks to avoid layout shift.
  • next/link does client-side navigation and prefetches routes when links enter the viewport in production. Static routes prefetch fully; dynamic routes prefetch down to the nearest loading.tsx. prefetch={false} turns it off.
  • next/script controls third-party scripts with strategy: beforeInteractive, afterInteractive (default), lazyOnload.
  • Other wins: keep Client Components small, use next/dynamic for heavy client-only widgets, analyse bundles, and enable the React Compiler (reactCompiler: true, stable in v16) for automatic memoization.

Interview questions

  • What does next/image do for you?
  • How does next/font prevent layout shift?
  • How does prefetching with <Link> work?
  • How would you improve a slow Next.js page?

Hydration errors & fixes

A hydration error means the HTML from the server does not match what React renders first in the browser.

  • Hydration attaches React event handlers and state to server-rendered HTML. React expects the first client render to produce the same markup.
  • Common causes: Date.now() / new Date().toLocaleString(), Math.random() or random IDs, typeof window !== 'undefined' branches, reading localStorage during render, browser extensions changing the DOM, and invalid HTML nesting (<div> inside <p>, <a> inside <a>).
  • Fix 1: move browser-only values into useEffect (render a placeholder first, update after mount).
  • Fix 2: load a client-only component with next/dynamic and { ssr: false } (inside a Client Component).
  • Fix 3: for one unavoidable text mismatch (like a timestamp), add suppressHydrationWarning to that element. It only works one level deep.
  • Use useId() for stable IDs, and format dates on the server with a fixed time zone and locale.

Interview questions

  • What is a hydration error?
  • List common causes of hydration mismatches.
  • How do you fix rendering something that depends on localStorage?

Env vars, build output & deployment

next build produces static assets plus server bundles; env vars without NEXT_PUBLIC_ never reach the browser.

  • Env files load in order of priority: process.env > .env.$(NODE_ENV).local > .env.local (not loaded in test) > .env.$(NODE_ENV) > .env. Commit .env defaults; never commit .env.local.
  • NEXT_PUBLIC_ vars are inlined into the client JS at build time. Changing them later needs a rebuild. Other vars exist only on the server and are read at runtime.
  • next build prints each route as static (○), SSG (●) via generateStaticParams, partial prerender (◐) or dynamic (ƒ). Output goes to .next/.
  • Deploy options: Vercel (zero config), Node server (next start), Docker with output: 'standalone' (copies only needed files and node_modules), or static export with output: 'export' (no server features: no Server Actions, cookies, ISR or Proxy).
  • Self-hosting at scale: share the cache across instances with a custom cache handler (e.g. Redis), set deploymentId / handle version skew, and put a CDN in front of static assets.
  • v16: Turbopack is the default bundler for dev and build (--webpack to opt out), Node.js 20.9+ is required, and next build no longer runs lint.

Interview questions

  • How do environment variables work in Next.js?
  • Why did my NEXT_PUBLIC_ variable not change after redeploying with new env values?
  • What does output: 'standalone' do?
  • How do you self-host Next.js with several replicas?