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.

Quick reference: Key concepts and pitfalls on a couple of pages →
  1. 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 client

    The '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. 2. What does <form action={createPost}> with a Server Action give you compared to onSubmit + fetch?

    Correct answer: The form works even before JS loads (progressive enhancement), with no API route

    A Server Action receives FormData directly, so you don't need a Route Handler and a client fetch. 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 via useActionState or useFormStatus.

  3. 3. What does revalidatePath('/blog') do after a mutation?

    Correct answer: Marks the cached data and UI of the /blog route as stale

    The next request to /blog gets 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. 4. How does updateTag differ from revalidateTag in Next.js 16?

    Correct answer: updateTag expires the cache immediately (read-your-writes), revalidateTag is stale-while-revalidate

    updateTag is 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, revalidateTag requires a second argument - a cacheLife profile.

  5. 5. Are fetch requests 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, fetch was 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. 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 with cacheComponents: 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 with cacheLife, invalidation tags with cacheTag. A cached result can become part of the page's static shell.

  7. 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. 8. Which cacheLife profile applies if you don't specify one in 'use cache'?

    Correct answer: default

    The default profile: stale 5 minutes, revalidate 15 minutes, expire never. There are presets seconds, minutes, hours, days, weeks, max, and custom profiles in next.config. The docs recommend always specifying cacheLife explicitly so the behavior is clear at the call site.

  9. 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. 10. What does loading.tsx do 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.tsx fallback is shown instead of the page, and the content streams in. The fallback can be prefetched along with the link. Without loading.tsx or <Suspense>, navigation would wait for the data.

  11. 11. What does generateStaticParams do?

    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 replaces getStaticPaths from 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. 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 later

    The server sends the shell and fallback right away and appends the slow block's HTML to the stream when it's ready. Loading in useEffect sends empty HTML, adds a request waterfall and hurts LCP. With Cache Components, uncached data must be inside <Suspense>.

  13. 13. How do you avoid a request waterfall if a component needs independent getUser() and getPosts()?

    Correct answer: Start both requests at once and wait with Promise.all

    Sequential 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 with use() under separate Suspense boundaries so parts of the UI appear independently.

  14. 14. How do you avoid a double DB query if both generateMetadata and the page call getUser(id)?

    Correct answer: Wrap the function in React's cache() - deduplication within one request

    cache() memoizes calls with the same arguments for the duration of one server render. Next.js deduplicates fetch with identical parameters itself, but ORMs and SDKs need cache(). A global variable would mix different users' data.

  15. 15. How do you guarantee a module with secrets never ends up in the client bundle?

    Correct answer: Add import 'server-only' to it

    The server-only package 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 matching client-only package. The .server suffix does nothing in the App Router, and public is served to everyone.

  16. 16. Can you use next/dynamic with ssr: false in a server component?

    Correct answer: No: ssr: false is allowed only in client components

    Use the ssr: false option inside a 'use client' file: for example, for a component that accesses window on import. In a server component, Next.js throws an error. Server components don't ship their code to the browser anyway.

  17. 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. 18. What are parallel routes (@slot)?

    Correct answer: Named slots rendering several pages in one layout

    The @analytics folder becomes the analytics prop 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 its default.tsx (or a 404 if there isn't one).

  19. 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/1 page opens. It's usually combined with a parallel @modal slot.

  20. 20. How do you read a cookie in a Next.js 16 server component?

    Correct answer: const store = await cookies(); store.get('theme')

    cookies() and headers() 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. 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. 22. What do you call in a client component to refetch the current route's server components?

    Correct answer: router.refresh() from useRouter()

    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 the refresh() function from next/cache.

  23. 23. How does global-error.tsx differ from error.tsx?

    Correct answer: It catches root layout errors and renders its own <html> and <body>

    An error.tsx at the root won't catch an error in the root layout itself - it lives inside it. global-error.tsx replaces the whole document, so it includes its own styles and markup. You can't export metadata from it; use React's <title> instead.

  24. 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> and connection() for request-time data. It doesn't turn components into client components.

  25. 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. 26. In the App Router, how do you get data for generateMetadata and the page without fetching the API twice via fetch?

    Correct answer: Do nothing: identical fetches within one render are deduplicated

    Request memoization: GET fetch requests with the same URL and options within one render run once. For other data sources (ORM, SDK), use React's cache(). getStaticProps doesn't work in the App Router.

  27. 27. What's the right way to do optimistic UI for a Server Action on the client?

    Correct answer: With useOptimistic while the action is running

    useOptimistic shows the expected state immediately and automatically switches back to the real one when the action finishes and fresh data arrives. revalidatePath works only on the server. router.refresh() before the action won't give instant feedback.

  28. 28. What happens with redirect() inside try/catch in a Server Action?

    try {
      await save(data);
      redirect('/done');
    } catch (e) {
      return { error: 'Failed to save' };
    }

    Correct answer: catch intercepts its internal exception: no redirect

    redirect() and notFound() work by throwing special exceptions. A regular catch swallows them. The fix is to call redirect after the try/catch block or rethrow internal errors (unstable_rethrow(e)).

  29. 29. How does <Form> from next/form differ 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 into searchParams and 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 in action, it behaves like a React form with a Server Action.

  30. 30. What does generateMetadata do compared to a static metadata export?

    Correct answer: Computes metadata dynamically, e.g. from data fetched by params

    export async function generateMetadata({ params }) { const post = await getPost((await params).slug); return { title: post.title } }. It runs on the server. There's a separate sitemap.ts file for sitemaps, and Open Graph images can be generated via opengraph-image.tsx.

  31. 31. How do you support multiple languages in the App Router?

    Correct answer: An app/[lang]/... segment + locale detection in proxy + dictionaries on the server

    The App Router doesn't use the built-in i18n option from the Pages Router. Typically you create a dynamic [lang] segment, redirect the user in proxy based on the Accept-Language header and load dictionaries in server components (they don't end up in the bundle). Libraries like next-intl are often used.

  32. 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 Request and return a Response (or NextResponse with extra features). res.status().json() is the Express style used by Pages Router API Routes. A plain object isn't a valid response.

  33. 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 via cacheComponents: true instead of the former experimental flag.

  34. 34. How do you prefetch data for client components using TanStack Query in the App Router?

    Correct answer: prefetchQuery on the server and HydrationBoundary

    A server component creates a QueryClient, runs prefetchQuery and passes the cache state via <HydrationBoundary state={dehydrate(qc)}>. A client useQuery with the same key gets the data immediately. Hooks don't work in server components.

  35. 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 children or another prop from a server parent.

  36. 36. How do you run code (e.g. analytics) after the response is sent, without delaying the user?

    Correct answer: Use after() from next/server

    after(() => 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. 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. 38. How does revalidatePath('/blog/[slug]', 'page') differ from revalidatePath('/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. 39. Where should you store a secret API key used in a server component?

    Correct answer: In an environment variable without the NEXT_PUBLIC_ prefix

    Variables 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*.local files aren't committed, and in production the values are set on the platform.

  40. 40. What does connection() from next/server do?

    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() or headers(): for example, Math.random() or the current time. With Cache Components, such a component goes inside <Suspense>.

  41. 41. Why is useFormStatus handy in forms with Server Actions?

    Correct answer: It gives the parent form's pending state so you can disable the button

    The 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 by useActionState.

  42. 42. Which file sets the fallback for a parallel route slot on a full page reload?

    Correct answer: default.tsx

    During 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.tsx usually returns null.

  43. 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 via generateStaticParams. With Cache Components, the boundary runs inside the page (PPR).

  44. 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. 45. How do you limit which paths proxy.ts runs on?

    Correct answer: Export a config with a matcher

    export const config = { matcher: ['/dashboard/:path*'] } - proxy runs only for matching paths. Static files and _next are usually excluded to save resources. There's one proxy per project, located at the root (or in src).

  46. 46. What is opengraph-image.tsx useful for?

    Correct answer: Generating the route's OG image from JSX at build time or on request

    By convention the file returns an ImageResponse with 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, params in such files is a promise too.

  47. 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 access window during render without checks - use effects or next/dynamic with ssr: false.

  48. 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, use updateTag in a Server Action.

  49. 49. What does staleTimes in next.config control?

    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. staleTimes sets how long this data is considered fresh for dynamic and static pages. The server data cache is configured separately.

  50. 50. How do you return validation errors to a form from a Server Action?

    Correct answer: Return an errors object and read it via useActionState

    Expected errors (an invalid email) are returned as data: return { errors: { email: 'Invalid address' } }. The form renders them via the useActionState state. Exceptions are reserved for unexpected failures - error.tsx catches them.

  51. 51. How can a layout highlight the active tab among its child segments?

    'use client'
    const segment = useSelectedLayoutSegment() // 'settings' on /dashboard/settings

    Correct answer: Use useSelectedLayoutSegment() in a client component rendered by the layout

    Layouts 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 (useSelectedLayoutSegments returns all of them).

  52. 52. What happens in Next.js 16 if a parallel route slot @modal has no default.tsx?

    Correct answer: The build fails: slots need an explicit default.js

    default.tsx is rendered when Next.js can't recover the slot's active state after a full page load. Return null from it if the slot should be empty.

  53. 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. 54. Where can you add security headers like X-Frame-Options to all responses without touching pages?

    async headers() {
      return [{ source: '/(.*)', headers: [{ key: 'X-Frame-Options', value: 'DENY' }] }]
    }

    Correct answer: In headers() in next.config.ts

    Config headers apply by path pattern. Headers that depend on the request, like a CSP nonce, are set in proxy.ts.

  55. 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. 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, redirect performs a client-side navigation. The 303 status keeps progressive enhancement working without re-posting the form.

  57. 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.ts

    HTTP headers must be sent before the body. Render may stream, so Next.js only allows writing cookies where the response is fully controlled.

  58. 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/standalone with a server.js. public and .next/static must be copied separately or served from a CDN.

  59. 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 ImageResponse from next/og in an opengraph-image.tsx file

    ImageResponse turns 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. 60. How do you split a sitemap of 200,000 product URLs?

    Correct answer: generateSitemaps: one file per returned sitemap id

    Search engines limit a sitemap to 50,000 URLs. Each id produces a separate URL like /product/sitemap/0.xml; in Next.js 16 the id argument is a Promise.

  61. 61. What is instrumentation-client.ts for?

    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. 62. What does 'use cache: private' allow?

    Correct answer: Caching a function that reads cookies() or headers()

    Results can be reused within a request and kept in the browser's router cache for the stale time. Use it for per-user data you want to prefetch.

  63. 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() from next/cache before reading it

    'use cache' captures the value once for everyone. io() suspends during prerendering; unlike connection(), it doesn't block prefetching.

  64. 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-params

    Root 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. 65. What is catchError from next/error for?

    Correct answer: A component-level error boundary with retry()

    It's a programmatic alternative to error.tsx that can wrap any part of the tree. It doesn't swallow Next.js control-flow errors and clears on navigation.

  66. 66. A monorepo package @acme/ui ships untranspiled TypeScript. How do you use it in a Next.js app?

    Correct answer: Add it to transpilePackages in next.config.ts

    transpilePackages lets Next.js compile dependencies from local packages or node_modules, replacing the old next-transpile-modules plugin.

  67. 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 Response whose body is a ReadableStream

    Route Handlers use the Web Response API, so any stream works on the Node.js runtime too. Add text/event-stream headers for SSE.

  68. 68. What does export const maxDuration = 60 do 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. 69. With cacheComponents: true, why does export const revalidate = 60 in a page fail?

    Correct answer: Cache Components removes it; use cacheLife

    Cache Components move caching decisions from the route to individual functions and components, so route-wide flags no longer apply.

  70. 70. What is the recommended way to test an async server 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. 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 startTransition from useTransition

    The transition gives isPending and lets Next.js update the UI with revalidated data from the action's response.

  72. 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 unmounted

    Up to 3 routes are preserved. Transient UI like open dropdowns should be reset in an effect cleanup, or keyed by bfcacheId.

  73. 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). useLinkStatus can show pending state for such links.

  74. 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. 75. A Server Action works locally but fails behind a reverse proxy with a different host. Which option helps?

    Correct answer: serverActions.allowedOrigins

    Next.js compares the Origin and Host headers to block CSRF. Trusted extra origins must be listed explicitly.