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.
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. 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.tsxis shown. There's no full document reload.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 shellWith 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. 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.remoteuses a handler fromcacheHandlers(Redis, a platform KV) - more reliable but more expensive. Access to request data comes from'use cache: private', notremote.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,
revalidateTagon one pod doesn't invalidate the cache on others, and users see different versions. You should also configuredeploymentIdto protect against version skew during rolling updates.6. What do the
stale,revalidateandexpireparameters incacheLifemean?Correct answer: Freshness on the client, background refresh and the full expiration time
staleis how long the client uses data without checking the server. Afterrevalidate, the next request gets the cached value and triggers regeneration in the background. Afterexpirewithout requests, the entry is considered expired, and the next request waits for a new value.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
OriginwithHost(orX-Forwarded-Host), rejecting requests from other sites. Together with SameSite cookies, this blocks most CSRF attacks. For complex proxy setups there'sserverActions.allowedOrigins. Authorization is still checked inside the action.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. 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. 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
taintin the config.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. Why does
error.tsxin production get a generic message for an error from a server component?Correct answer: Next.js hides the details and passes a
digestfor looking it up in logsError 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. What changed in
next/imagedefaults in Next.js 16?Correct answer:
minimumCacheTTLgrew to 4 hours, andprioritywas replaced bypreloadPreviously, images without
Cache-Controlwere revalidated every 60 seconds, which loaded the CPU. Now the default TTL is 4 hours. Thepriorityprop is deprecated in favor of the more explicitpreload. Also, local images with a query string requireimages.localPatterns.search, and the defaultqualitiesis[75].14. Which runtime does
proxy.tsuse 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
middlewarefor now. The runtime of routes (pages, Route Handlers) is still configured separately.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. What does
optimizePackageImportsdo?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. When do you need the
serverExternalPackagesoption?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 fromnode_modulesat runtime. Popular cases are already on the default list.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. What is the
instrumentation.tsfile with aregister()function for?Correct answer: Running code once on server startup, e.g. to set up OpenTelemetry
registeris called when a new server instance starts - suitable for initializing tracing, monitoring and logging.onRequestErrorlets you send server errors to a monitoring system. For the client side there'sinstrumentation-client.ts.20. How do you implement on-demand ISR via a CMS webhook?
Correct answer: A Route Handler checks a secret and calls
revalidateTag/revalidatePathThe CMS sends a POST to
/api/revalidatewith 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. 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>wrappercreateContextand providers are client features. You createproviders.tsxwith'use client'and render it in the root layout aroundchildren. That waychildrenstay server components. Providers are placed as deep as possible so more of the tree stays static.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. How do you get configuration from an environment variable at runtime rather than at build time?
Correct answer: Read
process.envon the server during dynamic renderingNEXT_PUBLIC_*variables are inlined into the bundle duringnext build, so one Docker image can't be promoted across environments with different values. Server code readsprocess.envat runtime; if the value is needed on the client, pass it via props from a dynamically rendered server component.24. What is version skew, and how does
deploymentIdhelp 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. Why can't
generateStaticParamsreturn 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 withnotFound(), but that weakens the check.26. How do
GETRoute 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. Accessingrequest,cookies()orheaders()makes the response dynamic. Methods other thanGETare always dynamic.27. What does the user get if a Server Action calls
revalidatePathand 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. How do you connect
forbidden()andunauthorized()to UI?Correct answer: Enable
authInterruptsand addforbidden.tsxThe 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, viaredirect().29. How does metadata from
generateMetadatabehave 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 viahtmlLimitedBots) get the metadata in<head>before the HTML is sent, so SEO doesn't suffer.30. When should you enable
reactCompilerin 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. How does
unstable_rethrowhelp with error handling?Correct answer: It rethrows Next.js internal errors out of
catchNext.js uses exceptions for control flow:
redirect,notFound, dynamic rendering signals. A broadtry/catchswallows them and breaks behavior.unstable_rethrow(err)at the start ofcatchrethrows such errors and leaves you only the "real" ones.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. What are Multi-Zones?
Correct answer: Several independent Next.js apps under one domain, split by path
For example,
/blogand/shopare 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. 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. 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.tsxor Suspense. Navigation becomes instant: the user sees a skeleton right away. With Partial Prefetching, the details depend on the PPR shell.36. How does
refresh()fromnext/cachediffer fromrevalidatePath?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, withoutrevalidatePath/revalidateTag/updateTagthe user sees the old value.37. How does Next.js 16 speed up repeated runs of
next devandnext 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/cachefolder between builds.next buildruns type checking unless it's explicitly disabled.38. What is
typedRoutesuseful for?Correct answer: TypeScript checks paths in
<Link href>androuter.pushNext.js generates types for all routes, and a typo in
href="/dashbord"becomes a compile error. The same generated types power thePageProps/LayoutPropshelpers. The option doesn't affect routing speed.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. 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;
suppressHydrationWarningon the element with the timestamp. Browser extensions also often cause mismatches.41. What does
after()in a Route Handler give you compared toawait 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
aftercallbacks finish. Inside, you can readcookies()andheaders()in Server Actions and Route Handlers.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. Readingcookies()inside a cached function is forbidden. Note that personal data in a shared server cache is a reason to consider'use cache: private'.43. How does the URL-preserving modal pattern work in the App Router?
Correct answer: An
@modalslot, an(.)photo/[id]interception anddefault.tsxOn 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.tsxguarantees an empty slot when the modal isn't active.44. What's the right outcome for an error in
generateStaticParamsduring the build?Correct answer: The build fails, and the broken version doesn't reach production
generateStaticParamsruns duringnext buildbefore 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. Why does reading
searchParamsat the top level of a page reduce the benefit of PPR?Correct answer: Everything below
await searchParamsdrops out of the static shellSearch params are request data. If
await searchParamsis 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. Which command generates the
PagePropsandLayoutPropstypes without running the dev server?Correct answer:
next typegennext typegen(since Next.js 15.5) generates global type helpers from the route structure - handy in CI beforetsc --noEmit. The types are also updated duringnext devandnext build.47. How does
htmlLimitedBotsdiffer 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. What happens if a layout calls
await paramsat the top level with Cache Components and nogenerateStaticParams?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 awaitparamsat 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. 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. 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. 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 requirescacheComponentsand has no effect withoutpartialPrefetching.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. What does
export const instant = truein 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. Why does
useOffline()fromnext/offlinealways returnfalsein a project?Correct answer: The
experimental.useOfflineflag isn't enabledThe flag turns on connectivity detection and automatic retry of blocked navigations, prefetches and Server Actions. The hook is also
falseon the server and before hydration.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().bfcacheIdRoutes are hidden with
<Activity>rather than unmounted.bfcacheIdchanges on push/replace but not on back/forward, which mirrors browser bfcache semantics.56. How can a
'use cache'component acceptchildrenif 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. Why does a
'use cache'function withcacheLife('seconds')end up as a dynamic hole instead of in the prerendered page?Correct answer: Entries with
expireunder 5 minutes skip prerendersVery short-lived data would be outdated right after the build. A
staleunder 30 seconds is excluded too, since a prefetch would expire before the click.58. Where do you plug in a shared cache store (e.g. Redis) for
'use cache'when self-hosting?Correct answer: The
cacheHandlersoption innext.configCustom handlers let several instances share
'use cache'/'use cache: remote'entries and tag invalidation instead of each pod keeping its own memory cache.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. Why can
next devandnext buildrun at the same time in Next.js 16?Correct answer: They use separate directories: dev writes to
.next/devPreviously both wrote to
.next, so a build could break a running dev server. Tools that read.nextdirectly may need path updates.61.
publicRuntimeConfigwas 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. Readingprocess.envin a dynamically rendered server component (e.g. afterconnection()) picks up the deploy's runtime values.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-behaviorby default because the manipulation was costly on every navigation. The attribute opts back into the old behavior.63. Why is
images.domainsdeprecated in favor ofimages.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. 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.dangerouslyAllowLocalIPshould be enabled only on private networks;maximumRedirectsnow defaults to 3 for the same reason.65. Why shouldn't a server component
fetchyour 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. 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. 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.
useEffectcauses a flash, and rendering client values during hydration causes a mismatch; an inline script runs before paint.68. How does
generateStaticParamswork 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.
notFound()is called inside a component that streams in a<Suspense>boundary. What does the crawler get?Correct answer: Status 200 plus a
noindexmeta tag in the HTMLStarting 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. Why should
proxy.tsdo 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. 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-maxageandstale-while-revalidate. Call the CDN purge API for both HTML and RSC variants alongside revalidation.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. Where does Turbopack configuration live in Next.js 16?
Correct answer: In the top-level
turbopackkey ofnext.configTurbopack is the default bundler for dev and build. A custom
webpackconfig makes the build fail unless you opt out with--webpackor migrate it.74. What changed for the props of
opengraph-image,iconandapple-iconfunctions in Next.js 16?export default async function Image({ params, id }) { const { slug } = await params const imageId = await id }Correct answer:
paramsandidare now Promises and must be awaitedIt matches the async request APIs elsewhere in Next.js 16. The same applies to the
idargument ofsitemapwithgenerateSitemaps.75. With Cache Components, when is
connection()still the right choice overio()?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.