Complete Next.js Progressive Master Question Bank
50 progressive Next.js interview questions covering client/server routing, rendering strategies, caching architecture, data fetching, security, and optimization techniques.
Q1: What is Next.js and why use it over plain React?
Next.js is a full-stack React framework built by Vercel. While plain React is a client-side rendering (CSR) library, Next.js provides hybrid rendering (SSR, SSG, ISR), file-based routing, automatic code splitting, image/font optimizations, Server Components, and API routes out of the box.
// app/about/page.js -> Creates /about route automatically
export default function AboutPage() {
return <h1>About Us</h1>;
}Creating page.js inside the app/about folder instantly maps it to the /about URL path.
Provides full-stack capabilities (Hybrid SSR, SSG, RSC, and API Route endpoints).
Enhances SEO, initial page load speeds, and Core Web Vitals automatically.
What primary performance drawback of traditional React Single Page Applications (SPAs) does Next.js solve?
Q2: What is the difference between the App Router and Pages Router in Next.js?
- Pages Router (
/pages): Legacy routing model using file names as routes. UsesgetStaticPropsandgetServerSidePropsfor data fetching. All components default to Client Components. - App Router (
/app): Modern router introduced in Next.js 13. Built on React Server Components (RSC), uses folder-based conventions (page.js,layout.js), nested layouts, streaming, and Server Actions.
app/
├── layout.js # Shared root layout
├── page.js # Root '/' route page
└── dashboard/
├── layout.js # Nested '/dashboard' layout
└── page.js # '/dashboard' page routeApp Router uses directory hierarchies and special reserved file conventions.
App Router defaults all components to Server Components.
App Router supports nested layouts and streaming Suspense boundaries natively.
What component model do files inside the App Router (/app) adopt by default?
Q3: What are the main rendering modes supported by Next.js (SSR, SSG, ISR, CSR)?
- SSR (Server-Side Rendering): HTML generated on every user request.
- SSG (Static Site Generation): HTML built once at build time.
- ISR (Incremental Static Regeneration): Re-generates static HTML pages in the background after deployment without a full site rebuild.
- CSR (Client-Side Rendering): Rendered dynamically inside the browser.
// 1. SSG (Static Default)
fetch('https://api.com/data', { cache: 'force-cache' });
// 2. SSR (Dynamic per Request)
fetch('https://api.com/data', { cache: 'no-store' });
// 3. ISR (Revalidate every 60 seconds)
fetch('https://api.com/data', { next: { revalidate: 60 } });App Router configures rendering behavior through options in native fetch calls.
SSG offers maximum speed for static content (blogs, docs).
ISR updates static pages periodically on demand using background revalidation.
Which rendering strategy allows updating a static landing page periodically after site deployment without triggering a full rebuild?
Q4: What are the special file conventions in Next.js App Router?
The App Router reserves explicit file names inside route folders:
page.js: Defines route UI.layout.js: Defines shared UI surrounding child pages (persists state across navigation).template.js: Similar to layout, but creates a new instance on every page navigation.loading.js: Creates automatic Suspense fallback UI.error.js: Creates an Error Boundary wrapper.
// app/dashboard/loading.js
export default function Loading() {
return <p>Loading dashboard stats...</p>;
}
// app/dashboard/error.js (Must be a Client Component)
'use client';
export default function Error({ error, reset }) {
return <button onClick={() => reset()}>Try Again</button>;
}loading.js wraps pages in Suspense; error.js isolates route errors inside an Error Boundary.
layout.jsstays mounted and preserves internal component state during route navigation.template.jsre-mounts on every route transition, re-running effects.
What is the key functional difference between layout.js and template.js in the App Router?
Q5: How do React Server Components (RSC) differ from Client Components in Next.js?
Server Components run exclusively on the server, send zero JS bundle code to browsers, and can query databases directly. Client Components are marked with 'use client', run on both server (for initial HTML) and browser, and handle interactivity, state (useState), and event listeners.
// app/page.js (Server Component)
import db from '@/lib/db';
import LikeButton from './LikeButton'; // Client Component
export default async function Page() {
const post = await db.post.findUnique({ id: 1 });
return (
<div>
<h1>{post.title}</h1>
<LikeButton postId={post.id} /> {/* Interactive Child */}
</div>
);
}Server Components fetch database data directly and pass serialized props down to interactive Client Component children.
Server Components reduce client JS bundle size to zero bytes.
Use
'use client'at the top of a file only when event listeners or state hooks are required.
What happens if you attempt to use useState() inside a component without declaring 'use client' in the App Router?
Q6: What does the 'use client' directive actually define?
The 'use client' directive defines a boundary between the Server Component tree and the Client Component tree. Declaring 'use client' at the top of a file marks that module and all of its imported dependencies as Client Components.
// ClientModal.js
'use client';
export default function ClientModal({ children }) {
const [isOpen, setIsOpen] = useState(false);
return isOpen ? <div className="modal">{children}</div> : null;
}
// Page.js (Server Component)
export default function Page() {
return (
<ClientModal>
<ServerDataComponent /> {/* Remains a Server Component! */}
</ClientModal>
);
}Passing Server Components as children slots to Client Components keeps them rendered on the server.
'use client'establishes a module dependency boundary, not just a single-file flag.Keep
'use client'boundaries as low down the component tree as possible to minimize JS bundle size.
How can you render a Server Component inside a Client Component wrapper without turning the Server Component into a client bundle item?
Q7: How does the next/image Component optimize images?
The <Image /> component optimizes images automatically by:
- Format conversion: Serves WebP/AVIF images dynamically.
- Resizing: Generates responsive image srcsets based on device sizes.
- CLS prevention: Enforces explicit dimensions or aspect ratios to eliminate layout shifts.
- Lazy loading: Defers loading off-screen images until scrolled near viewport.
import Image from 'next/image';
import profilePic from './profile.jpg';
export default function Avatar() {
return (
<Image
src={profilePic}
alt="User Avatar"
width={200}
height={200}
placeholder="blur"
priority // Loads immediately above the fold
/>
);
}Setting priority disables lazy loading for above-the-fold hero assets to optimize LCP.
Prevents Cumulative Layout Shift (CLS) by reserving display dimensions.
Converts images on-demand to AVIF/WebP, resizing images to device viewport width.
Which prop should be added to a next/image component if the image is an above-the-fold Hero banner image?
Q8: How does next/font optimize custom typography and prevent layout shift?
next/font automatically downloads font files at build time and hosts them alongside static assets. It injects CSS size-adjust fallbacks to match font metrics, eliminating external network requests to Google Fonts and completely preventing Flash of Unstyled Text (FOUT) and Cumulative Layout Shift (CLS).
import { Inter } from 'next/font/google';
const inter = Inter({ subsets: ['latin'], display: 'swap' });
export default function RootLayout({ children }) {
return (
<html lang="en" className={inter.className}>
<body>{children}</body>
</html>
);
}Inter font files download at build time and apply via CSS class name selectors.
Zero external network requests at runtime; fonts are self-hosted automatically.
Eliminates FOUT and CLS using size-adjust CSS fallbacks.
Does next/font make browser network calls to Google Fonts servers when users visit the site in production?
Q9: How do Dynamic Routes, Catch-all, and Optional Catch-all routes work in Next.js?
- Dynamic Route (
[id]): Matches single segment parameter (/posts/1->{ id: '1' }). - Catch-all (
[...slug]): Matches multiple path segments (/shop/clothes/shoes->{ slug: ['clothes', 'shoes'] }). Requires segment to exist. - Optional Catch-all (
[[...slug]]): Matches multiple segments AND root path (/shop->{ slug: undefined }).
// app/shop/[[...slug]]/page.js
export default async function ShopPage({ params }) {
const { slug } = await params; // Array or undefined
return <p>Active Path Categories: {slug ? slug.join(' > ') : 'Root Shop'}</p>;
}Optional catch-all handles /shop, /shop/men, and /shop/men/shoes inside a single page file.
[id]captures a single path segment.[...slug]captures array of segments;[[...slug]]also matches the base route without segments.
Which folder naming convention matches both /docs AND /docs/installation/setup?
Q10: What is generateStaticParams and how does it replace getStaticPaths?
In the App Router, generateStaticParams replaces the legacy getStaticPaths. Used inside dynamic routes ([id]), it returns an array of segment objects to pre-render routes at build time (SSG). Uncompiled routes fallback to dynamic on-demand rendering.
// app/posts/[id]/page.js
export async function generateStaticParams() {
const posts = await fetch('https://api.com/posts').then(res => res.json());
return posts.map(post => ({ id: String(post.id) }));
}
export default async function PostPage({ params }) {
const { id } = await params;
return <h1>Post ID: {id}</h1>;
}generateStaticParams outputs route parameters pre-rendered statically during build time.
Pre-renders dynamic routes (
[id]) statically during build time.Combines with
export const dynamicParams = falseto return 404 for non-generated paths.
What is the App Router equivalent of the legacy Pages Router getStaticPaths function?
Q11: What are Route Groups and how are parentheses folders used?
Route Groups use parenthesized folder names like (marketing) or (auth). They allow organizing route files without affecting the URL path structure. Useful for splitting application sub-trees to use different layout wrappers.
app/
├── (marketing)/
│ ├── layout.js # Marketing Layout (with public Header/Footer)
│ └── page.js # URL: '/'
└── (dashboard)/
├── layout.js # Dashboard Layout (with Sidebar/Auth Check)
└── page.js # URL: '/dashboard'Routes are accessed via / and /dashboard without exposing (marketing) or (dashboard) in URLs.
Parentheses
(group)omit folder names from the final browser URL path.Allows multiple root layouts across separate route groups inside the app folder.
What is the resolved URL path for a page located at app/(marketing)/about/page.js?
Q12: What are Parallel Routes (@slot) in Next.js?
Parallel Routes render one or more pages simultaneously inside the same layout using named slots (@slot). They allow building complex dashboard interfaces, modals, and conditional split-screen layouts with independent error and loading states.
// Directory: app/dashboard/@analytics/page.js & app/dashboard/@team/page.js
// app/dashboard/layout.js
export default function DashboardLayout({ children, analytics, team }) {
return (
<div>
{children}
<div className="grid-2-col">
{analytics} {/* Renders @analytics/page.js */}
{team} {/* Renders @team/page.js */}
</div>
</div>
);
}@analytics and @team slots pass as props into DashboardLayout to render side-by-side.
Folders prefixed with
@define slot props passed directly into the parent layout.Allows independent loading states and routing for split-screen interfaces.
How are slot folders designated when implementing Parallel Routes in the App Router?
Q13: What are Intercepting Routes and how do they power Modal overlays?
Intercepting Routes allow loading a route inside the current layout while masking the URL path (e.g., opening a photo modal over a feed). When navigated to via client links, the intercepted route modal displays. When refreshed or accessed directly via URL, the full standalone page renders.
app/
├── feed/
│ ├── page.js
│ └── photo/[id]/
│ └── page.js # Full standalone photo page (Hard Refresh)
└── @modal/
└── (..)photo/[id]/
└── page.js # Intercepted photo modal overlay (Soft Click)Clicking a photo in feed renders the photo inside @modal overlay; refreshing renders full photo page.
Syntax conventions:
(.)matches same level,(..)matches one level up,(...)matches root app.Powers soft navigation modals while keeping URLs shareable.
What happens when a user directly navigates to or hard-refreshes a shareable URL that uses an Intercepting Route?
Q14: What are Server Actions and how do they eliminate API endpoints?
Server Actions are asynchronous functions executed directly on the server. Annotated with 'use server', they can be called from client form submissions or event handlers to perform data mutations, set cookies, and revalidate cached paths without manual API route boilerplate.
// app/actions.js
'use server';
import { revalidatePath } from 'next/cache';
export async function updateProfile(formData) {
const name = formData.get('name');
await db.user.update({ where: { id: 1 }, data: { name } });
revalidatePath('/profile'); // Invalidate static cache
}Server Actions run on Node.js/Edge servers, performing direct DB writes and cache revalidations.
Annotated using
'use server'directive.Can be invoked directly from
<form action={myAction}>or client button event callbacks.
Which directive marks a function or file as an executable Server Action in Next.js?
Q15: How do revalidatePath and revalidateTag clear the Data Cache?
Next.js aggressively caches fetch requests in the Data Cache. To purge stale cache data on demand:
revalidatePath('/posts'): Purges cached data associated with a specific URL route path.revalidateTag('posts-tag'): Purges cached fetch requests tagged with a matching tag identifier (fetch(url, { next: { tags: ['posts-tag'] } })).
// Fetching with tag
fetch('https://api.com/posts', { next: { tags: ['posts'] } });
// Inside Server Action
import { revalidateTag } from 'next/cache';
export async function addPost() {
await db.post.create(...);
revalidateTag('posts'); // Immediately purges all fetch calls tagged 'posts'
}revalidateTag purges matching fetch records instantly across the entire application.
revalidatePathpurges route-specific cached data.revalidateTagenables fine-grained multi-route cache purging.
Why is revalidateTag preferable over revalidatePath for purging cached data shared across multiple pages?
Q16: What are the four caching layers in Next.js App Router architecture?
Next.js implements four distinct caching mechanisms:
- Request Memoization: Deduplicates identical GET fetch requests within a single React render tree pass (In-memory).
- Data Cache: Persists data across user requests on the server (Disk/Memory).
- Full Route Cache: Persists rendered HTML and RSC payload on the server for static routes.
- Router Cache (Client-side): Stores RSC payloads in browser memory during active user sessions.
Request Memoization lasts for a single render cycle.
Data Cache persists data across requests until manually revalidated.
Which Next.js caching layer operates entirely inside browser client memory during active user navigation?
Q17: How do you opt out of caching for dynamic routes?
To force dynamic, real-time rendering on every request:
- Pass
{ cache: 'no-store' }or{ next: { revalidate: 0 } }tofetch(). - Export route segment configs:
export const dynamic = 'force-dynamic'. - Use dynamic functions like
cookies(),headers(), orsearchParams.
// app/live-feed/page.js
export const dynamic = 'force-dynamic'; // Bypasses Full Route Cache
export default async function LiveFeed() {
const data = await fetch('https://api.com/feed').then(r => r.json());
return <div>Live Items: {data.length}</div>;
}force-dynamic ensures the page renders on every incoming request on the server.
Calling
cookies()orheaders()automatically converts a static route to dynamic rendering.export const dynamic = 'force-dynamic'forces SSR across the entire page.
What happens to a static page route when you call cookies() or headers() inside its Server Component?
Q18: What is Next.js Middleware and where does it execute?
Middleware (middleware.js in root) runs before a request is completed, directly at the Edge network layer (before hitting cache or route handlers). Commonly used for authentication checks, URL redirects, header modifications, and bot detection.
// middleware.js
import { NextResponse } from 'next/server';
export function middleware(request) {
const token = request.cookies.get('token');
if (!token && request.nextUrl.pathname.startsWith('/dashboard')) {
return NextResponse.redirect(new URL('/login', request.url));
}
return NextResponse.next();
}
export const config = {
matcher: ['/dashboard/:path*'],
};Intercepts request routes to /dashboard, redirecting unauthenticated users to /login.
Executes at the Edge network layer before matching routes.
Uses config matcher arrays to target specific request paths.
Where does Next.js Middleware execute relative to route handlers and page rendering?
Q19: What are Route Handlers and how do they replace API Routes?
Route Handlers (route.js) replace legacy Pages Router API routes (/pages/api). Defined inside the /app directory, they export named functions matching HTTP methods: GET, POST, PUT, DELETE, PATCH.
// app/api/users/route.js
import { NextResponse } from 'next/server';
export async function GET() {
const users = [{ id: 1, name: 'Alice' }];
return NextResponse.json(users);
}
export async function POST(request) {
const body = await request.json();
return NextResponse.json({ status: 'Created', data: body }, { status: 201 });
}Maps REST API endpoints to GET and POST requests served from /api/users.
Created inside
/appdirectory usingroute.jsfiles.Export standard HTTP method functions (
export async function GET(request) {}).
Can a route.js file coexist inside the exact same folder directory as a page.js file?
Q20: How does the Metadata API manage SEO head tags in the App Router?
Next.js manages document <head> metadata by exporting static metadata objects or dynamic generateMetadata() functions from layout.js or page.js files. Next.js automatically deduplicates and hoists metadata tags into the final HTML output.
// app/products/[id]/page.js
export async function generateMetadata({ params }) {
const { id } = await params;
const product = await fetchProduct(id);
return {
title: product.title,
description: product.summary,
openGraph: { images: [product.image] },
};
}generateMetadata fetches product details dynamically to output customized meta tags.
Export static
metadataobject or dynamicgenerateMetadata({ params })function.Supports Open Graph cards, Twitter metadata, and canonical links natively.
Which function is exported from page.js to dynamically compute SEO page titles based on route parameters?
Q21: What is Streaming SSR and how do Suspense boundaries speed up TTFB?
Streaming SSR breaks HTML page rendering into progressive chunks. Instead of delaying the entire server response until slow database queries complete, Next.js streams the initial HTML shell immediately. Slower subtrees wrapped in <Suspense> stream into place as data completes.
import { Suspense } from 'react';
import SlowFeed from './SlowFeed';
export default function Page() {
return (
<main>
<h1>Fast Static Header</h1>
<Suspense fallback={<p>Loading feed...</p>}>
<SlowFeed /> {/* Streams in asynchronously when resolved */}
</Suspense>
</main>
);
}The page shell renders immediately; SlowFeed streams over HTTP as soon as data resolves.
Lowers Time to First Byte (TTFB) by sending HTML shell chunks immediately.
Wrapped via
loading.jsor explicit<Suspense fallback={<Skeleton />}>boundaries.
What primary performance metric is improved by using Streaming SSR with Suspense boundaries?
Q22: When should you use <Link> versus the useRouter Hook for navigation?
<Link href="...">: Primary navigation method. Automatically prefetches linked route JS and RSC payloads into viewport memory for instant transitions.useRouter()(next/navigation): Used for programmatic imperative navigation inside event handlers (e.g.,router.push('/dashboard')after form submission).
import Link from 'next/link';
import { useRouter } from 'next/navigation'; // App Router import!
export function NavComponent() {
const router = useRouter();
const handleAction = async () => {
await submitData();
router.push('/success'); // Imperative route change
};
return <Link href="/about">About</Link>; // Automatic prefetching
}Link pre-fetches targets automatically; useRouter handles programmatic route redirects.
Always prefer
<Link>for visual anchor links due to automatic viewport prefetching.Import
useRouterstrictly fromnext/navigationin the App Router (notnext/router).
Which import path must be used for the useRouter hook inside the App Router?
Q23: How does the server-only package safeguard private backend utility code?
Importing import 'server-only' into utility files guarantees that private code (API tokens, database credentials) is never accidentally imported into Client Components. If a Client Component imports a server-only file, Next.js throws a build-time error.
// lib/db-queries.js
import 'server-only'; // Guarantees this file cannot be bundled for client
export async function getSensitiveData() {
return db.query('SELECT * FROM secret_table');
}Importing server-only breaks builds instantly if client code attempts to import db-queries.js.
Protects sensitive server logic from leaking into client JavaScript bundles.
Throws explicit compilation errors during build time if boundary leaks occur.
What occurs during build time if a Client Component ('use client') imports a module containing import 'server-only'?
Q24: What is Next.js Draft Mode and how does it benefit Headless CMS integrations?
Draft Mode bypasses static page caching (SSG/ISR) to show preview content live from a Headless CMS (like Contentful or Sanity). Enabled via an API route calling draftMode().enable(), which sets a temporary cookie that forces routes to switch to dynamic SSR.
// app/api/draft/route.js
import { draftMode } from 'next/headers';
export async function GET(request) {
const draft = await draftMode();
draft.enable(); // Sets cookie forcing dynamic SSR preview
return new Response('Draft mode enabled');
}draft.enable() sets a preview cookie that instructs Next.js to render unpublished content dynamically.
Bypasses static page cache to render unpublished CMS drafts.
Uses secure browser cookies to enable live preview rendering.
How does Next.js signal to route pages that Draft Mode preview rendering is active?
Q25: How does next/dynamic perform code splitting and disable SSR for client libraries?
next/dynamic is an extension of React.lazy(). It lazy-loads heavy client-side libraries or components on demand. Setting { ssr: false } completely disables server-side pre-rendering for browser-only libraries (e.g., Chart.js or Leaflet maps).
import dynamic from 'next/dynamic';
// Loads Leaflet Map component on client side only
const MapComponent = dynamic(() => import('./MapComponent'), {
ssr: false,
loading: () => <p>Loading Map...</p>,
});
export default function Page() {
return <MapComponent />;
}ssr: false prevents Leaflet from executing on Node.js servers where window/document is undefined.
Splits heavy JS components into separate lazily loaded bundle chunks.
{ ssr: false }prevents server rendering failures for window-dependent client libraries.
Why should you pass { ssr: false } to next/dynamic when importing a canvas charting library?
Q26: What are Static Exports (output: 'export') and what features are disabled?
Configuring output: 'export' in next.config.js builds a pure static HTML/CSS/JS site that can be hosted on any static storage bucket (like AWS S3 or Nginx). However, Node.js server features like Server Actions, Middleware, Dynamic SSR routes, and Image Optimization are disabled.
// next.config.js
module.exports = {
output: 'export', // Generates 'out' folder containing static HTML/CSS/JS
images: { unoptimized: true }, // Disables Node.js image processing
};output: export produces static assets suitable for CDN or AWS S3 hosting.
Outputs static HTML assets for un-hosted web server deployments.
Disables Node.js runtime features (Server Actions, Middleware, SSR).
Which core Next.js feature CANNOT be used when next.config.js is set to output: 'export'?
Q27: What is the instrumentation.js file used for in Next.js?
The instrumentation.js file allows executing server initialization logic, performance monitoring setup, or observability tools (like OpenTelemetry, Sentry, or Datadog) as soon as the Next.js Node.js server starts up.
// instrumentation.js (Root directory)
export async function register() {
if (process.env.NEXT_RUNTIME === 'nodejs') {
await import('./telemetry-node');
}
}register() executes once when the Next.js server instance launches.
Executes global server startup logic inside
register()function.Integrates APM observability tools (OpenTelemetry, Sentry) early.
Inside which exported function within instrumentation.js do you place server startup monitoring setup?
Q28: How does Request Memoization work across React Server Component trees?
React automatically extends native fetch() to deduplicate identical GET requests made across different components within the same render tree cycle. If 5 components call fetch('https://api.com/user'), Next.js executes the network call only once and shares the response.
// Component A & Component B both execute this simultaneously during render:
const user = await fetch('https://api.com/user').then(r => r.json());
// Request Memoization executes the HTTP call ONCE and shares the promise!Components fetch data independently without triggering duplicate network calls.
Deduplicates identical GET fetch requests within a single server render pass.
Eliminates the need to fetch data at root layouts and drill props down to children.
If three separate Server Components in the same render tree execute fetch('https://api.com/settings'), how many network calls are made to the external API?
Q30: What is Partial Pre-rendering (PPR) in Next.js?
Partial Pre-rendering (PPR) combines static pre-rendering and dynamic streaming in a single HTTP response. The static HTML shell (headers, layout) is served instantly from cache, while dynamic holes wrapped in <Suspense> stream in parallel over the same connection.
Merges SSG speed with SSR dynamic streaming within a single page response.
Uses React Suspense boundaries to define dynamic holes inside static shells.
How does Partial Pre-rendering (PPR) handle static and dynamic content on a single page?