Skip to main content
Frontend & Core Web

Next.js Interview Questions

All Levels (Junior to Staff)16 Questions

Production architecture interview guide for Next.js App Router, React Server Components (RSC), streaming SSR, ISR caching, and edge middleware routing.

22 min study timeIncludes Production Code & Pitfall TrapsActive Recall Practice Mode Available

Practice Next.js Interview Questions

Showing 16 of 16 technical questions with engineering explanations

Filter Level:
Question #1FundamentalJunior

How do layout.tsx, template.tsx, loading.tsx, and error.tsx compose inside Next.js App Router segments?

Senior Engineering Answer

Next.js wraps each route segment's page.tsx inside a predictable nested React tree: Layout > Template > ErrorBoundary > Suspense(fallback=Loading) > NotFoundBoundary > Page. layout.tsx preserves state and does NOT remount when navigating between sibling routes sharing that layout. template.tsx looks similar but creates a fresh DOM subtree and resets state on every route navigation (useful for page-view tracking or enter animations). loading.tsx automatically wraps page.tsx in a React Suspense fallback, and error.tsx (which must be a 'use client' component) catches runtime errors in child segments.

Production Code Example
// app/dashboard/error.tsx
"use client";

export default function DashboardError({
  error,
  reset
}: {
  error: Error & { digest?: string };
  reset: () => void;
}) {
  return (
    <div>
      <p>Failed to load dashboard: {error.message}</p>
      <button onClick={() => reset()}>Retry</button>
    </div>
  );
}
Common Interview Trap / Anti-Pattern:

An error.tsx file cannot catch errors thrown inside a layout.tsx in the SAME directory because Layout sits above ErrorBoundary in the component hierarchy; place error.tsx in the parent segment or use global-error.tsx for root layout errors.

Question #2FundamentalJunior

When do you add 'use client' in Next.js App Router, and what values cannot cross the Server-to-Client prop boundary?

Senior Engineering Answer

Every component in App Router defaults to a React Server Component. Add 'use client' at the top of a file only when the component (or its child imports) needs React hooks (useState, useEffect), browser APIs (window, localStorage), or interactive event handlers (onClick, onChange). Props passed from a Server Component to a Client Component must be serializable across the RSC payload protocol—functions/closures (except Server Actions), class instances, Symbols, and DOM nodes cannot be passed as props.

Production Code Example
// app/products/page.tsx (Server Component)
import { AddToCartButton } from "./AddToCartButton";

export default async function ProductPage({ params }: { params: Promise<{ id: string }> }) {
  const { id } = await params;
  const product = await fetchProduct(id);
  // Pass plain serializable primitives/objects to the Client Component
  return <AddToCartButton productId={product.id} priceCents={product.priceCents} />;
}
Common Interview Trap / Anti-Pattern:

Putting 'use client' on your root layout or top-level page unnecessarily turns the entire subtree into client-bundled JavaScript and loses zero-bundle Server Component benefits.

Question #3FundamentalJunior

Why does calling useSearchParams() in a static App Router page fail the production build unless wrapped in Suspense?

Senior Engineering Answer

During 'next build' static prerendering, URL query parameters (?sort=price) do not exist at build time. Calling useSearchParams() inside a Client Component without a <Suspense> boundary forces Next.js to bail out of static HTML generation up to the nearest Suspense boundary (or fail static build checks with 'useSearchParams() should be wrapped in a suspense boundary'). Wrapping the small Client Component in <Suspense> lets Next.js prerender the static shell and hydrate the query-dependent component on the client.

Production Code Example
import { Suspense } from "react";
import { SearchFilterBar } from "./SearchFilterBar"; // uses useSearchParams()

export default function CatalogPage() {
  return (
    <section>
      <h1>Catalog</h1>
      <Suspense fallback={<div>Loading filters...</div>}>
        <SearchFilterBar />
      </Suspense>
    </section>
  );
}
Common Interview Trap / Anti-Pattern:

Forgetting that in Server Components, the 'searchParams' page prop is directly available (as a Promise in Next.js 15+) and automatically opts that route into Dynamic Rendering at request time.

Question #4FundamentalJunior

How do next/image and next/font optimize Core Web Vitals (LCP and CLS)?

Senior Engineering Answer

next/image reserves exact layout space via width/height (or fill with sized parent) to eliminate Cumulative Layout Shift (CLS), lazily loads below-the-fold images, serves modern AVIF/WebP formats, and generates responsive srcset sizes. Marking the hero image with 'priority' (or preload) injects a <link rel='preload'> and disables lazy loading to optimize Largest Contentful Paint (LCP). next/font downloads Google Fonts at build time (zero runtime requests to Google), self-hosts subsetted WOFF2 files, and generates size-adjusted CSS fallback metrics to prevent font-swap layout shifts.

Production Code Example
import Image from "next/image";
import { Inter } from "next/font/google";

const inter = Inter({ subsets: ["latin"], display: "swap" });

export function Hero({ src }: { src: string }) {
  return (
    <div className={inter.className}>
      <Image src={src} alt="Product hero" width={1200} height={630} priority sizes="(max-width: 768px) 100vw, 1200px" />
    </div>
  );
}
Common Interview Trap / Anti-Pattern:

Using Image with 'fill' without passing a responsive 'sizes' prop causes the browser to download the full-width 100vw desktop asset even inside a tiny 200px card on mobile.

Question #5IntermediateMid

What triggers Dynamic Rendering vs Static Rendering in Next.js App Router, and what changed in Next.js 15+?

Senior Engineering Answer

By default, Next.js statically renders routes at build time when they depend only on build-time data. Calling Dynamic APIs—cookies(), headers(), draftMode(), or reading searchParams in a page—automatically switches the route to Dynamic Rendering (executed per request). In Next.js 14, fetch() defaulted to 'force-cache', whereas in Next.js 15+, fetch() defaults to 'no-store' and GET Route Handlers are uncached by default unless explicitly opted into caching with 'force-cache' or `export const dynamic = 'force-static'`.

Production Code Example
// Explicitly opt a Route Handler or page fetch into build-time / revalidated caching
export const revalidate = 3600;

export async function getCatalog() {
  const res = await fetch("https://api.example.com/catalog", {
    next: { revalidate: 3600, tags: ["catalog"] }
  });
  return res.json();
}
Common Interview Trap / Anti-Pattern:

Reading cookies() inside a shared root layout forces EVERY nested route in your app into Dynamic Rendering, disabling static/ISR optimization site-wide; push cookie reads down into leaf components or Suspense boundaries.

Question #6IntermediateMid

When should you use a Next.js Server Action ('use server') versus an API Route Handler (route.ts)?

Senior Engineering Answer

Server Actions are RPC-style POST endpoints bound to forms or client event handlers; they integrate tightly with React transitions, progressive enhancement (working even before hydration completes), and can revalidate Next.js cache tags/paths and return updated RSC payloads in a single round-trip. Use Route Handlers (route.ts) for public REST/webhook endpoints consumed by external services (Stripe webhooks, mobile apps, OAuth callbacks), custom HTTP verbs (GET, PUT, DELETE), custom headers/status codes, or streaming non-RSC payloads (PDFs, SSE, CSV exports).

Production Code Example
// app/actions/billing.ts
"use server";

import { revalidateTag } from "next/cache";
import { getSession } from "@/lib/auth";

export async function updatePlan(planId: string) {
  const session = await getSession();
  if (!session) throw new Error("Unauthorized");
  await db.subscriptions.update({ userId: session.userId, planId });
  revalidateTag(`sub-${session.userId}`);
}
Common Interview Trap / Anti-Pattern:

Treating Server Actions as private internal functions—they compile to publicly reachable HTTP POST endpoints! Every Server Action MUST authenticate the caller and validate all input arguments with Zod/Valibot.

Question #7IntermediateMid

How do generateStaticParams and dynamicParams control build-time vs on-demand static page generation?

Senior Engineering Answer

In a dynamic segment like app/blog/[slug]/page.tsx, exporting async function generateStaticParams() returns the array of slug objects to pre-render as static HTML during 'next build'. The route segment option 'export const dynamicParams = true' (default) allows un-listed slugs to render dynamically on first request and cache afterward, whereas 'export const dynamicParams = false' immediately returns a 404 for any slug not returned by generateStaticParams.

Production Code Example
export const dynamicParams = true;

export async function generateStaticParams() {
  const posts = await db.posts.findMany({ select: { slug: true }, take: 100 });
  return posts.map((post) => ({ slug: post.slug }));
}

export default async function BlogPost({ params }: { params: Promise<{ slug: string }> }) {
  const { slug } = await params;
  const post = await getPostBySlug(slug);
  if (!post) notFound();
  return <article>{post.title}</article>;
}
Common Interview Trap / Anti-Pattern:

Generating 50,000 pages inside generateStaticParams blows up CI build times; pre-render only the top N traffic routes and let dynamicParams = true generate and cache long-tail pages on first visit.

Question #8IntermediateMid

Why does parallelizing Server Component queries matter, and how do you avoid request waterfalls in Next.js?

Senior Engineering Answer

Awaiting independent database queries or fetches sequentially inside an async Server Component—or nesting parent/child async Server Components where each waits before mounting the next—creates an additive network waterfall. Initiate independent fetches concurrently with Promise.all() (or Promise.allSettled()), wrap slower secondary panels in separate <Suspense> boundaries so fast content streams immediately, and deduplicate repeated identical fetches across sibling components using React.cache().

Production Code Example
import { cache } from "react";

export const getUser = cache(async (id: string) => {
  return db.users.findUnique({ where: { id } });
});

export default async function ProfilePage({ params }: { params: Promise<{ id: string }> }) {
  const { id } = await params;
  const [user, orders] = await Promise.all([getUser(id), getRecentOrders(id)]);
  return <ProfileView user={user} orders={orders} />;
}
Common Interview Trap / Anti-Pattern:

Calling non-fetch ORM calls (Prisma, Drizzle) in both generateMetadata() and page.tsx triggers duplicate DB queries per request unless wrapped in React's cache().

Question #9SeniorSenior

Explain the four Next.js caching layers (Request Memoization, Data Cache, Full Route Cache, Client Router Cache) and how they interact.

Senior Engineering Answer

(1) Request Memoization (React scope, per-request): deduplicates identical GET fetch() URLs or React cache() calls within a single server render pass. (2) Data Cache (server/persistent): stores fetch/unstable_cache results across requests and deployments until revalidated. (3) Full Route Cache (server/build+ISR): stores rendered HTML + RSC payload for static routes. (4) Client Router Cache (browser memory): caches visited/prefetched RSC payloads during client navigation—in Next.js 15+, Page segments default to staleTime: 0 (no stale client cache on navigation) while shared Layouts remain cached and prefetching still warms the cache.

Production Code Example
// Invalidating Data Cache also invalidates dependent Full Route Cache entries
import { revalidateTag } from "next/cache";

export async function publishPost(slug: string) {
  await db.posts.publish(slug);
  revalidateTag("posts");
}
Common Interview Trap / Anti-Pattern:

Assuming Request Memoization persists across users: it exists ONLY for the duration of one HTTP render pass and is discarded immediately afterward.

Question #10SeniorSenior

Compare revalidatePath, revalidateTag, and time-based ISR: how do you avoid stale reads immediately after a user mutation?

Senior Engineering Answer

Time-based ISR (next: { revalidate: 60 }) uses stale-while-revalidate: the first request after 60s still receives the stale page while background regeneration runs. On-demand invalidation via revalidateTag('key') targets specific tagged queries across all pages that consume them, whereas revalidatePath('/posts/[slug]', 'page') purges a specific route. Calling revalidateTag or revalidatePath inside a Server Action instructs Next.js to purge the cache AND immediately re-render the active route in the same Server Action response so the mutating user sees fresh data immediately (read-your-own-writes).

Production Code Example
"use server";
import { revalidateTag } from "next/cache";

export async function createComment(postId: string, body: string) {
  await db.comments.create({ data: { postId, body } });
  revalidateTag(`comments-${postId}`);
}
Common Interview Trap / Anti-Pattern:

Calling revalidateTag inside a Route Handler does not auto-refresh the browser's current page unless the client calls router.refresh(); Server Actions automatically push the revalidated RSC payload back to the client.

Question #11SeniorSenior

How does Partial Prerendering (PPR) combine static shells with dynamic streaming holes in one HTTP response?

Senior Engineering Answer

Traditionally, reading a single dynamic API (like cookies() for a user's cart badge) turned the entire route dynamic, delaying TTFB until backend queries finished. With Partial Prerendering, Next.js prerenders everything outside dynamic <Suspense> boundaries into an instant static shell (navigation, layout, product hero, fallback skeletons) served immediately at edge speed. Inside the same HTTP stream, the server concurrently executes the dynamic <Suspense> subtrees (personalized pricing, cart count) and streams their HTML and RSC chunks into the placeholder slots as they resolve.

Production Code Example
import { Suspense } from "react";
import { PersonalizedCart } from "./PersonalizedCart"; // reads cookies()

export default function StorefrontPage() {
  return (
    <main>
      <StaticHeroBanner />
      <Suspense fallback={<CartSkeleton />}>
        <PersonalizedCart />
      </Suspense>
    </main>
  );
}
Common Interview Trap / Anti-Pattern:

Placing a dynamic cookie/header read above the <Suspense> boundary forces the entire page shell to block dynamically instead of streaming from the prerendered shell.

Question #12SeniorSenior

What are the runtime limits and security pitfalls of Next.js Middleware (middleware.ts)?

Senior Engineering Answer

Next.js Middleware runs before every matched route (historically on the Edge runtime—a lightweight V8 isolate lacking Node fs/net/native addons—with Node.js middleware added as an opt-in in newer Next.js releases). Because it executes on the hot path of every navigation and static asset unless filtered via config.matcher, Middleware should only perform fast, stateless operations: verifying signed JWTs/session cookies, geolocation/A-B rewrites, locale routing, or setting security headers. Never rely on Middleware alone as your security boundary, because CVE-class header/internal routing bypasses or direct Server Action invocations require defense-in-depth inside your Data Access Layer.

Production Code Example
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";

export function middleware(req: NextRequest) {
  const token = req.cookies.get("session")?.value;
  if (!token && req.nextUrl.pathname.startsWith("/app")) {
    return NextResponse.redirect(new URL("/login", req.url));
  }
  return NextResponse.next();
}

export const config = {
  matcher: ["/((?!_next/static|_next/image|favicon.ico).*)"]
};
Common Interview Trap / Anti-Pattern:

Omitting '_next/static' and '_next/image' from config.matcher runs middleware on every JS chunk and image request, wasting edge invocations and breaking asset loading if auth redirects trigger on static chunks.

Question #13PrincipalStaff

How do you prevent accidentally leaking sensitive database fields or server secrets across the RSC/Client boundary?

Senior Engineering Answer

Passing an entire ORM record (<ClientCard user={dbUser} />) serializes every property on that object—including passwordHash, stripeCustomerId, or internal notes—into the public HTML/RSC payload. Enforce a strict Data Access Layer (DAL) pattern: (1) import 'server-only' in DB/secret modules so importing them in any Client Component fails at build time, (2) project explicit DTO objects (selecting only safe public fields) before returning from DAL functions, and (3) use React's experimental_taintObjectReference / experimental_taintUniqueValue as a runtime safety net against accidental serialization of secret objects.

Production Code Example
// lib/dal/user.ts
import "server-only";
import { cache } from "react";

export const getPublicUserDto = cache(async (userId: string) => {
  const row = await db.users.findUnique({ where: { id: userId } });
  if (!row) return null;
  return { id: row.id, displayName: row.displayName, avatarUrl: row.avatarUrl };
});
Common Interview Trap / Anti-Pattern:

Prefixing environment variables with NEXT_PUBLIC_ inlines them directly into browser bundles at build time; never store API keys or secrets in NEXT_PUBLIC_* variables.

Question #14PrincipalStaff

How do Parallel Routes (@slot) and Intercepting Routes ((.)segment) implement URL-addressable modals cleanly?

Senior Engineering Answer

Parallel Routes (@modal) allow rendering multiple independent pages simultaneously within the same layout, each with its own loading.tsx and error.tsx. Intercepting Routes ((.)photos/[id]) intercept soft client-side navigation from a parent route to render a lightweight modal inside the @modal slot while updating the browser URL to /photos/42. On a full page refresh or shared external link, Next.js renders the canonical full-page app/photos/[id]/page.tsx instead, and a default.tsx file in @modal returns null when the modal slot is inactive.

Production Code Example
// app/layout.tsx
export default function RootLayout({
  children,
  modal
}: {
  children: React.ReactNode;
  modal: React.ReactNode;
}) {
  return (
    <html>
      <body>
        {children}
        {modal}
      </body>
    </html>
  );
}
Common Interview Trap / Anti-Pattern:

Forgetting to add default.tsx inside the @modal slot causes 404 errors on hard page reloads of sibling routes because Next.js cannot resolve an unmatched active state for the parallel slot.

Question #15PrincipalStaff

What architectural changes are required to run multi-instance Next.js in Kubernetes or containers without stale cache split-brain?

Senior Engineering Answer

By default, Next.js stores the Data Cache and ISR artifacts on the local filesystem (.next/cache). In a horizontally scaled multi-pod deployment, Pod A running revalidateTag('products') purges only Pod A's disk cache while Pods B and C keep serving stale responses. Fix this by enabling `output: 'standalone'` in next.config for minimal Docker images, configuring a shared custom `cacheHandler` backed by Redis or S3/DynamoDB so all pods share one Data/ISR cache, offloading `_next/image` resizing to a dedicated CDN/image proxy, and setting `serverActions` encryption keys (`NEXT_SERVER_ACTIONS_ENCRYPTION_KEY`) consistently across replicas so rolling deploys do not invalidate in-flight Server Actions.

Production Code Example
// next.config.ts
import type { NextConfig } from "next";

const nextConfig: NextConfig = {
  output: "standalone",
  cacheHandler: require.resolve("./lib/redis-cache-handler.mjs"),
  cacheMaxMemorySize: 0 // disable per-pod in-memory cache so Redis is authoritative
};

export default nextConfig;
Common Interview Trap / Anti-Pattern:

Rotating builds across Kubernetes pods without pinning NEXT_SERVER_ACTIONS_ENCRYPTION_KEY or matching buildIds causes clients on old tabs to fail Server Action decryption and chunk loads during rollouts.

Question #16PrincipalStaff

How do you profile and eliminate client bundle bloat and slow TTFB in a large Next.js production app?

Senior Engineering Answer

Inspect client JS chunk weights with `@next/bundle-analyzer` (`ANALYZE=true next build`) to catch accidental client bundling of heavy icon/date/chart barrel packages—enable `experimental.optimizePackageImports` for icon libraries and dynamically import heavy client widgets (`next/dynamic` with `ssr: false` only when browser-only). On the server side, wire OpenTelemetry via Next.js's native `instrumentation.ts` (`register()`) to trace spans across middleware, Server Components, fetch calls, and DB queries, exposing slow TTFB waterfalls and un-cached dynamic routes.

Production Code Example
// instrumentation.ts
export async function register() {
  if (process.env.NEXT_RUNTIME === "nodejs") {
    const { initTelemetry } = await import("./lib/otel-node");
    initTelemetry();
  }
}
Common Interview Trap / Anti-Pattern:

Importing a single helper from a large barrel file (e.g., `import { Button } from '@acme/ui'`) inside a 'use client' component can pull an entire 300KB icon or chart dependency into the client chunk unless tree-shaken or listed in optimizePackageImports.

Next.js Track Coverage & Difficulty Profile

16 of 16 prompts include code examples

This Next.js preparation set groups 16 prompts across Junior (4), Mid (4), Senior (4), Staff (4) roles with 4 fundamental, 4 intermediate, 4 senior, 4 principal exercises tailored to Frontend & Core Web.

JuniorFundamental

How do layout.tsx, template.tsx, loading.tsx, and error.tsx compose inside Next.js App Router segments?

JuniorFundamental

When do you add 'use client' in Next.js App Router, and what values cannot cross the Server-to-Client prop boundary?

JuniorFundamental

Why does calling useSearchParams() in a static App Router page fail the production build unless wrapped in Suspense?

JuniorFundamental

How do next/image and next/font optimize Core Web Vitals (LCP and CLS)?

MidIntermediate

What triggers Dynamic Rendering vs Static Rendering in Next.js App Router, and what changed in Next.js 15+?

MidIntermediate

When should you use a Next.js Server Action ('use server') versus an API Route Handler (route.ts)?

Frequently Asked Technical Interview Questions (Next.js)

Essential theoretical concepts, architecture trade-offs, and runtime design questions asked by hiring committees.

What is Incremental Static Regeneration (ISR) and how does stale-while-revalidate work?
ISR updates static pages without a full rebuild. When a request arrives after the revalidate window expires, Next.js serves the cached stale HTML immediately while regenerating the updated page asynchronously in the background for subsequent requests.
What is the difference between revalidatePath and revalidateTag in Next.js?
revalidatePath purges cached entries for a specific URL route path (e.g., '/products/123'), whereas revalidateTag purges all cached data entries tagged with a semantic cache tag across every route that consumes that data.
How does Partial Prerendering (PPR) improve TTFB and FCP?
PPR serves a static prerendered HTML shell immediately from the edge while streaming personalized dynamic components inside React Suspense boundaries over the same HTTP response.
How do Server Actions authenticate requests safely?
Because Server Actions compile into public HTTP POST endpoints, each Server Action must independently verify the user's session and authorize permissions and input payloads rather than relying solely on Middleware or client UI guards.
Complete Learning Ecosystem

Pair Interview Prep with Cheat Sheets & Roadmaps

Review syntax formulas on our interactive cheat sheets, test your skills in technical quizzes, and study high-scale system designs.

Want to practice other technologies?

Explore our comprehensive technical interview tracks across all core technology stacks.

Browse All Interview Tracks