Next.js Interview Questions and Answers

Routing, rendering modes, data fetching and deployment on Next.js.

Practise 10 random 151 peer-reviewed questions
Next.js Interview Syllabus & Preparation Strategy

Whether you are preparing for entry-level Next.js interview questions for freshers or senior software engineer interview questions addressing concurrency, scalability, and system architecture, this track provides peer-reviewed model answers with syntax walkthroughs, edge cases, and practical interview tips.

1 Explain SSR, SSG, ISR and CSR in Next.js. Medium

These describe when HTML is produced. CSR ships a minimal shell plus a JS bundle; the browser fetches data and renders, so first paint is slower and SEO weaker, but navigation feels app-like. SSR generates HTML on each request, giving fresh crawlable content at the cost of server work and higher time to first byte. SSG renders at build time and serves the same HTML from a CDN, which is fastest and cheapest but only suits content that rarely changes. ISR is static generation with revalidation: pages are served statically and regenerated in the background after revalidate seconds, combining speed with freshness.

const res = await fetch(url, { next: { revalidate: 60 } });

Use SSR for personalised or real-time pages, SSG and ISR for blogs and marketing, and CSR for dashboards behind auth. In the App Router, per-route segment config such as dynamic and revalidate selects the mode.

2 What are the main differences between the App Router and the Pages Router? Medium

The Pages Router uses files under pages/. Each file exports a default component, data comes from getStaticProps, getServerSideProps or getStaticPaths, and _app and _document customise the shell.

The App Router uses folders under app/ with page.tsx, layout.tsx, loading.tsx and error.tsx, and is built on React Server Components. Key differences: nested layouts preserve state across navigation, fetching happens directly in async server components with automatic request memoisation, streaming with Suspense is first-class, and client components are opt-in with "use client". Route handlers replace API routes.

The App Router is the recommended default for new projects; the Pages Router remains supported and many existing apps use it. You can run both in one project during migration, but a page and an App Router route cannot share the same path. Choose the App Router for new work unless a dependency still assumes the Pages conventions.

3 What is the difference between Server Components and Client Components? Medium

In the App Router components are Server Components by default. They run only on the server, can be async, can read databases or secrets directly, and send no JavaScript to the browser beyond the rendered output. They cannot use state, effects, browser APIs or event handlers.

Client Components are opted in with "use client" at the top of a file. They run on the server for the initial HTML and then hydrate in the browser, so they can use useState, useEffect, refs and event handlers. A "use client" boundary marks the module and everything it imports as client code, so keep boundaries low in the tree to minimise the bundle.

Server Components can render Client Components and pass serialisable props. Client Components cannot import Server Components, but they can receive them as children. Practically, fetch data in server components and keep interactive leaves client-side, passing only the data they need.

4 How does data fetching and caching work in the App Router? Medium

You fetch inside async Server Components using the extended fetch:

const res = await fetch('https://api.example.com/posts', {
  next: { revalidate: 60, tags: ['posts'] },
});

By default fetch is cached and deduplicated for the lifetime of a request; cache: 'no-store' opts out, and next.revalidate sets an ISR window. revalidatePath('/posts') and revalidateTag('posts') purge caches on demand, typically from a Server Action or route handler after a mutation.

Because components render on the server, data loading is colocated and can be parallelised; wrap slow parts in Suspense to stream. Avoid the old client-side useEffect pattern unless data must be live and user-specific. generateStaticParams pre-renders dynamic routes at build time.

Each route segment can tune caching with export const dynamic = 'force-dynamic' or export const revalidate. Getting these settings right is the main source of stale-data bugs.

5 How do dynamic routes and generateStaticParams work? Medium

Dynamic segments use bracket folders: app/blog/[slug]/page.tsx receives params as a prop, which is a Promise in recent versions. Catch-all routes use [...slug] and optional catch-all uses [[...slug]].

generateStaticParams runs at build time and returns an array of param objects so those pages are pre-rendered:

export async function generateStaticParams() {
  const posts = await getPosts();
  return posts.map(p => ({ slug: p.slug }));
}
export const dynamicParams = true;

With dynamicParams true, pages not returned at build time are generated on first request and cached; setting it false returns 404 for unknown params. Combined with ISR, the generated pages can revalidate over time. generateMetadata({ params }) gives per-page SEO using the same params.

The older Pages Router equivalent was getStaticPaths with getStaticProps. The App Router model is more flexible because params flow naturally into server components and streaming.

6 What is Next.js middleware and when should you use it? Medium

Middleware in middleware.ts at the project root runs before a request is completed, on the Edge runtime, and can rewrite, redirect, set headers or return a response directly. It is matched with a matcher config or conditional logic.

export function middleware(req: NextRequest) {
  if (!req.cookies.get('token')) {
    return NextResponse.redirect(new URL('/login', req.url));
  }
}
export const config = { matcher: ['/dashboard/:path*'] };

Common uses are auth gating, A/B testing via rewrites, locale detection, bot filtering and security headers. Constraints: it runs on every matched request, so keep it fast and avoid large dependencies. It cannot use Node APIs or query a database directly on the Edge runtime, and it is not a substitute for authorising data access inside routes.

Because middleware runs before caching, rewrites can change which cached page is served. Use it for coarse redirects and header logic, not data fetching.

7 What is the purpose of the `pages or app` directory in Next.js? Medium

The pages and app directories in Next.js represent the routing and layout backbone of the application. Next.js uses file-system based routing, meaning your filesystem structure directly maps to public URL paths:

### 1. The Modern app/ Directory (App Router):
Introduced in Next.js 13+, built entirely on React Server Components:

  • Folder-based: Every folder represents a route segment (e.g. app/blog/page.tsx -> /blog).
  • Special Filenames:
  • page.tsx: The leaf UI unique to that route.
  • layout.tsx: Shared UI that wraps child pages and preserves state across navigations.
  • loading.tsx: Instant loading skeleton wrapped in React Suspense.
  • error.tsx: React Error Boundary for isolated error recovery.
  • route.ts: API endpoint handler (GET, POST, etc.).

### 2. The Legacy pages/ Directory (Pages Router):

  • Every file exported as default React component in pages/ maps directly to a URL route (pages/about.js -> /about).
  • Relies on lifecycle data-fetching methods: getStaticProps, getServerSideProps, and getStaticPaths.
8 What is file based routing in Next.js? Medium

File-based routing is an architectural pattern where application URL routes are inferred automatically from the folder and file hierarchy on the filesystem, eliminating the need to maintain an imperative routing registry (like react-router-dom route tables).

### How It Works in Practice:

  • Static Routes: app/contact/page.tsx maps to /contact.
  • Dynamic Segment Routes: Folders wrapped in square brackets match dynamic variables:

app/products/[id]/page.tsx matches /products/123 or /products/shoes.

  • Catch-All Segments: app/docs/[...slug]/page.tsx matches /docs/setup/install/macos.
  • Route Groups: Folders surrounded by parentheses app/(marketing)/about/page.tsx organize code without appearing in the URL path (/about).
  • Parallel Routes & Intercepting Routes: Slots like @modal and (..)photo/[id] enable complex UI patterns like modal overlays with sharable URLs.

### Advantages:
Reduces configuration errors, makes codebase navigation intuitive for teams, and enables automatic code-splitting per route.

9 What are the key features of Next.js? Medium
  • Server Side Rendering (SSR): Next.js allows rendering React components on the server before sending them to the client, improving performance and SEO.
  • Static Site Generation (SSG): It pre-renders pages at build time, useful for blogs or e-commerce sites.
  • API Routes: You can build a backend using API routes in the same codebase without needing an external server.
  • File Based Routing: Next.js automatically creates routes based on the file structure inside the pages directory.
  • Client Side Rendering (CSR): Like React, Next.js also supports traditional client-side rendering.
  • Incremental Side Rendering:
  • Image Optimization: Built-in image optimization capabilities that reduce image sizes and enhance loading times.
  • Automatic Code Splitting: Next.js splits the code into smaller bundles, which are loaded only when required, improving performance.
  • TypeScript Support: Native support for TypeScript, enabling strict typing and better developer experience.
  • Incremental Static Regeneration (ISR): Pages can be statically generated at runtime and updated incrementally.
  • Fast Refresh: Provides an instant feedback loop while coding, similar to React's hot reloading.
10 What are the differences between Next.js and React.js? Medium

| Feature | Next.js | React.js |
| ------------------ | --------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------ |
| Rendering | Supports Server-Side Rendering (SSR), Static Site Generation (SSG), and Client-Side Rendering (CSR). | Only supports Client-Side Rendering (CSR) by default. |
| Routing | Built-in file-based routing system. Automatically generates routes based on the folder structure. | No built-in routing. Requires libraries like React Router. |
| SEO | Excellent for SEO as it supports SSR and SSG, allowing pre-rendered content to be indexed by search engines. | Limited SEO capabilities due to client-side rendering. Additional work is needed for SEO optimization. |
| Performance | Faster initial page load due to SSR, automatic code splitting, and static generation. | May have slower page loads for large apps since everything is rendered on the client. |
| Configuration | Minimal configuration required. Comes with SSR, SSG, and routing out of the box. | Requires manual setup for SSR, routing, and other advanced features. |
| Learning Curve | Slightly steeper due to built-in advanced features like SSR, SSG, and API routes. | Easier to learn initially, but requires additional tools for SSR and routing. |
| API Routes | Built-in API routes that can handle backend logic within the same project. | No support for API routes; requires external tools for backend development. |
| Code Splitting | Automatically splits code into smaller bundles, loading only what's needed for a specific page. | Requires manual code splitting or use of lazy loading to optimize performance. |
| Deployment | Optimized for easy deployment on platforms like Vercel (creators of Next.js) and supports serverless functions. | Deployment typically requires additional configuration for optimized hosting and SSR. |
| Image Optimization | Has a built-in Image component for automatic image resizing and optimization. | Does not provide image optimization; developers need third-party libraries for that. |

11 What is the difference between client-side and server-side rendering in Next.js? Medium

Client-side rendering (CSR) means that the browser fetches the JavaScript and renders the page on the client side, while server-side rendering (SSR) means that the server generates the HTML and sends it to the client.

12 What is the `metadata` export in the App Router and how do you use it? Medium

The App Router supports a metadata export (or metadata.js/ts) to define route-level metadata like title, description, open graph tags and robots. You can export a static object or an async function that returns metadata.

// app/blog/[slug]/page.js
export const metadata = {
  title: "Blog Post",
  description: "A useful blog post",
};

export default function PostPage() {
  /* ... */
}
13 What is `generateStaticParams` and when should you use it? Medium

generateStaticParams is used in the App Router to statically generate dynamic routes at build time (SSG). Return an array of param objects for routes like [slug] so Next.js can pre-render those pages.

// app/blog/[slug]/page.js
export async function generateStaticParams() {
  const posts = await fetch("https://api.example.com/posts").then((r) =>
    r.json()
  );
  return posts.map((p) => ({ slug: p.slug }));
}
14 How do fetch cache options work in the App Router? Medium

The fetch API in server components supports caching controls via { next: { revalidate } } and cache modes like cache: 'no-store' or cache: 'force-cache'. Use no-store for always-fresh data and force-cache to reuse cached responses.

const res = await fetch("https://api.example.com/data", {
  cache: "no-store",
});
// or
const res2 = await fetch("/api/data", { next: { revalidate: 60 } });
15 What does the `dynamic` export do in the App Router? Medium

Exporting dynamic controls how a route is rendered: 'force-dynamic', 'force-static', or 'auto'. Use it to override Next.js detection — for example, force dynamic when you need per-request rendering.

// app/dashboard/page.js
export const dynamic = "force-dynamic";
16 How do you set head metadata per-route with `head.js` / `head.tsx`? Medium

In the App Router you can create a head.js or head.tsx file inside a route segment to return <head> elements (title, meta, link) for that segment. This is preferred for complex/head-only components.

// app/about/head.js
export default function Head() {
  return (
    <>
      <title>About Us</title>
      <meta name="description" content="About page" />
    </>
  );
}
17 What is the useRouter hook in Next.js? Medium

A hook that allows access to the router object and perform navigation. The useRouter hook allows you to programmatically change routes inside client components.

18 What is the difference between push and replace in useRouter? Medium

The push method adds a new entry to the browser's history stack, while replace replaces the current entry in the history stack.

const router = useRouter();

// Pushes a new route
router.push("/new-route");

// Replaces the current route
router.replace("/new-route");
19 How do you navigate programmatically in Next.js? Medium

Using useRouter() hook.

const router = useRouter();

function handleClick() {
  router.push(`/path`);
}

<button onClick={handleClick}>Go There</button>;
jsx
router.push(href: string, { scroll: boolean })
20 How do you enable TypeScript in a Next.js project? Medium

Next.js provides built-in, zero-configuration TypeScript support out of the box:

### 1. In a New Project:
Pass the --typescript flag when bootstrapping:

npx create-next-app@latest my-app --typescript

### 2. In an Existing JavaScript Project:

  1. Create an empty tsconfig.json in your project root:
   touch tsconfig.json
   
  1. Run the Next.js development server:
   npm run dev
   
  1. Next.js detects the tsconfig.json file and automatically prompts you to install the necessary type packages:
   npm install --save-dev typescript @types/react @types/node @types/react-dom
   
  1. Next.js automatically populates tsconfig.json with recommended production defaults and generates next-env.d.ts to ensure full Next.js type declarations.
Showing 20 of 151 questions

Frequently Asked Questions About Next.js Interviews

What do hiring managers evaluate in Next.js technical rounds?

Technical interviewers look for foundational fluency, idiomatic syntax, clarity when communicating complex logic, and awareness of performance trade-offs (e.g. memory footprint, render performance, and network latency) in production environments.

What are the best interview tips for practicing Next.js questions?

Use active recall: summarize each answer in your own words before revealing the model solution. Focus on explaining why a certain approach is chosen rather than just memorizing code syntax.