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
- App Router (
app/) is the modern default: React Server Components, nested layouts, streaming, Server Actions. Pages Router (pages/) is older but still supported, withgetStaticProps/getServerSideProps. - A folder is a route segment; it becomes public only when it has a
page.tsx(UI) orroute.ts(API). Other files can be colocated safely. - Special files:
layout(persists, keeps state),template(remounts on every navigation),loading(Suspense fallback),error(client error boundary),not-found,default(parallel-route fallback). [id]= dynamic segment,[...slug]= catch-all (1+ parts),[[...slug]]= optional catch-all (0+).(group)folders organise code without changing the URL._folderis private.- Since v15,
params,searchParams,cookies(),headers()anddraftMode()are async. In v16 the sync fallback is removed: alwaysawaitthem. - 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. - 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. - 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).
- v15 caching flip:
fetch,GETRoute Handlers and the client Router Cache for pages are not cached by default. Opt in withcache: 'force-cache',next.revalidate, or'use cache'. - 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. - Revalidate on demand with
revalidatePath(path)orrevalidateTag(tag, 'max')(v16 needs a profile).updateTag(tag)gives read-your-writes inside a Server Action. - 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. - Route Handlers (
app/api/x/route.ts) exportGET,POSTand so on, using WebRequest/Response. A folder cannot have bothpageandroute. - v16 renamed
middleware.tstoproxy.ts(exportproxy); it runs on Node.js. Use it for redirects, rewrites and cheap optimistic auth checks, not as the only security layer. - Only
NEXT_PUBLIC_*env vars reach the browser, and they are inlined at build time. Everything else is server-only. - Hydration errors mean server HTML ≠ first client render:
Date.now(),Math.random(),windowchecks, locale formatting, invalid HTML nesting. Fix withuseEffect, stable data, orsuppressHydrationWarningfor 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, andpage.tsxmakes 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 fromgetStaticProps,getStaticPathsandgetServerSideProps; API routes live inpages/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
pageandroutefiles are routable, you can colocate components, tests and styles insideapp/safely. Prefix a folder with_to mark it private. - Navigation uses
<Link>(client-side transitions with prefetching) anduseRouter()fromnext/navigationin the App Router (next/routeris 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.tsxwraps a segment and its children. It persists across navigations, keeps state and does not re-render when you move between sibling pages.template.tsxis 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.tsxbecomes a<Suspense>fallback around the page. It shows instantly during navigation and enables streaming.error.tsxis a React error boundary and must be a Client Component. It receiveserrorand areset()function to re-render the segment (v16.2 also added anunstable_retryprop that re-fetches). It does not catch errors in the layout of the same segment.global-error.tsxcatches errors in the root layout and must render its own<html>and<body>.not-found.tsxrenders when you callnotFound()or a URL matches nothing.default.tsxis the fallback for parallel-route slots.
Interview questions
- What is the difference between
layout.tsxandtemplate.tsx? - How does
loading.tsxwork? - Why must
error.tsxbe 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.tsxmatches/blog/hellowithparams = { slug: 'hello' }.[...slug]is a catch-all:/shop/a/bgives{ slug: ['a','b'] }and/shopdoes not match.[[...slug]]is optional and also matches/shop.- In v15+
paramsandsearchParamsare Promises:const { slug } = await params. In Client Components use React'suse(params)or theuseParams()hook. generateStaticParams()returns the param values to prerender at build time.export const dynamicParams = falsemakes 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)/aboutand(b)/aboutis an error).
Interview questions
- Difference between
[...slug]and[[...slug]]? - What are route groups used for?
- What does
generateStaticParamsdo? - Why are
paramsandsearchParamsPromises 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
@teamis a slot. It is passed to the parent layout as a prop (team) next tochildren. Slots are not URL segments. - Each slot can have its own
loadinganderrorfiles, 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 adefault.tsxor 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,(...)= fromapproot. Levels are route segments, not folders. - The classic use is a modal: clicking a photo in a feed opens
/photo/1in a modal (intercepted), while a refresh or shared link opens the full photo page. - Use parallel routes for conditional UI too, for example showing
@adminor@userbased 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.tsxneeded 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 beasync, 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,onClickor browser APIs. Client Components cannot beasyncor 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
childrenor 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.tsxwith'use client'and render it in the root layout aroundchildren. - 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.tsxis 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 oldexperimental.pprflag andexperimental_pprexport 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
awaityour data:fetch, an ORM, or a DB client. NouseEffectand 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 callgetUser()without double requests. For non-fetch calls, wrap them in Reactcache(). - 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:
fetchis no longer cached by default (no-store unless you opt in),GETRoute Handlers are not cached by default, and the Router Cache usesstaleTime0 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_cachefor non-fetch, and segment configexport const revalidate = 60/dynamic = 'force-static'. - On-demand:
revalidatePath('/blog')clears a route;revalidateTag('posts', 'max')marks tagged data stale (v16 requires the secondcacheLifeprofile 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) andrefresh()(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
revalidatePathandrevalidateTag? - Difference between
revalidateTagandupdateTagin 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: trueinnext.config.ts(this replacedexperimental.dynamicIOand 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 beasync.- 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 forrevalidateTag/updateTag.- Cached scopes cannot read
cookies(),headers()orsearchParams. Read them outside and pass the values in as arguments (they become part of the key). - Arguments and return values must be serializable.
childrenand 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 fromunstable_cacheor 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 receivesFormData. 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), anduseOptimisticfor instant UI. - After a mutation, call
revalidatePath/revalidateTag/updateTagto refresh data, andredirect()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
OriginandHostheaders. Addexperimental.serverActions.allowedOriginsif 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.tsand exportGET,POST,PUT,PATCH,DELETE,HEADorOPTIONS. Unsupported methods get 405. - Handlers use standard Web APIs plus
NextRequest/NextResponsehelpers (req.nextUrl.searchParams,Response.json(), cookies). - Dynamic segments work the same: the second argument is
{ params }, which is a Promise in v15+. - A
route.tsand apage.tsxcannot be in the same folder. - Since v15,
GEThandlers are dynamic by default. Opt into static output withexport 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.tstoproxy.tsand the exported function toproxy(named or default export). The logic is the same;middleware.tsis deprecated. proxy.tssits in the project root (orsrc/), one per project. It runs on the Node.js runtime. The oldmiddleware.tsremains only for Edge-runtime use cases.- Use
export const config = { matcher: [...] }to limit paths. Without a matcher it runs on every request, including_next/staticand 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 andfetchcaching 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,sameSitecookie) or database sessions (cookie holds an ID). - Create a Data Access Layer (DAL): a
server-onlymodule withverifySession()(wrapped in Reactcache()) 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 nofs, 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.tsruns on Node.js; Edge remains available through the deprecatedmiddleware.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, ... }inlayout.tsxorpage.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 withImageResponse),robots.ts,sitemap.ts,manifest.ts. - Viewport and theme colour go in a separate
viewportexport /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 withwidth/heightorfillto prevent CLS, and servessrcsetviasizes. Remote hosts must be allowed withimages.remotePatterns.- Mark the LCP hero image with
preload(v16;priorityis now deprecated) orloading="eager"so it is not lazy-loaded. next/font(next/font/googleornext/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/linkdoes client-side navigation and prefetches routes when links enter the viewport in production. Static routes prefetch fully; dynamic routes prefetch down to the nearestloading.tsx.prefetch={false}turns it off.next/scriptcontrols third-party scripts withstrategy:beforeInteractive,afterInteractive(default),lazyOnload.- Other wins: keep Client Components small, use
next/dynamicfor heavy client-only widgets, analyse bundles, and enable the React Compiler (reactCompiler: true, stable in v16) for automatic memoization.
Interview questions
- What does
next/imagedo for you? - How does
next/fontprevent 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, readinglocalStorageduring 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/dynamicand{ ssr: false }(inside a Client Component). - Fix 3: for one unavoidable text mismatch (like a timestamp), add
suppressHydrationWarningto 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.envdefaults; 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 buildprints each route as static (○), SSG (●) viagenerateStaticParams, partial prerender (◐) or dynamic (ƒ). Output goes to.next/.- Deploy options: Vercel (zero config), Node server (
next start), Docker withoutput: 'standalone'(copies only needed files andnode_modules), or static export withoutput: '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
devandbuild(--webpackto opt out), Node.js 20.9+ is required, andnext buildno 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?