Next.js Interview Questions and Answers

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

Practise 10 random 21 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 What are Route Handlers and how do they differ from API Routes? Easy

Route Handlers live in app/api/.../route.ts and export HTTP-method functions such as GET, POST, PUT, DELETE and PATCH. They receive a standard Request and return a Response or NextResponse, support streaming, and can be cached or made dynamic with route segment config. They can run on the Node or Edge runtime via export const runtime = 'edge'.

export async function GET() {
  const data = await db.query();
  return Response.json(data);
}

API Routes live in pages/api/*.ts, export a single default handler using (req, res) with helpers like res.status().json(), and are the older Pages Router model. Route Handlers are the App Router equivalent and are recommended for new projects.

Both run only on the server, so secrets stay safe. Prefer Server Actions for form-driven mutations and use route handlers for public APIs, webhooks and third-party callbacks.

2 How do you handle metadata and SEO in the App Router? Easy

You export a static metadata object or a generateMetadata async function from a layout or page. It can set title, description, canonical URL, Open Graph, Twitter cards and robots directives.

export const metadata: Metadata = {
  title: 'Blog',
  description: 'Articles about web development',
  openGraph: { images: ['/og.png'] },
};

Metadata merges along the route hierarchy, so layouts set sensible defaults and pages override them. generateMetadata receives params and searchParams and can fetch data, and Next deduplicates those requests automatically.

next/font inlines and self-hosts fonts with no layout shift, and next/image provides responsive images, lazy loading and modern formats, which help Core Web Vitals and therefore SEO. Add sitemap.ts, robots.ts and structured JSON-LD for richer results.

Because the server renders your content, crawlers do not need to execute JavaScript. Always verify metadata renders in the built output, not just in dev mode.

3 What is Next.js? Easy

Next.js is an open-source React framework developed and maintained by Vercel that enables developers to build high-performance, full-stack web applications.

### Core Architectural Features:

  1. Hybrid Rendering Paradigms:
  • Server Components (RSC): Code executes exclusively on the server, streaming lightweight HTML to the client with zero bundle impact.
  • Static Site Generation (SSG): HTML pages pre-built at deployment time for lightning-fast CDN edge delivery.
  • Server-Side Rendering (SSR): Dynamic page generation on every incoming HTTP request.
  • Incremental Static Regeneration (ISR): Update static pages in the background without rebuilding the entire application.
  1. File-System Based Routing:

Intuitive directory-based routing (app directory with page.tsx and nested layout.tsx).

  1. Built-in Performance Optimizations:

Automatic image optimization (next/image), font optimization (next/font), script loading (next/script), and automatic route segment code splitting.

  1. Server Actions & Route Handlers:

Built-in full-stack backend capabilities to handle database mutations and REST/GraphQL API endpoints without configuring an external Express server.

4 How do you create a new Next.js project? Easy

The officially supported and recommended way to scaffold a new Next.js application is using create-next-app:

npx create-next-app@latest

### Interactive Setup Wizard Options:
Running this command prompts an interactive configuration CLI where you can select:

  • Project Name: e.g., my-next-app
  • TypeScript: Enables end-to-end static type checking (highly recommended for production).
  • ESLint: Configures code quality rules out of the box.
  • Tailwind CSS: Pre-configures Tailwind styling and PostCSS.
  • src/ directory: Keeps code organized inside src/ rather than project root.
  • App Router: Uses Next.js's modern routing architecture (recommended over legacy pages).
  • Import Alias: Configures @/* path mapping for clean imports.

### Non-Interactive One-Liner for Automated CI/CD:

npx create-next-app@latest my-app --typescript --tailwind --eslint --app --src-dir --import-alias "@/*"
5 What is the Link component in Next.js? Easy

A component for client side navigation between pages.

import Link from "next/link";

<Link href="/">Home</Link>
<Link href="/about">About</Link>
6 What is the default port for a Next.js app? Easy

By default, Next.js runs on port 3000 for both the development server (next dev) and production server (next start).

When you launch npm run dev, you can access the application at:
http://localhost:3000

### Automatic Port Fallback:
In modern versions of Next.js, if port 3000 is already occupied by another running application, Next.js will detect the conflict and automatically increment to port 3001 or prompt you to confirm switching to the next available port.

7 How to change default port for a Next.js app? Easy

You can change the port used by Next.js using several straightforward approaches:

### 1. In package.json Scripts (Recommended):
Pass the -p (or --port) flag in your scripts:

{
  "scripts": {
    "dev": "next dev -p 8080",
    "start": "next start -p 8080"
  }
}

### 2. Via Command Line Arguments:

npm run dev -- -p 5000
# or with npx directly
npx next dev -p 5000

### 3. Using the PORT Environment Variable:
Next.js respects the system PORT environment variable commonly used by cloud hosts (AWS, Heroku, DigitalOcean, Docker):

PORT=4000 npm run dev

Or define PORT=4000 inside your .env.local file.

8 What is Fast Refresh in Next.js? Easy

Fast Refresh is Next.js's hot module replacement (HMR) experience that provides near-instantaneous visual feedback when you edit React components in development.

### Key Capabilities:

  1. Preserves Component State:

If you edit a component that uses useState or useReducer, Fast Refresh updates only the modified code while keeping existing form inputs, scroll positions, and in-memory state intact.

  1. Instant Error Recovery:

If you make a syntax error or runtime exception, a detailed error overlay appears without crashing the development server. As soon as you fix the typo in your code editor, the overlay disappears and execution resumes seamlessly without a manual browser reload.

  1. Safe Fallback:

If you edit an export that is used outside React component boundaries (such as a shared constant), Fast Refresh safely performs a full page reload to guarantee runtime consistency.

9 How do you add global CSS in Next.js? Easy

Adding global CSS depends on whether you are using the modern App Router or the legacy Pages Router:

### 1. In App Router (app/ directory):
Import your global CSS file directly inside your root layout (app/layout.tsx):

// app/layout.tsx
import './globals.css';

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <body>{children}</body>
    </html>
  );
}

### 2. In Pages Router (pages/ directory):
Import global CSS only inside the custom pages/_app.js (or _app.tsx):

// pages/_app.tsx
import '../styles/globals.css';
import type { AppProps } from 'next/app';

export default function MyApp({ Component, pageProps }: AppProps) {
  return <Component {...pageProps} />;
}

*Note: In Pages Router, Next.js prohibits importing global stylesheets inside arbitrary page components to prevent global CSS rule ordering conflicts.*

10 How do you use Tailwind CSS in Next.js? Easy

By installing Tailwind CSS and configuring it in the next.config.js file.

npm install tailwindcss postcss autoprefixer
npx tailwindcss init -p

Then, add the following to your tailwind.config.js:

module.exports = {
  content: [
    "./pages/**/*.{js,ts,jsx,tsx}",
    "./components/**/*.{js,ts,jsx,tsx}",
  ],
  theme: {
    extend: {},
  },
  plugins: [],
};

And import Tailwind CSS in your \_app.js:

import "tailwindcss/tailwind.css";
11 What is the Image component in Next.js? Easy

A component that optimizes images for faster loading.

export default function Page() {
  return (
    <Image
      src={profilePic}
      alt="Picture of the author"
      // width={500} automatically provided
      // height={500} automatically provided
      // blurDataURL="data:..." automatically provided
      // placeholder="blur" // Optional blur-up while loading
    />
  );
}
12 How do you create API endpoints in Next.js? Easy

Next.js provides built-in serverless backend capabilities for creating REST or GraphQL endpoints:

### 1. In App Router (Route Handlers - Modern):
Create a route.ts (or route.js) inside any folder in the app directory. Export named HTTP verb functions (GET, POST, PUT, DELETE, PATCH):

// app/api/users/route.ts
import { NextResponse } from 'next/server';

export async function GET(request: Request) {
  const users = await db.user.findMany();
  return NextResponse.json(users);
}

export async function POST(request: Request) {
  const body = await request.json();
  const newUser = await db.user.create({ data: body });
  return NextResponse.json(newUser, { status: 201 });
}

### 2. In Pages Router (API Routes - Legacy):
Create files inside pages/api/ exporting a default handler:

// pages/api/users.js
export default async function handler(req, res) {
  if (req.method === 'GET') {
    res.status(200).json({ message: 'Success' });
  } else {
    res.status(405).end();
  }
}
13 What is the next/image component used for? Easy

The next/image component is an extension of the HTML <img> element engineered to automatically optimize images for Core Web Vitals:

### Automatic Optimizations Performed:

  1. Modern Format Conversion: Serves modern formats like AVIF and WebP if the user's browser supports them (saving 30-50% file size).
  2. Responsive Resizing: Generates a responsive srcset tailored to device viewports, preventing mobile devices from downloading desktop 4K images.
  3. Prevents Cumulative Layout Shift (CLS): Enforces explicit width/height or fill to reserve aspect ratio boxes in the layout before images finish downloading.
  4. Lazy Loading by Default: Offscreen images are loaded only as they approach the user's viewport.
  5. Priority Loading: The priority prop preloads Largest Contentful Paint (LCP) hero banners:
   <Image
     src="/images/hero.webp"
     alt="HireXTech Hero"
     width={1200}
     height={600}
     priority
   />
   
14 What is the next/link component used for? Easy

The next/link component (<Link>) is the primary way to perform client-side transitions between pages in Next.js applications:

### Why Use <Link> Instead of Standard <a href="...">?

  1. Client-Side Navigation: Standard <a> tags trigger a full browser document request, discarding application state and re-downloading stylesheets and scripts. <Link> intercepts the click and fetches only the required page chunk, updating the DOM instantaneously.
  2. Automatic Route Prefetching: When a <Link> enters the browser's viewport, Next.js automatically prefetches the destination route's code in the background, making page transitions feel instant when clicked.
  3. Preserves React State: Global layouts, audio players, or search filters stay mounted during transitions.

### Basic Syntax:

import Link from 'next/link';

<Link href="/categories/react" className="text-blue-600 hover:underline">
  Explore React Track
</Link>
15 How do you use placeholders with the next/image component? Easy

Use placeholder="blur" with a blurDataURL or let Next.js generate it when importing static images. This shows a low-quality blurred preview while the image loads.

import profilePic from "../public/profile.jpg";

<Image src={profilePic} alt="Profile" placeholder="blur" />;
16 How do you create a route in the Pages Router? Easy

In Next.js pages router, you create routes by adding files to the pages directory:

  • pages/index.js - the homepage (/)
  • pages/about.js - the about page (/about)
  • pages/blog/index.js - the blog index page (/blog)
  • pages/blog/[slug].js - dynamic blog posts (/blog/:slug)
17 How do you create a dynamic route in Next.js? Easy

In the pages directory, you can add bracket syntax to create dynamic routes:

 pages/posts/[id].js → /posts/1, /posts/2, etc.
 pages/[username]/settings.js → /foo/settings, /bar/settings, etc.
 pages/post/[...all].js → /post/2020/id/title, etc.

18 How do you create a 404 page in Next.js? Easy

Creating a customized 404 Not Found page is straightforward in both Next.js routers:

### 1. In App Router (app/ directory):
Create app/not-found.tsx:

// app/not-found.tsx
import Link from 'next/link';

export default function NotFound() {
  return (
    <div className="flex flex-col items-center justify-center min-h-[60vh]">
      <h1 className="text-4xl font-bold">404 - Question Not Found</h1>
      <p className="mt-2 text-gray-600">The requested interview question does not exist.</p>
      <Link href="/" className="mt-4 px-4 py-2 bg-blue-600 text-white rounded">
        Return Home
      </Link>
    </div>
  );
}

You can also trigger this page programmatically in any Server Component by calling notFound().

### 2. In Pages Router (pages/ directory):
Create pages/404.tsx:
Export a default React component. Next.js statically generates this page at build time for instant loading.

19 How do you create a route in the App Router? Easy

In the App Router, you create routes by adding files to the app directory. Each file corresponds to a route, and you can create nested routes by creating subdirectories.

app/
├── page.js          // Home page
├── about/
│   └── page.js      // About page
└── blog/
    ├── page.js      // Blog index page
    └── [slug]/
        └── page.js  // Dynamic blog post page
20 How do you create a dynamic route with app router in Next.js? Easy

In the App Router, you create dynamic routes by using square brackets in the file name. For example, to create a dynamic blog post route, you would create a file named [slug]/page.js inside the blog directory.

app/
└── blog/
    └── [slug]/
        └── page.js  // Dynamic blog post page
Showing 20 of 21 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.