Next.js interview questions and answers for React developers
Next.js interview questions center on where code runs and when HTML is produced: server components versus client components, static versus dynamic rendering, and how caching and revalidation decide whether a user sees fresh data. Expect App Router questions on layouts, loading states, server actions and route handlers, plus Pages Router questions if the company has an older codebase. Because caching defaults changed between major versions, the best answers say which version they are describing.
By Evin JohnPublished 7 min read
How Next.js is tested in interviews
Next.js comes up in frontend and full-stack interviews wherever the product is built on React and rendered on the server. A Next.js developer interview usually mixes React fundamentals with framework questions, a small build (a page that fetches data, a form that mutates it) and a debugging or performance conversation. If your React basics are shaky, start with frontend developer interview questions; this page assumes components, props, state and hooks.
- Framework conceptsRendering modes, the two routers, server versus client components, what the build step produces.
- Practical taskBuild a list and detail page with a dynamic route, a loading state and a form. Reviewers check where you put 'use client'.
- Caching and data freshnessWhy a page shows stale data after an update, or why a page that should be static renders on every request.
- Production topicsAuth at the edge, images, Core Web Vitals, environment variables, and self-hosting versus a managed platform.
Next.js fundamentals questions
| Question | What it tests | What a strong answer shows |
|---|---|---|
| What does Next.js add on top of React? | Framework purpose | File-based routing, server rendering and static generation, server-side data access, an API layer through route handlers, image and font optimization, and a build pipeline. React alone renders components; Next.js decides where and when. |
| App Router versus Pages Router? | Routers | The App Router (the app directory) is built on React Server Components with nested layouts, streaming and server actions. The Pages Router (pages directory) uses getServerSideProps, getStaticProps and API routes. Both are supported and can coexist during a migration. |
| What is a server component? | RSC | A component that renders only on the server and sends no JavaScript for itself to the browser. It can read databases and secrets directly but cannot use state, effects or browser APIs. In the App Router, components are server components unless marked otherwise. |
| What does 'use client' do? | Boundary | It marks a module, and everything it imports, as part of the client bundle. Put it as low in the tree as possible, on the interactive leaf, not on the whole page. |
| What are layout.tsx, page.tsx, loading.tsx and error.tsx? | File conventions | A layout wraps child routes and keeps its state across navigation, a page is the route's UI, loading becomes a Suspense fallback, and error is a client error boundary for that segment. |
| How do dynamic routes work? | Routing | A folder such as [id] becomes a parameter, [...slug] catches all segments. In recent versions params arrive as a Promise you await in server components. |
| SSR, SSG and ISR in one sentence each? | Rendering modes | SSR renders on each request. SSG renders at build time. ISR serves a static page and regenerates it after a set time or on demand, so static pages can still change. |
| What is hydration? | Client runtime | React attaches event handlers to server-rendered HTML in the browser. If the client's first render differs from the server HTML, you get a hydration mismatch. |
| How do Link and prefetching help? | Navigation | next/link does client-side navigation and prefetches routes in the viewport, so the next page's payload is often ready before the click. |
| Which environment variables reach the browser? | Config and safety | Only those prefixed with NEXT_PUBLIC_, and they are inlined at build time. Everything else stays on the server; secrets must never get that prefix. |
Server components, data fetching and caching
import { notFound } from "next/navigation";
type Product = { id: string; name: string; priceCents: number };
async function getProduct(id: string): Promise<Product | null> {
const res = await fetch(`https://api.example.com/products/${id}`, {
next: { revalidate: 300 }, // cache, then refresh in the background after 300 s
});
if (res.status === 404) return null;
if (!res.ok) throw new Error(`Product request failed: ${res.status}`);
return res.json();
}
export default async function ProductPage({
params,
}: {
params: Promise<{ id: string }>;
}) {
const { id } = await params;
const product = await getProduct(id);
if (!product) notFound();
return <h1>{product.name}</h1>;
}- Is fetch cached by default? It depends on the version, so say which one you mean. In Next.js 13 and 14, fetch in server components was cached by default. From Next.js 15 it is not, and you opt in with options such as
next: { revalidate }orcache: "force-cache". Newer versions also add theuse cachedirective; check what the team runs. - What makes a route dynamic? Reading request-time data such as cookies(), headers() or searchParams, or uncached fetches. Then the route cannot be fully prerendered at build time.
- Time-based versus on-demand revalidation? Time-based refreshes after N seconds on the next request. On-demand calls revalidatePath or revalidateTag after a write, so the change shows at once instead of after the timer.
- How does streaming work? The server sends the layout and fast parts first, and slow parts wrapped in Suspense (or covered by loading.tsx) arrive later in the same response. Users see content sooner and time to first byte improves.
- How do you avoid request waterfalls in server components? Start independent fetches together with Promise.all, or push slow sections into their own Suspense boundary so they do not block the rest.
- Can a client component import a server component? Not directly. Pass the server component as children or another prop from a server parent; it renders on the server and slots into the client tree.
- What must props crossing into a client component look like? Serializable: plain objects, arrays, strings, numbers, dates and similar. Functions cannot cross, except server actions.
- How did the Pages Router do the same thing? getStaticProps with revalidate for SSG and ISR, getStaticPaths for dynamic static pages, getServerSideProps for per-request rendering. Expect this on older codebases.
Server actions, route handlers and middleware
"use server";
import { revalidatePath } from "next/cache";
import { getSession } from "@/lib/auth";
import { db } from "@/lib/db";
export async function addTodo(formData: FormData) {
const session = await getSession();
if (!session) throw new Error("Not signed in");
const title = String(formData.get("title") ?? "").trim();
if (title.length === 0 || title.length > 200) return;
await db.todo.create({ data: { title, userId: session.userId } });
revalidatePath("/todos");
}| Question | What it tests | What a strong answer shows |
|---|---|---|
| What is a server action? | Mutations | An async function marked 'use server' that the client can call, often as a form's action. Next.js turns it into a POST endpoint, which is why it needs its own validation and auth checks. |
| Server action or route handler? | API design | Actions suit mutations from your own UI. Route handlers (route.ts with GET, POST and so on) suit webhooks, third-party clients, file downloads and anything that needs a stable public URL. |
| Are GET route handlers cached? | Version awareness | Not by default from Next.js 15; in 14 they were static by default when they used no dynamic input. You opt in with a segment config such as dynamic = "force-static". |
| What is middleware for, and what is it not for? | Middleware | Runs before a request is routed: redirects, rewrites, headers, a quick session cookie check. It is not the place for heavy data access. Newer versions rename the file convention from middleware to proxy, with a codemod. |
| Where do you enforce authorization? | Security | Close to the data: in the server action, route handler or data function. A middleware redirect is a convenience, not the only check. |
| How do you handle forms with pending and error states? | UX | useFormStatus or useActionState from React with a server action, plus validation messages returned from the action. The form should also work before JavaScript loads. |
import { NextResponse, type NextRequest } from "next/server";
export function middleware(request: NextRequest) {
if (!request.cookies.has("session")) {
return NextResponse.redirect(new URL("/login", request.url));
}
return NextResponse.next();
}
export const config = { matcher: ["/dashboard/:path*"] };Senior Next.js and debugging questions
| Scenario | Likely cause | What to say you would check |
|---|---|---|
| A product page still shows the old price after an edit. | Cached data or route | Which cache holds it: a cached fetch, a prerendered route, or the client router. Revalidate the path or tag in the mutation, or mark the fetch as uncached. |
| A page you expected to be static renders on every request. | Dynamic API use | A cookies() or headers() call, searchParams, or an uncached fetch deep in the tree. The build output shows which routes are static and which are dynamic. |
| "Text content does not match server-rendered HTML." | Hydration mismatch | Dates, random values, locale formatting or typeof window branches in render, or invalid nesting such as a div inside a p. Render those parts in an effect or on the client only. |
| The client bundle doubled after a feature. | Boundary placement | 'use client' too high, or a heavy library imported into a client component. Check the bundle analyzer, move work to the server, or load it with next/dynamic. |
| Largest Contentful Paint is poor on the home page. | Images and fonts | Use next/image with the priority flag on the hero, correct sizes, and next/font to avoid layout shift and extra font requests. |
| A secret API key appeared in the browser. | Env misuse | A NEXT_PUBLIC_ prefix on a secret, or a server module imported into a client file. Use the server-only package to make that import fail at build time. |
- What does next/image do for you? Resizes and serves modern formats on demand, generates srcset for different screens, lazy loads below the fold and reserves space to prevent layout shift. Remote images need their hosts allowed in config.
- Self-host or a managed platform?
next starton Node works with ISR and middleware; a standalone output trims the deployment. On several instances you need a shared cache for ISR, and image optimization needs its dependencies on the server. - How would you migrate from the Pages Router? Route by route: both routers run side by side, shared layout moves to app/layout, data functions become server component fetches, and API routes move to route handlers when it pays off.
- Edge or Node runtime? Edge starts fast and runs close to users but has a limited API surface. Node supports the full ecosystem and database drivers. Choose per route.
Fictional example
- Interviewer
- After a user updates their budget, the dashboard still shows the old total until they refresh twice. What is happening?
- Candidate
- First I would ask which Next.js version and router, because the caching defaults differ. Assuming the App Router: the total probably comes from a fetch or data function that is cached, and the update path never invalidates it. I would check the mutation, and if it is a server action, add revalidatePath for the dashboard or tag the fetch and call revalidateTag. If it is a separate API, the server can call the same revalidation after the write. The refresh-twice detail suggests the client router cache is also serving the old payload, so router.refresh after the action, or relying on the action's revalidation, would fix that part. Then I would test it by updating and navigating without a full reload.
Next.js practice plan
- Day 1: build a list and a detail route with a dynamic segment, loading.tsx and notFound, all as server components.
- Day 2: add one interactive client component and keep 'use client' on that leaf only; compare the bundle before and after.
- Day 3: add a server action with validation and an auth check, then make the list update with revalidatePath.
- Day 4: mark one page static and one dynamic, read the build output, and explain why each landed where it did.
- Day 5: cause a hydration error on purpose, fix it, and rehearse the caching answer for the version you use.
Related reading: Angular interview questions if the role weighs frameworks against each other, Flask interview questions for a Python API behind a Next.js front end, and software engineer interview questions for the coding rounds that usually come with it.
Caching questions punish vague answers, so rehearse them with a record. Natively, an AI interview assistant for Mac and Windows, transcribes your mock Next.js round on your computer, which shows whether you said which version and which cache you meant. When you practice it can read a component or an error overlay from a screenshot and suggest a fix, and on Pro or the free trial it can work from your résumé and the job description you add. Each session's transcript and notes are saved for later.
Questions people ask
What Next.js questions are asked in interviews?
App Router versus Pages Router, server and client components, SSR, SSG, ISR and streaming, data fetching and caching, revalidation, server actions, route handlers, middleware, next/image and hydration errors.
What is the difference between SSR, SSG and ISR in Next.js?
SSR renders a page on each request, SSG renders it at build time, and ISR serves a static page that is regenerated after a set time or on demand.
Are fetch requests cached by default in Next.js?
It depends on the version. In Next.js 13 and 14 fetch in server components was cached by default; from Next.js 15 it is not, and you opt in with options such as revalidate or force-cache.
When should I use a server action instead of a route handler?
Use server actions for mutations triggered from your own UI, such as forms. Use route handlers for webhooks, external clients and anything that needs a stable public URL.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
