Next.js Middle 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 a Server Function (Server Action) in Next.js?
Correct answer: An async function marked
'use server'that can be called from the clientThe
'use server'directive turns a function into a server function, and Next.js creates an endpoint for it. You can pass it to<form action>or call it from a client handler. The call is a POST request. Server Actions are Server Functions used for mutations, often followed by cache revalidation.2. What does
<form action={createPost}>with a Server Action give you compared toonSubmit+fetch?Correct answer: The form works even before JS loads (progressive enhancement), with no API route
A Server Action receives
FormDatadirectly, so you don't need a Route Handler and a clientfetch. If the form is rendered by a server component, it submits even before hydration. You still write validation yourself (e.g. with Zod). Submission state is shown viauseActionStateoruseFormStatus.3. What does
revalidatePath('/blog')do after a mutation?Correct answer: Marks the cached data and UI of the
/blogroute as staleThe next request to
/bloggets fresh data. When called in a Server Action, the updated UI comes back right in the action's response. For targeted invalidation of data used on many pages, tags are more convenient (cacheTag+revalidateTag/updateTag).4. How does
updateTagdiffer fromrevalidateTagin Next.js 16?Correct answer:
updateTagexpires the cache immediately (read-your-writes),revalidateTagis stale-while-revalidateupdateTagis available only in Server Actions: the user who changed the data sees the changes immediately.revalidateTag(tag, 'max')marks data as stale: visitors see the old version while the new one is prepared in the background - good for blogs and catalogs. In Next.js 16,revalidateTagrequires a second argument - acacheLifeprofile.5. Are
fetchrequests in server components cached by default (Next.js 15+, without Cache Components)?Correct answer: No: they aren't cached by default; enable caching with
cache: 'force-cache'In Next.js 14,
fetchwas cached by default, which often surprised people. Since version 15 the behavior is the opposite. With Cache Components enabled, caching is explicit via'use cache', and uncached data streams inside<Suspense>.6. What does the
'use cache'directive do?Correct answer: Caches the result of an async function or component; arguments are part of the cache key
'use cache'works withcacheComponents: true: at the level of a data function, a component or a whole file. Arguments and captured values become part of the key. The lifetime is set withcacheLife, invalidation tags withcacheTag. A cached result can become part of the page's static shell.7. Why can't you call
cookies()inside a function with'use cache'?Correct answer: The cache is shared; cookies are per-request data
If a cached function read cookies, one user's data could be served to another. The right way is to read cookies outside and pass the needed value as an argument (it becomes part of the key). For rare cases there's
'use cache: private', which doesn't store the result in the server cache across requests.8. Which
cacheLifeprofile applies if you don't specify one in'use cache'?Correct answer:
defaultThe
defaultprofile: stale 5 minutes, revalidate 15 minutes, expire never. There are presetsseconds,minutes,hours,days,weeks,max, and custom profiles innext.config. The docs recommend always specifyingcacheLifeexplicitly so the behavior is clear at the call site.9. What is
cacheTag('products')inside a cached function for?Correct answer: To invalidate entries with this tag later
Tags link cache entries to a type of data rather than a URL. One product mutation can invalidate every page and component that uses products:
revalidateTag('products', 'max'). You can set several tags, e.g. a general one and one with an id:cacheTag('products',product-${id}).10. What does
loading.tsxdo during client navigation to a segment with slow data?Correct answer: Immediately shows a fallback inside the shared layout
Navigation is instant: the layout stays interactive, the
loading.tsxfallback is shown instead of the page, and the content streams in. The fallback can be prefetched along with the link. Withoutloading.tsxor<Suspense>, navigation would wait for the data.11. What does
generateStaticParamsdo?Correct answer: Returns segment values to prerender at build time
export function generateStaticParams() { return posts.map(p => ({ slug: p.slug })) }- these pages are built ahead of time. It replacesgetStaticPathsfrom the Pages Router. With Cache Components, the function must return at least one set of params - that's how the build verifies the route doesn't access request data incorrectly.12. How do you show a page with slow data in Next.js without delaying the whole page?
Correct answer: Wrap the slow component in
<Suspense>- it streams in laterThe server sends the shell and fallback right away and appends the slow block's HTML to the stream when it's ready. Loading in
useEffectsends empty HTML, adds a request waterfall and hurts LCP. With Cache Components, uncached data must be inside<Suspense>.13. How do you avoid a request waterfall if a component needs independent
getUser()andgetPosts()?Correct answer: Start both requests at once and wait with
Promise.allSequential
awaits add up the waiting time.const [user, posts] = await Promise.all([getUser(), getPosts()])runs them in parallel. Another option is to pass promises down and unwrap them withuse()under separate Suspense boundaries so parts of the UI appear independently.14. How do you avoid a double DB query if both
generateMetadataand the page callgetUser(id)?Correct answer: Wrap the function in React's
cache()- deduplication within one requestcache()memoizes calls with the same arguments for the duration of one server render. Next.js deduplicatesfetchwith identical parameters itself, but ORMs and SDKs needcache(). A global variable would mix different users' data.15. How do you guarantee a module with secrets never ends up in the client bundle?
Correct answer: Add
import 'server-only'to itThe
server-onlypackage causes a build error if the module is imported from a client component. This protects against accidentally leaking DB code or keys. There's a matchingclient-onlypackage. The.serversuffix does nothing in the App Router, andpublicis served to everyone.16. Can you use
next/dynamicwithssr: falsein a server component?Correct answer: No:
ssr: falseis allowed only in client componentsUse the
ssr: falseoption inside a'use client'file: for example, for a component that accesseswindowon import. In a server component, Next.js throws an error. Server components don't ship their code to the browser anyway.17. Why wrap a component using
useSearchParams()in<Suspense>?Correct answer: Otherwise everything up to the nearest boundary drops out of prerendering
Query parameters are unknown during prerendering. If a Suspense boundary sits close to the component, the rest of the page goes into static HTML and only this piece renders on the client. Without a boundary, a large part of the tree becomes client-rendered, and Next.js warns about it.
18. What are parallel routes (
@slot)?Correct answer: Named slots rendering several pages in one layout
The
@analyticsfolder becomes theanalyticsprop of the parent layout. Each slot has its own navigation, loading and error states - handy for dashboards and modals. On a full reload, an inactive slot renders itsdefault.tsx(or a 404 if there isn't one).19. What are intercepting routes
(.)photo/[id]for?Correct answer: Showing a route on top of the current page, e.g. in a modal
On client navigation from a feed to
/photo/1, the interceptor renders the photo in a modal over the feed, and the URL changes. On direct access or page reload, the full/photo/1page opens. It's usually combined with a parallel@modalslot.20. How do you read a cookie in a Next.js 16 server component?
Correct answer:
const store = await cookies(); store.get('theme')cookies()andheaders()are async: synchronous access was removed in Next.js 16. Using them makes rendering request-dependent. You can set cookies in Server Actions and Route Handlers, but not while rendering a server component.21. What does
proxy.ts(formerly middleware) do?Correct answer: Runs before the request is handled: redirects, rewrites, headers
Proxy intercepts requests at the network boundary: redirecting unauthenticated users, A/B tests, locales, headers. Its scope is set with
matcher. Don't use it for heavy logic or as the only authorization check - permissions should also be checked close to the data.22. What do you call in a client component to refetch the current route's server components?
Correct answer:
router.refresh()fromuseRouter()router.refresh()makes a new request to the server and re-renders server components while preserving React and browser client state (scroll, typed input).location.reload()resets everything. In Server Actions, the counterpart is therefresh()function fromnext/cache.23. How does
global-error.tsxdiffer fromerror.tsx?Correct answer: It catches root layout errors and renders its own
<html>and<body>An
error.tsxat the root won't catch an error in the root layout itself - it lives inside it.global-error.tsxreplaces the whole document, so it includes its own styles and markup. You can't export metadata from it; use React's<title>instead.24. What does
export const dynamic = 'force-dynamic'do (without Cache Components)?Correct answer: Forces the route to render on every request, disabling prerendering
It's a route segment config option from the previous caching model. With Cache Components, explicit tools are used instead:
'use cache'for caching,<Suspense>andconnection()for request-time data. It doesn't turn components into client components.25. Which props can be passed from a server page to a client component?
Correct answer: Serializable values and Server Actions; regular functions can't be passed
Props travel over the network in the RSC payload. Objects, arrays,
Date,Map, promises, JSX and Server Functions are supported. You can't pass a regular function (onClick={() => ...}) from a server component - declare the handler in the client component.26. In the App Router, how do you get data for
generateMetadataand the page without fetching the API twice viafetch?Correct answer: Do nothing: identical
fetches within one render are deduplicatedRequest memoization: GET
fetchrequests with the same URL and options within one render run once. For other data sources (ORM, SDK), use React'scache().getStaticPropsdoesn't work in the App Router.27. What's the right way to do optimistic UI for a Server Action on the client?
Correct answer: With
useOptimisticwhile the action is runninguseOptimisticshows the expected state immediately and automatically switches back to the real one when the action finishes and fresh data arrives.revalidatePathworks only on the server.router.refresh()before the action won't give instant feedback.28. What happens with
redirect()insidetry/catchin a Server Action?try { await save(data); redirect('/done'); } catch (e) { return { error: 'Failed to save' }; }Correct answer:
catchintercepts its internal exception: no redirectredirect()andnotFound()work by throwing special exceptions. A regularcatchswallows them. The fix is to callredirectafter thetry/catchblock or rethrow internal errors (unstable_rethrow(e)).29. How does
<Form>fromnext/formdiffer from a plain<form>for a search form?Correct answer: With a string
action, it performs a client-side navigation with the query<Form action="/search">turns the fields intosearchParamsand performs an SPA navigation that keeps the shared layout, instead of a full reload. It prefetches shared UI (e.g.loading.tsx). Without JS it works like a regular form. With a function inaction, it behaves like a React form with a Server Action.30. What does
generateMetadatado compared to a staticmetadataexport?Correct answer: Computes metadata dynamically, e.g. from data fetched by
paramsexport async function generateMetadata({ params }) { const post = await getPost((await params).slug); return { title: post.title } }. It runs on the server. There's a separatesitemap.tsfile for sitemaps, and Open Graph images can be generated viaopengraph-image.tsx.31. How do you support multiple languages in the App Router?
Correct answer: An
app/[lang]/...segment + locale detection in proxy + dictionaries on the serverThe App Router doesn't use the built-in
i18noption from the Pages Router. Typically you create a dynamic[lang]segment, redirect the user in proxy based on theAccept-Languageheader and load dictionaries in server components (they don't end up in the bundle). Libraries like next-intl are often used.32. How do you return JSON with status 201 from a Route Handler?
Correct answer:
return Response.json(data, { status: 201 })Route Handlers are built on Web APIs: they take a
Requestand return aResponse(orNextResponsewith extra features).res.status().json()is the Express style used by Pages Router API Routes. A plain object isn't a valid response.33. What is Partial Prerendering (PPR) in Next.js 16?
Correct answer: The page's static shell is sent immediately, and dynamic parts stream in
One route can combine static and dynamic parts: everything that can be prerendered (including
'use cache') goes into the shell and is served instantly, while request data streams inside<Suspense>. In Next.js 16 it's enabled viacacheComponents: trueinstead of the former experimental flag.34. How do you prefetch data for client components using TanStack Query in the App Router?
Correct answer:
prefetchQueryon the server andHydrationBoundaryA server component creates a
QueryClient, runsprefetchQueryand passes the cache state via<HydrationBoundary state={dehydrate(qc)}>. A clientuseQuerywith the same key gets the data immediately. Hooks don't work in server components.35. What happens when you import a server component into a
'use client'file?Correct answer: It becomes a client component, and server code breaks or leaks
Everything imported from a client module goes into the client bundle. If the component accessed the DB, the build fails (or worse, the code reaches the browser). Pass a server component to a client one as
childrenor another prop from a server parent.36. How do you run code (e.g. analytics) after the response is sent, without delaying the user?
Correct answer: Use
after()fromnext/serverafter(() => log(...))schedules work after the response finishes (in server components, Server Actions, Route Handlers, proxy). A "dangling" promise in a serverless environment can be cut off when the function ends, and its errors get lost.37. In Next.js, how do you send only part of the DB data to the client so nothing extra (like a password hash) leaks?
Correct answer: Return DTOs with only the needed fields from the data access layer
Everything in a client component's props is serialized into the HTML and RSC payload and visible in DevTools. A Data Access Layer that checks permissions and returns minimal DTOs is recommended. You can also use the taint API to forbid passing certain objects to the client.
38. How does
revalidatePath('/blog/[slug]', 'page')differ fromrevalidatePath('/blog/my-post')?Correct answer: The first covers all pages of the pattern, the second one specific path
If you pass a pattern with a dynamic segment, you must specify the type
'page'or'layout', and invalidation affects all paths matching the pattern. A specific path invalidates one page.revalidatePath('/', 'layout')resets the whole app.39. Where should you store a secret API key used in a server component?
Correct answer: In an environment variable without the
NEXT_PUBLIC_prefixVariables without the prefix are available only on the server.
NEXT_PUBLIC_*variables are inlined into the client bundle and visible to everyone. Hardcoding ends up in the repository..env*.localfiles aren't committed, and in production the values are set on the platform.40. What does
connection()fromnext/serverdo?Correct answer: Signals that rendering from here on must wait for an actual request
It's needed when a component uses values that mustn't be computed during prerendering but doesn't access
cookies()orheaders(): for example,Math.random()or the current time. With Cache Components, such a component goes inside<Suspense>.41. Why is
useFormStatushandy in forms with Server Actions?Correct answer: It gives the parent form's
pendingstate so you can disable the buttonThe hook is called in a component inside
<form>(usually the submit button):const { pending } = useFormStatus(). This lets you build a reusable<SubmitButton>. The action's result and errors are held byuseActionState.42. Which file sets the fallback for a parallel route slot on a full page reload?
Correct answer:
default.tsxDuring soft navigation, Next.js remembers the active state of slots. After a reload, it can't restore the state of slots that don't match the URL, so it renders their
default.tsx(or a 404 if the file is missing). For a modal,@modal/default.tsxusually returnsnull.43. How does a static route differ from a dynamic one in terms of rendering?
Correct answer: Static - at build time, dynamic - on every request
A route becomes dynamic when it uses request data:
cookies(),headers(),searchParams, uncached requests. A[slug]segment by itself doesn't do that - it can be prerendered viagenerateStaticParams. With Cache Components, the boundary runs inside the page (PPR).44. Where is the right place to check authorization in the App Router?
Correct answer: Close to the data: in the Data Access Layer, Server Actions and Route Handlers
Proxy is fine for optimistic checks and redirects but shouldn't be the only protection: Server Actions are called directly, and layouts don't re-render on navigation. Check the session and permissions reliably where data is read and changed. Hiding buttons on the client isn't security.
45. How do you limit which paths
proxy.tsruns on?Correct answer: Export a
configwith amatcherexport const config = { matcher: ['/dashboard/:path*'] }- proxy runs only for matching paths. Static files and_nextare usually excluded to save resources. There's one proxy per project, located at the root (or insrc).46. What is
opengraph-image.tsxuseful for?Correct answer: Generating the route's OG image from JSX at build time or on request
By convention the file returns an
ImageResponsewith JSX markup - Next.js turns it into a PNG and adds the necessary<meta>tags. Handy for article previews with a title. In Next.js 16,paramsin such files is a promise too.47. Where does a client component's code run on the first page load?
Correct answer: Both on the server (for HTML) and in the browser (hydration)
'use client'doesn't mean "client only": the component is prerendered to HTML on the server and then hydrated. That's why you can't accesswindowduring render without checks - use effects ornext/dynamicwithssr: false.48. How is page data updated after an action if
revalidateTag(tag, 'max')is used?Correct answer: Old data is served while fresh data generates in the background
The
'max'profile gives stale-while-revalidate semantics: the entry is marked stale, the first request gets the old version and triggers regeneration. If the author of the change should see the result immediately, useupdateTagin a Server Action.49. What does
staleTimesinnext.configcontrol?Correct answer: How long segments live in the client router cache
The client router cache stores the RSC payload of visited and prefetched segments so back/forward navigation and repeat visits are instant.
staleTimessets how long this data is considered fresh for dynamic and static pages. The server data cache is configured separately.50. How do you return validation errors to a form from a Server Action?
Correct answer: Return an errors object and read it via
useActionStateExpected errors (an invalid email) are returned as data:
return { errors: { email: 'Invalid address' } }. The form renders them via theuseActionStatestate. Exceptions are reserved for unexpected failures -error.tsxcatches them.51. How can a layout highlight the active tab among its child segments?
'use client' const segment = useSelectedLayoutSegment() // 'settings' on /dashboard/settingsCorrect answer: Use
useSelectedLayoutSegment()in a client component rendered by the layoutLayouts don't re-render on navigation and don't get the child's path. The hook returns the active segment one level below the layout (
useSelectedLayoutSegmentsreturns all of them).52. What happens in Next.js 16 if a parallel route slot
@modalhas nodefault.tsx?Correct answer: The build fails: slots need an explicit
default.jsdefault.tsxis rendered when Next.js can't recover the slot's active state after a full page load. Returnnullfrom it if the slot should be empty.53. How does a rewrite differ from a redirect in
next.config.ts?Correct answer: A rewrite keeps the URL; a redirect changes it
Rewrites act as a proxy, e.g. mapping
/api/:path*to another backend or an old app during migration. The user never sees the destination URL.54. Where can you add security headers like
X-Frame-Optionsto all responses without touching pages?async headers() { return [{ source: '/(.*)', headers: [{ key: 'X-Frame-Options', value: 'DENY' }] }] }Correct answer: In
headers()innext.config.tsConfig headers apply by path pattern. Headers that depend on the request, like a CSP nonce, are set in
proxy.ts.55. A form uploads a 5 MB file via a Server Action and fails. What's the likely cause?
Correct answer: Server Action bodies are limited to 1 MB by default
The limit protects the server from large-payload attacks. For big files, a signed upload URL to object storage avoids sending the bytes through your server.
56. What does
redirect()in a Server Action do for a form submitted before JavaScript loaded?Correct answer: It responds with a 303, and the browser follows with GET
When JavaScript is available,
redirectperforms a client-side navigation. The 303 status keeps progressive enhancement working without re-posting the form.57. Why can't you call
(await cookies()).set(...)while rendering a server component?Correct answer: Cookies are set only in Actions, Route Handlers or
proxy.tsHTTP headers must be sent before the body. Render may stream, so Next.js only allows writing cookies where the response is fully controlled.
58. What is
output: 'standalone'useful for?Correct answer: A minimal server folder, e.g. for a small Docker image
The build traces imported files and copies them to
.next/standalonewith aserver.js.publicand.next/staticmust be copied separately or served from a CDN.59. How do you generate a dynamic Open Graph image (e.g. with the post title) in code?
// app/blog/[slug]/opengraph-image.tsx import { ImageResponse } from 'next/og' export default async function Image({ params }) { const { slug } = await params return new ImageResponse(<div style={{ fontSize: 64 }}>{slug}</div>) }Correct answer: Return
ImageResponsefromnext/ogin anopengraph-image.tsxfileImageResponseturns JSX and a subset of CSS (flexbox) into a PNG. By default the image is generated at build time and cached unless it uses request-time APIs.60. How do you split a sitemap of 200,000 product URLs?
Correct answer:
generateSitemaps: one file per returned sitemap idSearch engines limit a sitemap to 50,000 URLs. Each id produces a separate URL like
/product/sitemap/0.xml; in Next.js 16 theidargument is a Promise.61. What is
instrumentation-client.tsfor?Correct answer: Client monitoring set up before the app is interactive
Put it in the project root (or
src). It needs no exports - the code simply runs early in the browser, e.g. to init error tracking.62. What does
'use cache: private'allow?Correct answer: Caching a function that reads
cookies()orheaders()Results can be reused within a request and kept in the browser's router cache for the
staletime. Use it for per-user data you want to prefetch.63. With Cache Components, how do you keep
new Date()out of the static shell?async function CurrentTime() { await io() return <p>{new Date().toISOString()}</p> }Correct answer: Call
await io()fromnext/cachebefore reading it'use cache'captures the value once for everyone.io()suspends during prerendering; unlikeconnection(), it doesn't block prefetching.64. How can a deeply nested server component read the
[lang]segment of the root layout without prop drilling?import { lang } from 'next/root-params' const current = await lang()Correct answer: Import the generated getter from
next/root-paramsRoot params are dynamic segments above the root layout. The getters work in server components but not in client components, Server Actions or Route Handlers.
65. What is
catchErrorfromnext/errorfor?Correct answer: A component-level error boundary with
retry()It's a programmatic alternative to
error.tsxthat can wrap any part of the tree. It doesn't swallow Next.js control-flow errors and clears on navigation.66. A monorepo package
@acme/uiships untranspiled TypeScript. How do you use it in a Next.js app?Correct answer: Add it to
transpilePackagesinnext.config.tstranspilePackageslets Next.js compile dependencies from local packages ornode_modules, replacing the oldnext-transpile-modulesplugin.67. How do you stream a response gradually from a Route Handler (e.g. AI tokens)?
export async function GET() { const stream = new ReadableStream({ async start(controller) { for await (const chunk of tokens()) controller.enqueue(chunk) controller.close() }, }) return new Response(stream) }Correct answer: Return a
Responsewhose body is aReadableStreamRoute Handlers use the Web
ResponseAPI, so any stream works on the Node.js runtime too. Addtext/event-streamheaders for SSE.68. What does
export const maxDuration = 60do in a page or Route Handler?Correct answer: Limits the route's function execution time, in seconds
It's a route segment config read by deployment platforms. Server Actions inherit it from the page that uses them.
69. With
cacheComponents: true, why doesexport const revalidate = 60in a page fail?Correct answer: Cache Components removes it; use
cacheLifeCache Components move caching decisions from the route to individual functions and components, so route-wide flags no longer apply.
70. What is the recommended way to test an
asyncserver component?Correct answer: End-to-end tests, e.g. with Playwright
Synchronous server and client components can be unit-tested with Vitest or Jest. Data functions can be tested separately as plain async code.
71. How do you call a Server Action from a button's
onClick(not a form) and show pending state?const [isPending, startTransition] = useTransition() <button onClick={() => startTransition(() => likePost(id))}>Correct answer: Wrap the call in
startTransitionfromuseTransitionThe transition gives
isPendingand lets Next.js update the UI with revalidated data from the action's response.72. With Cache Components, why does a form keep its typed text after navigating away and pressing Back?
Correct answer: Routes are hidden with
<Activity>, not unmountedUp to 3 routes are preserved. Transient UI like open dropdowns should be reset in an effect cleanup, or keyed by
bfcacheId.73. When does
prefetch={false}on<Link>make sense?Correct answer: For long lists of rarely-clicked links
Without prefetching, the route loads on click (hover may still help with a custom handler).
useLinkStatuscan show pending state for such links.74. What happens when navigating between two routes that use different root layouts (via route groups)?
Correct answer: A full page load instead of client-side navigation
Each root layout owns its own
<html>and<body>, so the client can't keep the shared tree. Use multiple root layouts for truly separate sections.75. A Server Action works locally but fails behind a reverse proxy with a different host. Which option helps?
Correct answer:
serverActions.allowedOriginsNext.js compares the
OriginandHostheaders to block CSRF. Trusted extra origins must be listed explicitly.