Next.js Senior cheat sheet: interview answers

Every question of this level with its correct answer and explanation, on one page for a quick review before the interview.

Quick reference: Key concepts and pitfalls on a couple of pages →
  1. 1. What is the RSC payload?

    Correct answer: The serialized render result of Server Components with references to client ones

    The payload contains the rendered tree of server components, placeholders for client components with references to their JS chunks, and their props. On the first load it's embedded in the HTML (for hydration); during client navigation it's fetched separately. Server component code never reaches the browser.

  2. 2. What happens during client navigation via <Link> in the App Router?

    Correct answer: The new segment's RSC payload is loaded, and React updates only the changed parts

    The router requests the payload (or takes a prefetched one from the client cache) and reconciles it with the current tree: shared layouts are preserved and client state isn't lost. If the segment is still loading, loading.tsx is shown. There's no full document reload.

  3. 3. With cacheComponents: true, the dev overlay shows "blocking route". What does it mean?

    Correct answer: Uncached data is read outside <Suspense> and blocks the static shell

    With Cache Components, every piece of async work must be either cached via 'use cache' (it goes into the shell) or wrapped in <Suspense> (it streams at request time). Otherwise the whole page would wait for data. This rule is checked in development and at build time.

  4. 4. How does 'use cache: remote' differ from 'use cache'?

    Correct answer: It stores the result in a remote handler shared by all instances, at the cost of network latency

    Plain 'use cache' stores entries in process memory (LRU) by default, so in serverless and with multiple instances the cache is short-lived and not shared. remote uses a handler from cacheHandlers (Redis, a platform KV) - more reliable but more expensive. Access to request data comes from 'use cache: private', not remote.

  5. 5. What do you need to consider when self-hosting Next.js on several Kubernetes pods?

    Correct answer: The cache is local to each instance by default; you need a shared cache handler

    By default, generated pages and data are stored in each pod's memory and disk. Without shared storage, revalidateTag on one pod doesn't invalidate the cache on others, and users see different versions. You should also configure deploymentId to protect against version skew during rolling updates.

  6. 6. What do the stale, revalidate and expire parameters in cacheLife mean?

    Correct answer: Freshness on the client, background refresh and the full expiration time

    stale is how long the client uses data without checking the server. After revalidate, the next request gets the cached value and triggers regeneration in the background. After expire without requests, the entry is considered expired, and the next request waits for a new value.

  7. 7. How does Next.js protect Server Actions from CSRF?

    Correct answer: It accepts only POST and compares the Origin header with Host

    Server Actions can be invoked only with POST, and Next.js compares Origin with Host (or X-Forwarded-Host), rejecting requests from other sites. Together with SameSite cookies, this blocks most CSRF attacks. For complex proxy setups there's serverActions.allowedOrigins. Authorization is still checked inside the action.

  8. 8. Why shouldn't Server Actions be used for loading data?

    Correct answer: The client calls them one at a time, as uncached POSTs - slow for reads

    Next.js dispatches Server Actions from one client sequentially: the second waits for the first so the server tree stays consistent with the result. That's good for mutations but bad for parallel reads. Load data in Server Components (or Route Handlers) and keep actions for changes.

  9. 9. A Server Action is declared inside a component and uses a variable from its closure. What happens to it?

    Correct answer: Captured values are encrypted, sent to the client and sent back on invocation

    Next.js serializes captured variables, encrypts them and embeds them in the page so the closure can be restored on invocation. Encryption protects against accidental leaks, but it's better not to keep secrets in closures. Multiple instances need a shared encryption key (NEXT_SERVER_ACTIONS_ENCRYPTION_KEY).

  10. 10. What is the React Taint API (experimental_taintObjectReference) for in Next.js?

    Correct answer: To forbid passing a specific object to a client component

    For example, mark a user object from the DB: if it's passed whole into a client component's props, you get an error. It's a safety net, not the main protection - the foundation is a Data Access Layer that returns only the needed fields. It requires enabling taint in the config.

  11. 11. Why does a CSP with a nonce make pages dynamic?

    Correct answer: The nonce is unique per response, so the HTML can't be prerendered

    Next.js reads the nonce from a request header (generated by proxy) and adds it to its scripts. Static HTML with a fixed nonce makes no sense. An alternative that keeps static rendering is a hash-based CSP or looser policies.

  12. 12. Why does error.tsx in production get a generic message for an error from a server component?

    Correct answer: Next.js hides the details and passes a digest for looking it up in logs

    Error text can contain SQL, paths and secrets, so the client gets a generic message plus error.digest - a hash for finding the full error in server logs. In development the full message is available.

  13. 13. What changed in next/image defaults in Next.js 16?

    Correct answer: minimumCacheTTL grew to 4 hours, and priority was replaced by preload

    Previously, images without Cache-Control were revalidated every 60 seconds, which loaded the CPU. Now the default TTL is 4 hours. The priority prop is deprecated in favor of the more explicit preload. Also, local images with a query string require images.localPatterns.search, and the default qualities is [75].

  14. 14. Which runtime does proxy.ts use in Next.js 16?

    Correct answer: Node.js, with no option to switch to Edge

    In Next.js 16, proxy always runs on Node.js: familiar libraries and APIs are available. If you specifically need the edge runtime, stay on the deprecated middleware for now. The runtime of routes (pages, Route Handlers) is still configured separately.

  15. 15. What prefetching optimizations appeared in the Next.js 16 router?

    Correct answer: Layout deduplication and incremental prefetching of only the missing parts

    If several links lead to pages with a shared layout, it's downloaded once. The router loads only what isn't already in the client cache. There may be more requests, but their total size is noticeably smaller. No code changes are needed.

  16. 16. What does optimizePackageImports do?

    Correct answer: Loads only the used modules from libraries with barrel files

    Importing import { Icon } from 'big-icon-lib' through a barrel file can pull in hundreds of modules and slow down the build and the dev server. The option rewrites imports to the specific modules. For some popular libraries Next.js does this automatically.

  17. 17. When do you need the serverExternalPackages option?

    Correct answer: When a server package can't be bundled, e.g. one with native modules

    By default, Next.js bundles the dependencies of server code. Some packages (with native bindings, dynamic requires, large binaries) break when bundled - they're marked as external and loaded from node_modules at runtime. Popular cases are already on the default list.

  18. 18. What is Draft Mode for?

    Correct answer: Temporarily rendering static pages dynamically to preview CMS drafts

    A CMS editor visits a special Route Handler that calls (await draftMode()).enable() and sets a cookie. While the cookie is present, pages bypass the cache and load draft content. Other visitors keep getting fast static pages.

  19. 19. What is the instrumentation.ts file with a register() function for?

    Correct answer: Running code once on server startup, e.g. to set up OpenTelemetry

    register is called when a new server instance starts - suitable for initializing tracing, monitoring and logging. onRequestError lets you send server errors to a monitoring system. For the client side there's instrumentation-client.ts.

  20. 20. How do you implement on-demand ISR via a CMS webhook?

    Correct answer: A Route Handler checks a secret and calls revalidateTag/revalidatePath

    The CMS sends a POST to /api/revalidate with a secret and the ID of the changed entry; the handler verifies the signature and invalidates the relevant tags. Pages update on the next request, without a full rebuild. router.refresh() is a client-side API.

  21. 21. Why are Context providers in the App Router moved into a separate client component?

    Correct answer: Context is a client feature; the layout renders a <Providers> wrapper

    createContext and providers are client features. You create providers.tsx with 'use client' and render it in the root layout around children. That way children stay server components. Providers are placed as deep as possible so more of the tree stays static.

  22. 22. A third-party component uses hooks but has no 'use client'. How do you use it in a server page?

    Correct answer: Re-export it from your own file with 'use client'

    Create components/carousel.tsx: 'use client'; export { Carousel } from 'acme-carousel'. Now the server component imports the client wrapper. Many libraries have already added the directive themselves. Suspense has nothing to do with the client boundary.

  23. 23. How do you get configuration from an environment variable at runtime rather than at build time?

    Correct answer: Read process.env on the server during dynamic rendering

    NEXT_PUBLIC_* variables are inlined into the bundle during next build, so one Docker image can't be promoted across environments with different values. Server code reads process.env at runtime; if the value is needed on the client, pass it via props from a dynamically rendered server component.

  24. 24. What is version skew, and how does deploymentId help with it?

    Correct answer: An old-version client and a new-version server; the ID helps detect it

    A user with a tab open after a deploy may request chunks or Server Actions that no longer exist. With deploymentId, Next.js adds an identifier to asset and navigation requests and, on mismatch, does a full reload instead of producing cryptic errors.

  25. 25. Why can't generateStaticParams return an empty array with Cache Components?

    Correct answer: It needs sample params to validate the route at build time

    The build renders the route with sample params and checks that cookies(), headers() and other request data sit inside Suspense. Without samples, validation is impossible, so it's a build error. You can return a placeholder and handle it with notFound(), but that weakens the check.

  26. 26. How do GET Route Handlers behave with Cache Components enabled?

    Correct answer: They follow the same prerendering model as pages

    If the handler doesn't read request data, its response can be prerendered at build time; use 'use cache' for cacheable parts. Accessing request, cookies() or headers() makes the response dynamic. Methods other than GET are always dynamic.

  27. 27. What does the user get if a Server Action calls revalidatePath and returns a value?

    Correct answer: The action's result and the updated RSC tree in one response

    Next.js optimizes mutations: the Server Action response contains both the returned value and the new payload of the affected routes (a single roundtrip). The user immediately sees the updated UI without an extra request.

  28. 28. How do you connect forbidden() and unauthorized() to UI?

    Correct answer: Enable authInterrupts and add forbidden.tsx

    The functions interrupt rendering and show the corresponding UI with 403 and 401 statuses - similar to notFound(). It's an experimental feature for now. Redirecting to login is done separately, via redirect().

  29. 29. How does metadata from generateMetadata behave during streaming?

    Correct answer: It streams after the UI, but for HTML-only bots the response waits for it

    Streaming metadata avoids delaying the first byte with a slow generateMetadata. Bots that don't run JS (detected by User-Agent, configurable via htmlLimitedBots) get the metadata in <head> before the HTML is sent, so SEO doesn't suffer.

  30. 30. When should you enable reactCompiler in Next.js 16?

    Correct answer: When the code follows the rules of React; builds get slower

    In Next.js 16, React Compiler support is stable but disabled by default. The compiler relies on Babel, so builds get slower. It skips components that break the rules of React - the ESLint plugin helps find them.

  31. 31. How does unstable_rethrow help with error handling?

    Correct answer: It rethrows Next.js internal errors out of catch

    Next.js uses exceptions for control flow: redirect, notFound, dynamic rendering signals. A broad try/catch swallows them and breaks behavior. unstable_rethrow(err) at the start of catch rethrows such errors and leaves you only the "real" ones.

  32. 32. Why shouldn't a layout be the only place where authorization is checked?

    Correct answer: A layout doesn't re-render during client navigation between child pages

    Thanks to partial rendering, a shared layout doesn't run again during navigation within a segment, so a check in it may not fire. Besides, Route Handlers and Server Actions are reachable directly. Keep checks close to the data - in the Data Access Layer, pages and actions.

  33. 33. What are Multi-Zones?

    Correct answer: Several independent Next.js apps under one domain, split by path

    For example, /blog and /shop are separate apps from different teams, combined via rewrites. Navigation between zones is a full reload (plain <a>), within a zone it's client-side. It's one approach to micro-frontends.

  34. 34. Why is page data sometimes sent twice - in the HTML and in the RSC payload?

    Correct answer: HTML is for fast painting, the payload is for hydration

    Client component props are serialized into the payload embedded in the page, even if the same data is already visible in the HTML. So large arrays passed to client components bloat the response. Pagination, passing minimal fields and rendering large static parts on the server help.

  35. 35. What is prefetched for a dynamic route by <Link> with default settings?

    Correct answer: The tree up to the nearest loading boundary

    For static content everything is prefetched; for dynamic routes, the shared static part and the fallback up to loading.tsx or Suspense. Navigation becomes instant: the user sees a skeleton right away. With Partial Prefetching, the details depend on the PPR shell.

  36. 36. How does refresh() from next/cache differ from revalidatePath?

    Correct answer: It refreshes the client router only, not the cache

    refresh() in a Server Action makes the client router refetch the current page - e.g. to update a notification counter whose data isn't cached. If the data is cached, without revalidatePath/revalidateTag/updateTag the user sees the old value.

  37. 37. How does Next.js 16 speed up repeated runs of next dev and next build?

    Correct answer: Turbopack caches build artifacts on disk by default

    Turbopack's file system cache is enabled by default for dev and build, so restarts are noticeably faster. In CI, it's useful to cache the .next/cache folder between builds. next build runs type checking unless it's explicitly disabled.

  38. 38. What is typedRoutes useful for?

    Correct answer: TypeScript checks paths in <Link href> and router.push

    Next.js generates types for all routes, and a typo in href="/dashbord" becomes a compile error. The same generated types power the PageProps/LayoutProps helpers. The option doesn't affect routing speed.

  39. 39. How does the Edge runtime differ from Node.js for routes?

    Correct answer: Edge - a reduced set of Web APIs and fast startup; Node.js - the full API

    The Edge runtime runs closer to the user and starts quickly, but it lacks fs, many npm packages and native modules, plus it has size limits. Node.js is recommended for most apps. In Next.js 16, proxy runs only on Node.js.

  40. 40. A component shows new Date().toLocaleString() and causes a hydration mismatch. What's the most correct fix?

    Correct answer: Show the time after mounting or fix it on the server

    The server and the client are in different time zones and moments in time, so the string differs. Options: a client component that shows the time after mounting; formatting on the server with a fixed zone; suppressHydrationWarning on the element with the timestamp. Browser extensions also often cause mismatches.

  41. 41. What does after() in a Route Handler give you compared to await logEvent() before responding?

    Correct answer: The response is sent immediately, and logging runs afterwards

    The user doesn't have to wait for analytics, logs or syncing with third-party services. The platform keeps the function alive until the after callbacks finish. Inside, you can read cookies() and headers() in Server Actions and Route Handlers.

  42. 42. How do you make sure a 'use cache' function doesn't cache different users' data together?

    Correct answer: Pass the user ID as an argument: it becomes part of the key

    The cache key is built from arguments and captured values, so getDashboard(userId) creates separate entries. Reading cookies() inside a cached function is forbidden. Note that personal data in a shared server cache is a reason to consider 'use cache: private'.

  43. 43. How does the URL-preserving modal pattern work in the App Router?

    Correct answer: An @modal slot, an (.)photo/[id] interception and default.tsx

    On client navigation, the interceptor renders content in the modal slot over the current page; the URL reflects the open item, and the link can be shared. On direct access, the full page opens. Closing is router.back(). default.tsx guarantees an empty slot when the modal isn't active.

  44. 44. What's the right outcome for an error in generateStaticParams during the build?

    Correct answer: The build fails, and the broken version doesn't reach production

    generateStaticParams runs during next build before pages render. An error (e.g. an unavailable API) aborts the build - better than shipping an app without pages. If the source is unreliable, you can return a subset of paths and render the rest on demand.

  45. 45. Why does reading searchParams at the top level of a page reduce the benefit of PPR?

    Correct answer: Everything below await searchParams drops out of the static shell

    Search params are request data. If await searchParams is at the page root, the static shell is almost empty. Better to pass the promise down and unwrap it in a component inside <Suspense>, keeping the heading, filters and navigation in the shell.

  46. 46. Which command generates the PageProps and LayoutProps types without running the dev server?

    Correct answer: next typegen

    next typegen (since Next.js 15.5) generates global type helpers from the route structure - handy in CI before tsc --noEmit. The types are also updated during next dev and next build.

  47. 47. How does htmlLimitedBots differ from regular bot handling?

    Correct answer: It defines the bots that get metadata without streaming

    Some crawlers don't run JavaScript and can't see metadata that arrives via streaming. Next.js detects them by User-Agent and waits for the metadata before sending HTML. The option lets you override the list.

  48. 48. What happens if a layout calls await params at the top level with Cache Components and no generateStaticParams?

    Correct answer: The layout drops out of the shell; better to pass the promise down

    Without generateStaticParams, param values are known only at request time - they're runtime data. The docs advise not to await params at the top level of a layout, but to pass the promise to the component that actually needs the value and wrap it in Suspense.

  49. 49. How does 'use cache' caching work on a serverless platform with the default handler?

    Correct answer: Entries live in instance memory and aren't shared between instances

    The default handler is an in-memory LRU. In serverless, instances are short-lived and isolated, so the runtime cache is short-lived. The main value of 'use cache' is including data in the static shell at build time. For a reliable runtime cache, you need a remote handler or the platform's cache.

  50. 50. Why do Server Actions get encrypted, non-deterministic IDs?

    Correct answer: So the IDs are hard to guess and unused actions can be removed

    Next.js creates IDs for action references and periodically recalculates them between builds; unused Server Actions are removed from the client bundle (dead code elimination). But any used ID is visible in network requests - so permission checks inside the action are mandatory.

  51. 51. With Partial Prefetching enabled, what does await prefetch() inside a component do?

    async function Recommendations() {
      await prefetch()
      const items = await getRecommendations()
      return <List items={items} />
    }

    Correct answer: Keeps the work below it out of the App Shell

    The nearest <Suspense> fallback goes into the shell instead. It requires cacheComponents and has no effect without partialPrefetching.

  52. 52. What does export const ensureStatic = 'shell' guarantee for a route?

    Correct answer: The build fails if the App Shell turns request-time

    Levels are 'shell', 'prefetch' and 'navigation', each stricter than the previous one. It works only with Cache Components and protects performance from regressions.

  53. 53. What does export const instant = true in a segment do?

    Correct answer: Navigations must render instantly; blockers are reported

    It's a validation tool for Cache Components. Validation reflects production behavior, because prefetching is disabled in development.

  54. 54. Why does useOffline() from next/offline always return false in a project?

    Correct answer: The experimental.useOffline flag isn't enabled

    The flag turns on connectivity detection and automatic retry of blocked navigations, prefetches and Server Actions. The hook is also false on the server and before hydration.

  55. 55. With Cache Components, how do you reset a subtree on <Link> navigation but still restore it on browser Back?

    const { bfcacheId } = useRouter()
    return <Fragment key={bfcacheId}>{children}</Fragment>

    Correct answer: Key the subtree with useRouter().bfcacheId

    Routes are hidden with <Activity> rather than unmounted. bfcacheId changes on push/replace but not on back/forward, which mirrors browser bfcache semantics.

  56. 56. How can a 'use cache' component accept children if JSX can't be serialized as a cache key?

    Correct answer: Elements may pass through, but not be inspected

    Pass-through values don't affect the cached result, so the cached shell can wrap dynamic content. The same applies to functions passed through to client components.

  57. 57. Why does a 'use cache' function with cacheLife('seconds') end up as a dynamic hole instead of in the prerendered page?

    Correct answer: Entries with expire under 5 minutes skip prerenders

    Very short-lived data would be outdated right after the build. A stale under 30 seconds is excluded too, since a prefetch would expire before the click.

  58. 58. Where do you plug in a shared cache store (e.g. Redis) for 'use cache' when self-hosting?

    Correct answer: The cacheHandlers option in next.config

    Custom handlers let several instances share 'use cache' / 'use cache: remote' entries and tag invalidation instead of each pod keeping its own memory cache.

  59. 59. What is the Build Adapters API (adapterPath) for?

    Correct answer: Letting platforms map build output to their infrastructure

    Instead of reverse-engineering build output, a platform adapter receives a documented description of routes and functions. Vercel's adapter is a reference implementation.

  60. 60. Why can next dev and next build run at the same time in Next.js 16?

    Correct answer: They use separate directories: dev writes to .next/dev

    Previously both wrote to .next, so a build could break a running dev server. Tools that read .next directly may need path updates.

  61. 61. publicRuntimeConfig was removed in Next.js 16. How do you provide config that differs per environment without rebuilding?

    Correct answer: Read server env at request time and pass values down

    NEXT_PUBLIC_ values are inlined at build time. Reading process.env in a dynamically rendered server component (e.g. after connection()) picks up the deploy's runtime values.

  62. 62. The site uses scroll-behavior: smooth, and after upgrading to Next.js 16 every navigation scrolls smoothly to the top. How do you restore instant jumps?

    Correct answer: Add data-scroll-behavior="smooth" to <html>

    Next.js 16 no longer overrides scroll-behavior by default because the manipulation was costly on every navigation. The attribute opts back into the old behavior.

  63. 63. Why is images.domains deprecated in favor of images.remotePatterns?

    Correct answer: Patterns also restrict protocol, port and path

    A whole domain is often too broad, e.g. a CDN host serving user uploads. Narrow patterns reduce the image optimizer's attack surface.

  64. 64. Why does Next.js 16 block optimizing images from local IP addresses by default?

    Correct answer: To prevent SSRF through the image optimizer

    The optimizer fetches URLs from the server's network. images.dangerouslyAllowLocalIP should be enabled only on private networks; maximumRedirects now defaults to 3 for the same reason.

  65. 65. Why shouldn't a server component fetch your own Route Handler (/api/products) for data?

    Correct answer: It adds a round trip and fails during prerendering

    Call the data source or a shared data-access function directly. Route Handlers are for external clients: mobile apps, webhooks, third parties.

  66. 66. A Server Action deletePost(id) is used only on an admin page. Why must it still check authorization itself?

    Correct answer: Every Server Action is a public POST endpoint

    Validate inputs (e.g. with Zod) and verify the session and permissions inside the action or in the data-access layer it calls.

  67. 67. How do you apply a saved theme or locale-specific date before the first paint without a hydration error or flash?

    Correct answer: A small inline script that runs during HTML parsing

    The server can't know client preferences. useEffect causes a flash, and rendering client values during hydration causes a mismatch; an inline script runs before paint.

  68. 68. How does generateStaticParams work for nested dynamic segments like /[category]/[product]?

    // app/[category]/[product]/page.tsx
    export async function generateStaticParams({ params }) {
      const { category } = params
      return (await getProducts(category)).map((p) => ({ product: p.slug }))
    }

    Correct answer: The child's function runs once per parent result

    Alternatively, the child can return both params at once. Top-down generation keeps each level's data fetching small.

  69. 69. notFound() is called inside a component that streams in a <Suspense> boundary. What does the crawler get?

    Correct answer: Status 200 plus a noindex meta tag in the HTML

    Starting the stream fixes the status code. For a real 404 status, call notFound() before anything streams, e.g. at the top of the page.

  70. 70. Why should proxy.ts do only optimistic auth checks?

    Correct answer: It runs on many requests, prefetches included

    Slow checks in proxy delay every navigation. A data access layer that verifies the session before reading data is the source of truth.

  71. 71. A CDN in front of a self-hosted Next.js keeps serving an old page after revalidateTag(). Why?

    Correct answer: Revalidation clears only the Next.js server cache

    ISR pages are sent with s-maxage and stale-while-revalidate. Call the CDN purge API for both HTML and RSC variants alongside revalidation.

  72. 72. A catalog has 1M products. How do you build quickly but still serve all of them statically (without Cache Components)?

    Correct answer: Prebuild the popular ones; the rest render on first request

    Build time scales with prerendered pages. On-demand generation fills the cache gradually, and ISR revalidation keeps pages fresh.

  73. 73. Where does Turbopack configuration live in Next.js 16?

    Correct answer: In the top-level turbopack key of next.config

    Turbopack is the default bundler for dev and build. A custom webpack config makes the build fail unless you opt out with --webpack or migrate it.

  74. 74. What changed for the props of opengraph-image, icon and apple-icon functions in Next.js 16?

    export default async function Image({ params, id }) {
      const { slug } = await params
      const imageId = await id
    }

    Correct answer: params and id are now Promises and must be awaited

    It matches the async request APIs elsewhere in Next.js 16. The same applies to the id argument of sitemap with generateSitemaps.

  75. 75. With Cache Components, when is connection() still the right choice over io()?

    Correct answer: When the code must wait for a real user request

    io() suspends like any async call, so the code after it can still be cached and prefetched. connection() stays suspended until a navigation reaches the server.