Skip to content
RED SAGSkills

Next.js interview questions and answers

Next.js questions test the App Router model: server and client components, caching and how pages are rendered and revalidated. Interviewers want to see that you know what runs on the server and what ships to the browser.

Below are 60 Next.js questions with the correct answer and a short explanation, grouped from fresher to experienced level. Try each one before you open the answer.

What Next.js interviews usually check

  • ✓Server components vs client components
  • ✓Static, dynamic and incremental rendering
  • ✓Data fetching, caching and revalidation
  • ✓Routing, layouts, middleware and route handlers
  • ✓Images, fonts, metadata and Core Web Vitals

Next.js interview questions for freshers easy

1. Where to keep a secret key

Your Next.js app needs a payment provider secret key to create payments. Where should this key live?

  1. A.In a server-only environment variable, used inside a Route Handler or Server Action
  2. B.In an environment variable named NEXT_PUBLIC_PAYMENT_SECRET
  3. C.In localStorage after the user logs in
  4. D.Hardcoded in a client component so it is easy to find
Show answer

Answer: A. In a server-only environment variable, used inside a Route Handler or Server Action

Secret keys must never reach the browser. In Next.js, variables starting with NEXT_PUBLIC_ are bundled into client JavaScript, and localStorage or client code can be read by anyone. Keep the key in a server-only variable and call the provider from server code.

2. Renaming a secret to NEXT_PUBLIC_

A client component shows undefined for process.env.STRIPE_SECRET_KEY, so a developer renames it to NEXT_PUBLIC_STRIPE_SECRET_KEY and it starts working. What is wrong?

  1. A.Nothing, because NEXT_PUBLIC_ variables are encrypted inside the bundle and decrypted at runtime
  2. B.It only works in development, not in production
  3. C.The secret is now copied into the JavaScript bundle that anyone can download
  4. D.Environment variables cannot contain underscores
Show answer

Answer: C. The secret is now copied into the JavaScript bundle that anyone can download

Next.js inlines NEXT_PUBLIC_ variables into client JavaScript at build time, so the secret becomes public. Secret keys must stay on the server, for example in a Route Handler or Server Action that calls Stripe. The key should also be rotated because it has already been exposed.

3. Linking between pages

Which is the recommended way to link to another page inside a Next.js app?

  1. A.<a href="/pricing" target="_self"> only
  2. B.window.location.assign('/pricing')
  3. C.<Redirect to="/pricing"> from next/redirect
  4. D.<Link href="/pricing"> from next/link
Show answer

Answer: D. <Link href="/pricing"> from next/link

Link does client-side navigation, keeps shared layouts, and prefetches routes in production. A plain <a> causes a full page reload, losing client state.

4. Folder with an underscore

What does a folder named _components inside app do?

  1. A.It is left out of routing entirely
  2. B.It becomes the /components route
  3. C.It is loaded only on the client side
  4. D.It is the place for error pages
Show answer

Answer: A. It is left out of routing entirely

Folders starting with an underscore are private and are skipped by the router, even if they hold a page file. They are a clear place for helpers and components next to routes.

5. Two routers in one project

Can a project use both the pages directory and the app directory at the same time?

  1. A.No, the build fails if both exist
  2. B.Yes, but only for API routes
  3. C.Yes, which helps step-by-step migration
  4. D.No, unless you use two separate servers
Show answer

Answer: C. Yes, which helps step-by-step migration

Next.js supports both routers side by side, so teams can move routes one at a time. A path must not be defined in both, and navigating between the two routers does a full page load.

6. Highlighting the active link

A navbar needs to highlight the link of the current page. Which hook gives the current path in the App Router?

  1. A.useParams() from next/link
  2. B.usePathname()
  3. C.useLocation()
  4. D.useCurrentRoute()
Show answer

Answer: B. usePathname()

usePathname returns a string like /dashboard/settings. It is a client hook, so the navbar (or that part of it) must be a Client Component.

7. Fetching data in a page

How do you fetch data in an App Router Server Component?

  1. A.Use useEffect and setState in the page
  2. B.Export getInitialProps from the page
  3. C.Make the component async and await the data
  4. D.Call fetch inside a <Script> tag
Show answer

Answer: C. Make the component async and await the data

Server Components can be async functions, so you simply await fetch or a database call during render. No client effect or loading state code is needed for the first render.

8. How Server Actions are called

When a client calls a Server Action, what kind of request is sent?

  1. A.A GET request with the args in the URL
  2. B.A WebSocket message to the server
  3. C.A POST request to the current route
  4. D.A request to /api/actions by default
Show answer

Answer: C. A POST request to the current route

Server Actions use POST with an action ID header, sent to the page's URL. That is why they should not be used as a way to fetch data on GET and why they need the same security as any public endpoint.

9. Default caching of fetch

In Next.js 15 and later, what is the default caching of fetch() in a Server Component?

  1. A.Cached forever by default
  2. B.Cached for 60 seconds by default
  3. C.Cached only in the browser
  4. D.Not cached by default
Show answer

Answer: D. Not cached by default

Next.js 15 changed the default so fetch is no longer cached unless you opt in, for example with cache: 'force-cache', next.revalidate or 'use cache'. This avoids surprising stale data.

10. Reading a JSON body

In a POST route handler, how do you read a JSON body?

  1. A.await request.json()
  2. B.request.body.json
  3. C.JSON.parse(request)
  4. D.request.query.body
Show answer

Answer: A. await request.json()

Route handlers get a standard Web Request. request.json() returns a promise for the parsed body. Validate it, for example with zod, before using it.

11. Caching one fetch for 10 minutes

Which fetch call caches the response for 10 minutes in the Next.js data cache?

  1. A.fetch(url, { cache: 'no-store' })
  2. B.fetch(url, { revalidate: '10m' })
  3. C.fetch(url, { next: { revalidate: 600 } })
  4. D.fetch(url, { maxAge: 600000 })
Show answer

Answer: C. fetch(url, { next: { revalidate: 600 } })

The next.revalidate option sets a time in seconds for the cached response. After 600 s, the next request gets the stale data and a background refetch updates it.

12. Allowing an image host

next/image throws an error for an image from images.shopcdn.com. What fixes it?

  1. A.Add the host to images.remotePatterns in next.config
  2. B.Add the host to the .env.local file
  3. C.Set the image loading prop to lazy
  4. D.Use a relative path for the remote image
Show answer

Answer: A. Add the host to images.remotePatterns in next.config

The image optimiser only fetches remote images from hosts you allow, so it cannot be abused as an open proxy. remotePatterns lets you set protocol, hostname, port and path.

13. Benefit of next/font/google

What does importing a font with next/font/google do?

  1. A.Loads it from Google on every page view
  2. B.Turns the font into an SVG image
  3. C.Adds the font only to the server bundle
  4. D.Downloads it at build time and self-hosts it
Show answer

Answer: D. Downloads it at build time and self-hosts it

next/font fetches the font files during the build and serves them from your own domain, so no request goes to Google from the browser. It also sets a matching fallback to reduce layout shift.

14. Setting the page title

How do you set the browser tab title of a static App Router page?

  1. A.<title> inside a useEffect hook
  2. B.export const metadata = { title: 'Pricing' }
  3. C.document.title in a Server Component
  4. D.export const head = '<title>Pricing</title>'
Show answer

Answer: B. export const metadata = { title: 'Pricing' }

The metadata export in a Server Component page or layout generates the head tags. For titles that depend on data, export an async generateMetadata function instead.

15. Small Docker image

Which next.config option creates a minimal server folder that is handy for Docker?

  1. A.output: 'standalone'
  2. B.output: 'export'
  3. C.output: 'docker'
  4. D.output: 'minimal-image'
Show answer

Answer: A. output: 'standalone'

standalone copies only the files and node_modules the server needs into .next/standalone, which keeps container images small. You still copy public and .next/static next to it.

16. Generating a sitemap

Which App Router file creates /sitemap.xml?

  1. A.public/sitemap.tsx returning JSX
  2. B.app/sitemap.ts returning a list of URLs
  3. C.app/api/sitemap/page.tsx
  4. D.next.config sitemap: true
Show answer

Answer: B. app/sitemap.ts returning a list of URLs

sitemap.ts exports a function that returns an array of URL entries, and Next.js serves it as XML. robots.ts works the same way for robots.txt.

17. Reading next build output

In the next build route list, what does the ○ symbol next to a route mean?

  1. A.Dynamic, rendered on each request
  2. B.Broken, failed to compile
  3. C.Static, prerendered as HTML
  4. D.Proxy, matched by proxy.ts
Show answer

Answer: C. Static, prerendered as HTML

○ marks a static route, while ƒ marks a dynamic server-rendered route. Checking this list after a change shows if something made a page dynamic by mistake.

18. Social share image

How can a blog post get an automatically generated social share image in the App Router?

  1. A.Add opengraph-image.tsx using ImageResponse
  2. B.Add a share.png to every blog folder name
  3. C.Set og: true in the next.config file
  4. D.Use a client effect to set a meta tag
Show answer

Answer: A. Add opengraph-image.tsx using ImageResponse

opengraph-image.tsx can render JSX to a PNG with ImageResponse, and Next.js adds the og:image tags. A static opengraph-image.png in the folder also works.

19. Image with fill is not visible

An <Image fill> is inside a div, but nothing shows. What is the likely cause?

  1. A.The image is missing a loading prop value
  2. B.The parent has no position set and no height
  3. C.fill only works with SVG image sources
  4. D.The alt text on the image is far too long
Show answer

Answer: B. The parent has no position set and no height

With fill the image is absolutely positioned to cover its parent. The parent must have position relative, absolute or fixed, and a real size, or the image has nothing to fill.

20. Measuring speed in dev mode

A developer times page loads under next dev and finds them slow. Why is this a poor speed test?

  1. A.Dev mode always uses a slower network for safety
  2. B.Dev mode turns off Server Components entirely
  3. C.Dev compiles on demand and skips production optimisations
  4. D.Dev mode loads every page twice to test them
Show answer

Answer: C. Dev compiles on demand and skips production optimisations

next dev compiles routes on first request, adds dev checks and skips minification and prefetching. Measure with next build and next start, or a preview deployment.

Next.js intermediate interview questions medium

21. Server Components and the database

In the Next.js App Router, this Server Component queries the database directly. What does the browser receive?

import { db } from '@/lib/db'

export default async function Page() {
  const products = await db.product.findMany()
  return <ProductList items={products} />
}
  1. A.The full component source, including the db import and connection string
  2. B.Nothing; Server Components cannot use async/await
  3. C.An empty page that fetches products later with useEffect
  4. D.The rendered result (HTML and the RSC payload); the database code and credentials stay on the server
Show answer

Answer: D. The rendered result (HTML and the RSC payload); the database code and credentials stay on the server

Server Components run only on the server, so their code and imports are never shipped to the client bundle. The browser gets HTML plus a serialized RSC payload with the rendered output and any props passed to Client Components. Be careful: whatever you pass as props to a Client Component is sent to the browser.

22. Relative fetch on the server

A Server Component calls await fetch('/api/products') and fails during render with an invalid URL error. What is the best fix?

  1. A.Add 'use client' to the component
  2. B.Wrap the fetch in useEffect
  3. C.Import and call the data function (or query the database) directly instead of calling your own API route
  4. D.Change the path to './api/products'
Show answer

Answer: C. Import and call the data function (or query the database) directly instead of calling your own API route

On the server there is no page origin, so a relative URL cannot be resolved. Calling your own Route Handler over HTTP would also add an extra network hop and serialization. Server Components can run the same data-access code the route uses, keeping the API route for external clients.

23. Reading params in Next.js 15+

Which page code reads the id correctly in Next.js 15 and later?

export default async function Page({ params }: { params: Promise<{ id: string }> }) {
  // read id here
}
  1. A.const { id } = params.value
  2. B.const id = useParams(params)
  3. C.const { id } = await params
  4. D.const id = params.get('id')
Show answer

Answer: C. const { id } = await params

From Next.js 15, params and searchParams passed to pages, layouts and route handlers are Promises. You await them in an async Server Component, or unwrap with React use() in a Client Component. Next.js 16 removed the old sync access.

24. Server content inside a client wrapper

You want a Client Component Modal that wraps content from a Server Component. What is the right pattern?

  1. A.Import the Server Component inside the Modal file
  2. B.Add 'use server' to the top of the Modal file
  3. C.Pass the server content to the Modal as children
  4. D.Render the Modal only inside a route handler
Show answer

Answer: C. Pass the server content to the Modal as children

A Client Component cannot import a Server Component, but it can receive one as children or other props. The server renders that part first and passes the result into the client tree.

25. Same DB query in layout and page

The layout and the page both call getUser(id), which queries the database. How do you make it run once per request?

  1. A.Store the user in a global variable
  2. B.Call getUser only in a useEffect
  3. C.Use fetch with cache: 'no-store'
  4. D.Wrap getUser with React cache()
Show answer

Answer: D. Wrap getUser with React cache()

React cache() memoises a function for the length of one server request. Both calls share the result, and the next request starts fresh. A global variable would leak data between users.

26. Same fetch called twice

Two Server Components in the same render call fetch('https://api.x.com/me') with the same options. How many network requests are made?

  1. A.Two, as each component makes its own request
  2. B.None, because fetch is blocked on the server
  3. C.One, because GET fetches are memoised per render
  4. D.Three, including one prefetch from the client
Show answer

Answer: C. One, because GET fetches are memoised per render

React and Next.js memoise identical GET fetch calls during a single render pass. You can call the same fetch where you need the data instead of passing it through many props.

27. Where to check permissions

A deleteInvoice Server Action is called only from an admin page. Where must the permission check be?

  1. A.Only in the admin page layout
  2. B.Inside the Server Action itself
  3. C.Only in the button's onClick handler
  4. D.Only in proxy.ts for that path
Show answer

Answer: B. Inside the Server Action itself

A Server Action is a public POST endpoint; anyone who finds its ID can call it. Page or layout checks do not protect it. Verify the session and role inside the action every time.

28. GET route handler caching

In Next.js 15+, is a GET route handler that returns Response.json(data) cached by default?

  1. A.Yes, it is cached forever after the first call
  2. B.No, it runs on each request unless opted in
  3. C.Yes, it is cached for exactly one minute
  4. D.No, GET handlers are not allowed in route.ts
Show answer

Answer: B. No, it runs on each request unless opted in

Next.js 15 made GET route handlers dynamic by default. You can opt in to static output with export const dynamic = 'force-static', or use caching APIs for the data.

29. First visitor after revalidate time

A page has revalidate = 60. It was generated 5 minutes ago. What does the next visitor get?

  1. A.A loading screen until the new page is built
  2. B.A 503 error until the build finishes
  3. C.The old page, while a new one is built in the background
  4. D.The new page, built before the response
Show answer

Answer: C. The old page, while a new one is built in the background

ISR uses stale-while-revalidate: the expired page is still served immediately, and regeneration happens in the background. Later visitors get the fresh page once it is ready.

30. Tagging cached data

Inside a 'use cache' function that loads a product, how do you tag it so it can be revalidated later?

  1. A.Call cacheTag('product-42') inside the function
  2. B.Return { tag: 'product-42' } from the function
  3. C.Add next: { tags } to the use cache line
  4. D.Set a header named x-cache-tag on the page
Show answer

Answer: A. Call cacheTag('product-42') inside the function

cacheTag attaches tags to the cache entry. Later, revalidateTag or updateTag with that tag invalidates it. Use specific tags like product-42 plus broad ones like products.

31. Hidden data waterfall

A page awaits getUser(), then renders <Orders userId>, which awaits getOrders(). getOrders needs only the user ID from the URL. What is the issue?

  1. A.Both fetches run in parallel already
  2. B.Orders cannot start until the user fetch ends
  3. C.getOrders will be cached forever
  4. D.React cancels the second fetch
Show answer

Answer: B. Orders cannot start until the user fetch ends

Because Orders renders only after the parent finishes awaiting, the two requests run one after the other. Starting getOrders earlier with the ID from params, or using Promise.all, removes the wait.

32. How long React cache() lasts

A getRates() function wrapped with React cache() calls a currency API. How long does its result stay memoised on the server?

  1. A.For the life of the server process
  2. B.Until the next deploy of the app
  3. C.For 60 seconds by default
  4. D.For one server request only
Show answer

Answer: D. For one server request only

React cache() is request-scoped: it dedupes calls within one render on the server. To share data across requests, use 'use cache', fetch caching or an external cache such as Redis.

33. Title from database data

A product page needs a title like "Red Shoe – ₹1,999". Which approach is correct?

  1. A.Set document.title inside a useEffect
  2. B.Put a <title> inside the page JSX
  3. C.Edit the root layout title on each request
  4. D.export async function generateMetadata({ params })
Show answer

Answer: D. export async function generateMetadata({ params })

generateMetadata can await params and fetch the product. If the page fetches the same data, React memoises the fetch, or you can use React cache() for DB calls.

34. Hiding a backend URL

You want /api/v1/* calls from the browser to reach https://backend.internal/v1/* without CORS. Which config fits?

  1. A.redirects() with permanent set to false
  2. B.headers() adding Access-Control headers
  3. C.basePath set to /api/v1 in the config
  4. D.rewrites() mapping the source to the destination
Show answer

Answer: D. rewrites() mapping the source to the destination

A rewrite proxies the request on the server, so the browser sees a same-origin URL and no CORS is needed. A redirect would send the browser to the backend URL directly.

35. Hero image loads late

A hero banner uses next/image and LCP is slow. By default, how does next/image load images?

  1. A.Lazily, so above-the-fold images need eager or preload
  2. B.Eagerly, with the highest fetch priority set
  3. C.Only after the user clicks on the image
  4. D.Only once the whole page has hydrated
Show answer

Answer: A. Lazily, so above-the-fold images need eager or preload

next/image adds loading="lazy" by default. For the LCP image, mark it to load early (preload or eager with high fetch priority) so it is not delayed until layout.

36. Native module breaks the build

A package with a native .node binary fails to bundle in Server Components. Which config usually helps?

  1. A.transpilePackages with that package name
  2. B.images.unoptimized set to true
  3. C.experimental.reactCompiler set to true
  4. D.serverExternalPackages with that package name
Show answer

Answer: D. serverExternalPackages with that package name

serverExternalPackages tells Next.js to leave a package out of the server bundle and require it at runtime with Node. Many common native packages are already on the built-in list.

37. Slow dev from icon library

Importing a few icons from a library with thousands of modules makes dev compiles slow. Which option helps?

  1. A.serverExternalPackages listing the library
  2. B.experimental.optimizePackageImports for it
  3. C.output: 'standalone' in the next.config
  4. D.images.remotePatterns listing the library
Show answer

Answer: B. experimental.optimizePackageImports for it

optimizePackageImports rewrites barrel imports to load only the modules used. Next.js already does this for many popular libraries such as lucide-react and date-fns.

38. Fewer manual memos

A team wants automatic memoisation instead of writing useMemo and useCallback everywhere. What does Next.js 16 support?

  1. A.Adding 'use memo' to every client file
  2. B.Using Server Components for all buttons
  3. C.Turning on the React Compiler in next.config
  4. D.Switching the bundler back to webpack
Show answer

Answer: C. Turning on the React Compiler in next.config

The React Compiler analyses components at build time and memoises where safe. Next.js 16 supports it as a stable config option. It may raise build times, as it runs through Babel.

39. Can crawlers see streamed content?

A product page streams its description inside Suspense. Does this content still appear in the HTML that crawlers get?

  1. A.Yes; streamed HTML is part of the same response
  2. B.No; only the shell is ever sent to crawlers
  3. C.Only if the page is a Client Component
  4. D.Only if JavaScript is disabled in the crawler
Show answer

Answer: A. Yes; streamed HTML is part of the same response

Streaming sends the fallback first and later chunks with the real HTML in the same response. Crawlers that read the full response get the content. Metadata generation can affect how head tags stream.

40. Component that touches window

A map library touches window at import time and crashes during server rendering. What is a common fix in a Client Component?

  1. A.export const runtime = 'edge'
  2. B.'use server' on the map file
  3. C.A route handler that returns the map
  4. D.next/dynamic with ssr: false
Show answer

Answer: D. next/dynamic with ssr: false

next/dynamic with { ssr: false } loads the component only in the browser. It must be used inside a Client Component, and you can show a loading placeholder in the meantime.

Next.js interview questions for experienced candidates hard

41. 404 page returns status 200

A Next.js product page wraps the product lookup in a Suspense boundary, and that component calls notFound() for unknown IDs. Users see the 404 UI, but crawlers get HTTP 200. Why?

  1. A.notFound() only works inside Route Handlers
  2. B.Crawlers do not support 404 responses
  3. C.Streaming had already sent the 200 status and headers before the lookup finished; check existence before any Suspense boundary
  4. D.The page needs export const dynamic = "force-static"
Show answer

Answer: C. Streaming had already sent the 200 status and headers before the lookup finished; check existence before any Suspense boundary

With streaming, the response starts as soon as the shell is ready, and HTTP status and headers cannot be changed after that. When notFound() fires inside streamed content, Next.js can only render the not-found UI and add a noindex tag. Doing the existence check at the top of the page or in generateMetadata, before streaming begins, lets it return a real 404.

42. Nonce-based CSP trade-off

You add a strict Content Security Policy with a fresh nonce on every request in a Next.js app. What is the main trade-off?

  1. A.Pages that use the nonce must be rendered per request, so they lose static generation and CDN caching
  2. B.Nonces can safely be reused across many requests, so the cached HTML and CDN caching are not affected at all
  3. C.Nonces only apply to CSS, so scripts stay unprotected
  4. D.The site can no longer be served over HTTPS
Show answer

Answer: A. Pages that use the nonce must be rendered per request, so they lose static generation and CDN caching

A nonce only works if attackers cannot predict it, so it must change on every response and cannot be baked into cached HTML. That forces dynamic rendering for those pages. For mostly static sites, a hash-based CSP or a looser policy on static pages can keep caching while still blocking injected scripts.

43. Errors only right after a deploy

Right after each deploy, users who had the app open see "Failed to find Server Action" and chunk loading errors until they refresh. What is the cause and the best mitigation?

  1. A.The CDN is down during deploys; add a second CDN
  2. B.The database migration runs too slowly; run it after the deploy
  3. C.Browsers refuse new JavaScript files for five minutes after a deploy; lower the cache time
  4. D.Old tabs run the previous build against the new server; use skew protection
Show answer

Answer: D. Old tabs run the previous build against the new server; use skew protection

Each build has its own chunk filenames and Server Action IDs, so an old client can ask for things the new server no longer has. Skew protection routes old clients to their original deployment, and keeping previous assets plus backward-compatible APIs avoids hard failures. A fallback that reloads the page on chunk load errors helps users recover.

44. Scroll position after navigation

A user clicks a <Link> to a long page. What does the App Router do with scroll by default?

  1. A.Keeps the exact scroll position of the old page
  2. B.Always jumps to the bottom of the page
  3. C.Scrolls only after a full page reload
  4. D.Scrolls to the top of the new segment if not visible
Show answer

Answer: D. Scrolls to the top of the new segment if not visible

By default Next.js scrolls so the newly rendered segment is in view, usually to the top. Use scroll={false} on Link, or { scroll: false } with router.push, to keep the position.

45. Async Client Component

A developer makes a Client Component async and awaits fetch inside it. What is the problem?

  1. A.It works the same as in a Server Component
  2. B.Async makes the component run only on the server
  3. C.Async components are not supported for client rendering
  4. D.The fetch is cached forever in the browser
Show answer

Answer: C. Async components are not supported for client rendering

React supports async components only on the server. In the client, use use() with a promise from a server parent, or a data library, inside Suspense. React warns or errors on async client components.

46. getServerSideProps in the app folder

A team moves a page to app/ and keeps its getServerSideProps export. What happens?

  1. A.It runs as before on every incoming request
  2. B.It is not supported in app; fetch in the component
  3. C.It runs once at build time and never again
  4. D.It turns the page into a route handler instead
Show answer

Answer: B. It is not supported in app; fetch in the component

getServerSideProps, getStaticProps and getStaticPaths are Pages Router APIs. In the App Router you fetch inside async Server Components and control caching with segment config or caching APIs.

47. Reading cookies inside use cache

A function marked 'use cache' calls await cookies() to read the user's currency. What happens?

  1. A.The cookie is cached for all users safely
  2. B.Next.js reads the cookie at build time
  3. C.The cookie value becomes the cache tag
  4. D.It errors; read cookies outside and pass the value in
Show answer

Answer: D. It errors; read cookies outside and pass the value in

Cached scopes cannot read request APIs like cookies() or headers(), since their output is shared. Read the cookie outside the cached function and pass it as an argument, which then becomes part of the cache key.

48. Build error with Cache Components

With cacheComponents enabled, a page does await db.query() without 'use cache' and without Suspense. The build reports uncached data accessed outside of Suspense. What fixes it?

  1. A.Add 'use client' to the top of the page file
  2. B.Move the query into the root layout file
  3. C.Set export const revalidate = false on the page
  4. D.Wrap that part in <Suspense> or mark it 'use cache'
Show answer

Answer: D. Wrap that part in <Suspense> or mark it 'use cache'

Cache Components prerenders a static shell. Uncached or request data must be explicit: either cached with 'use cache' or placed under a Suspense boundary so it streams at request time.

49. Values captured by an inline action

A Server Component defines an inline Server Action that uses a variable from the component scope. How does Next.js handle that captured value?

  1. A.It is stored in the server memory forever
  2. B.It is sent to the client encrypted and sent back on call
  3. C.It is sent to the client in plain text only
  4. D.It is dropped, and the action gets undefined
Show answer

Answer: B. It is sent to the client encrypted and sent back on call

Closed-over values must travel with the action reference, so Next.js encrypts them. Still, never rely on this for secrets; fetch sensitive data inside the action instead.

50. Deleting data in a GET handler

A route handler GET /api/delete?id=5 deletes a record. Why is this risky?

  1. A.GET handlers cannot reach the database at all
  2. B.GET responses always have an empty body
  3. C.Prefetchers, crawlers or img tags can trigger GETs
  4. D.Browsers block GET requests with params
Show answer

Answer: C. Prefetchers, crawlers or img tags can trigger GETs

GET should be safe and have no side effects. Link prefetch, crawlers, link previews or a CSRF image tag can all fire it. Use POST or DELETE with auth and CSRF protection.

51. Making a random value per request

A Server Component uses Math.random() for a daily offer code, and the value is the same for all users. Which API opts this part into request-time rendering?

  1. A.await cookies() and ignore the result
  2. B.await connection() from next/server
  3. C.useEffect on the server component
  4. D.export const random = true
Show answer

Answer: B. await connection() from next/server

Without request data, the page may be prerendered, freezing the random value. connection() tells Next.js to wait for an actual request. With Cache Components you place this inside Suspense.

52. What an action may return

A Server Action returns { ok: true, saved: new Map() } to a Client Component that called it. What is the rule for return values?

  1. A.They must be serialisable by React for the client
  2. B.They can be any JS value, including classes
  3. C.They are always turned into JSON strings
  4. D.They must be a Response object only
Show answer

Answer: A. They must be serialisable by React for the client

Return values travel to the client using React's serialisation, which supports plain objects, arrays, Dates, Maps, Sets and more, but not class instances or plain functions. Keep returns small and plain.

53. Trusting form data in an action

A Server Action reads formData.get('price') and saves it as the order price. What is the flaw?

  1. A.FormData cannot be read inside a Server Action
  2. B.The client can send any value; validate and price on server
  3. C.Prices must be sent through query strings
  4. D.Server Actions convert all values to numbers
Show answer

Answer: B. The client can send any value; validate and price on server

Anything from the client can be changed with DevTools or a script. Validate input with a schema such as zod, and look up prices, GST and totals on the server rather than trusting submitted values.

54. Blocking secrets from reaching the client

You want a build-time guard so a user object with a password hash can never be passed to a Client Component by mistake. Which React API helps?

  1. A.experimental_taintObjectReference
  2. B.useDeferredValue on the user object
  3. C.React.memo wrapping the user object
  4. D.startTransition around the user fetch
Show answer

Answer: A. experimental_taintObjectReference

React taint APIs mark an object or value so React throws if it is sent to the client. They are a safety net; the main defence is a data-access layer that returns only safe fields (DTOs).

55. CSRF protection for Server Actions

What built-in protection do Server Actions have against cross-site request forgery?

  1. A.Each action requires a CAPTCHA by default
  2. B.Only POST is allowed, and Origin is checked against Host
  3. C.Server Actions refuse all requests with cookies
  4. D.They check a secret that is kept in localStorage
Show answer

Answer: B. Only POST is allowed, and Origin is checked against Host

Server Actions accept only POST and compare the Origin header with the Host. Behind proxies with different hosts, add allowed origins to serverActions.allowedOrigins, carefully.

56. ISR across several containers

A self-hosted app runs 4 containers. After revalidateTag, some users still see stale data. Why?

  1. A.revalidateTag works only on Vercel hosting
  2. B.Each container has its own local cache by default
  3. C.ISR needs a single CPU core to work
  4. D.Tags are case-insensitive across containers
Show answer

Answer: B. Each container has its own local cache by default

The default cache lives on each instance's disk or memory. Revalidating on one does not clear the others. Configure a shared cache handler, for example Redis, so all instances share entries.

57. Using an external image CDN

You already pay for an image CDN and want next/image URLs to point there instead of Next.js optimisation. What do you set?

  1. A.images.unoptimized set to false in config
  2. B.images.remotePatterns set to an empty array
  3. C.The quality prop set to 100 on each image
  4. D.A custom loader in images.loader or loaderFile
Show answer

Answer: D. A custom loader in images.loader or loaderFile

A loader function builds the CDN URL from src, width and quality. Next.js still generates srcset and sizes, but transforms happen at the CDN, removing load from your server.

58. Sharing cache in Kubernetes

A self-hosted Next.js app on Kubernetes needs ISR and 'use cache' entries shared across pods. What do you configure?

  1. A.output: 'export' so there is no cache at all
  2. B.A larger disk for each pod in the cluster
  3. C.export const dynamic on every single page
  4. D.A custom cache handler backed by a shared store
Show answer

Answer: D. A custom cache handler backed by a shared store

Next.js lets you plug in cache handlers (cacheHandler and cacheHandlers) that read and write to Redis or similar. All pods then see the same entries and revalidations.

59. Streaming an AI answer

A route handler must stream tokens from an LLM to the browser as they arrive. What should it return?

  1. A.A JSON object after all tokens arrive
  2. B.A Response wrapping a ReadableStream
  3. C.A redirect to the model provider URL
  4. D.A Server Component that awaits all text
Show answer

Answer: B. A Response wrapping a ReadableStream

Route handlers use Web Response, which accepts a ReadableStream body. Writing chunks as they arrive lets the browser show text at once. Libraries like the AI SDK give helpers for this.

60. Pages Router fallback: blocking

In a legacy Pages Router app, getStaticPaths returns fallback: 'blocking'. What happens for a path not built ahead?

  1. A.A 404 is returned until the next full build
  2. B.A loading page is shown, then data fills in
  3. C.The server renders it on first request, then caches it
  4. D.The request is sent to a route handler
Show answer

Answer: C. The server renders it on first request, then caches it

With blocking, the first visitor waits for server rendering, like SSR, then the page is cached as static. fallback: true would show a fallback UI first, and false would give a 404.

Ready to test yourself?

Take a 15-question Next.js MCQ test with a score at the end, or practise the full Next.js question bank and earn points on the leaderboard.