Navigation

GyaanSetu Educational Platform

Top 20 Next.js Interview Questions for 2026

Master the production framework for React: App Router, Server Components, SSR, and critical performance optimizations.

App RouterSSR & SSGMiddlewareServer Components
1

What is Next.js and why use it over plain React?

Next.js is a React framework that provides a Production-grade environment. Unlike plain React (a library), Next.js handles routing, rendering (SSR/SSG), API routes, and optimizations out of the box. Key benefits include improved SEO (due to pre-rendering), faster initial load times, automatic code splitting, and a built-in router. It bridges the gap between a client-side library and a full-stack web framework.

Next.js / TypeScript
1// Plain React Directory
2src/
3 App.js
4 index.js
5 components/
6
7// Next.js Directory (App Router)
8app/
9 page.tsx (Home route)
10 about/
11 page.tsx (About route)
12 api/
13 route.ts (API endpoint)
14 layout.tsx (Root layout)
2

Explain Pre-rendering (SSR vs SSG) in Next.js.

Next.js pre-renders every page, generating HTML in advance. **SSG (Static Site Generation):** HTML is generated at **build time**. Reused on each request. Best for performance and SEO (blogs, docs). **SSR (Server-Side Rendering):** HTML is generated on **each request**. Best for dynamic data that changes constantly (dashboards, personalized feeds).

Next.js / TypeScript
1// SSG (Pages Router)
2export async function getStaticProps() {
3 const data = await fetchData();
4 return { props: { data } };
5}
6
7// SSR (Pages Router)
8export async function getServerSideProps() {
9 const data = await fetchData();
10 return { props: { data } };
11}
3

What is ISR (Incremental Static Regeneration)?

ISR allows you to create or update static pages *after* the site has been built. You can use static generation on a per-page basis, without needing to rebuild the entire site. By setting a `revalidate` time, Next.js can regenerate the page in the background when a request comes in after that time has passed. This combines the performance of static sites with the freshness of dynamic ones.

Next.js / TypeScript
1export async function getStaticProps() {
2 const res = await fetch('https://api.example.com/posts');
3 const posts = await res.json();
4
5 return {
6 props: { posts },
7 // Next.js will attempt to re-generate the page:
8 // - When a request comes in
9 // - At most once every 10 seconds
10 revalidate: 10,
11 };
12}
4

How does Client-Side Navigation work in Next.js?

Next.js uses the `<Link>` component for client-side transitions between routes. When a user clicks a link, Next.js fetches the JSON data for the new page and updates the DOM without a full browser refresh. Additionally, Next.js automatically **prefetches** code for linked pages in the background when they come into the viewport (in production), making navigation almost instant.

Next.js / TypeScript
1import Link from 'next/link';
2
3function Navbar() {
4 return (
5 <nav>
6 {/* Client-side transition */}
7 <Link href="/about">About Us</Link>
8
9 {/* Full refresh (avoid provided unless necessary) */}
10 <a href="/legacy">Legacy Page</a>
11 </nav>
12 );
13}
5

Explain Dynamic Routing in Next.js.

Dynamic routes allow you to create pages with dynamic URLs based on file names. A file name wrapped in brackets `[param]` creates a dynamic route. For example, `pages/posts/[id].js` will match `/posts/1`, `/posts/abc`, etc. The matched path parameter is accessible via the router query object (Pages Router) or `params` prop (App Router).

Next.js / TypeScript
1// app/blog/[slug]/page.tsx
2
3export default function Page({ params }: { params: { slug: string } }) {
4 return <div>My Post: {params.slug}</div>
5}
6
7// URL: /blog/nextjs-tips -> Renders: My Post: nextjs-tips
6

What is `getStaticPaths`?

When using dynamic routes (`[id].js`) with `getStaticProps` (SSG), Next.js needs to know exactly which paths to pre-render at build time. `getStaticPaths` returns a list of paths (e.g., specific IDs) that should be generated. It also defines a `fallback` behavior (true, false, or 'blocking') for handling paths not generated at build time.

Next.js / TypeScript
1export async function getStaticPaths() {
2 return {
3 paths: [
4 { params: { id: '1' } },
5 { params: { id: '2' } }
6 ],
7 fallback: 'blocking' // or false, true
8 };
9}
7

How do you handle API routes in Next.js?

Next.js allows you to build a public API within the same application. In the Pages Router, files in `pages/api/*` are treated as API endpoints (Serverless Functions). In the App Router, you define `route.ts` files inside route directories. They handle standard HTTP methods (GET, POST, etc.) and run on the server, keeping DB credentials secure.

Next.js / TypeScript
1// app/api/hello/route.ts
2
3import { NextResponse } from 'next/server';
4
5export async function GET() {
6 return NextResponse.json({ message: 'Hello from Next.js API' });
7}
8
9export async function POST(request: Request) {
10 const body = await request.json();
11 return NextResponse.json({ received: body });
12}
8

Explain the Image Component (`next/image`).

The Next.js Image component extends the HTML `<img>` element with modern web optimization features. It automatically resizes images based on device screen size, supports modern formats like WebP/AVIF, enables lazy loading by default (improving LCP), and prevents Cumulative Layout Shift (CLS) by requiring dimensions. It can optimize both local and remote images.

Next.js / TypeScript
1import Image from 'next/image';
2import myPic from './profile.png';
3
4function Profile() {
5 return (
6 <>
7 {/* Local Image (width/height auto-detected) */}
8 <Image src={myPic} alt="Profile" placeholder="blur" />
9
10 {/* Remote Image (must define dimensions) */}
11 <Image
12 src="https://example.com/hero.jpg"
13 alt="Hero"
14 width={500}
15 height={300}
16 />
17 </>
18 );
19}
9

What is the `layout.tsx` (or `_app.js`) file?

In the App Router, `layout.tsx` defines UI that is shared between multiple routes. Preserves state, remains interactive, and does not re-render on navigation. The Root Layout (`app/layout.tsx`) is required and wraps all pages (including `<html>` and `<body>`). In the Pages Router, `_app.js` is used to initialize pages, persist layouts, and keep global state.

Next.js / TypeScript
1// app/layout.tsx
2export default function RootLayout({
3 children,
4}: {
5 children: React.ReactNode
6}) {
7 return (
8 <html lang="en">
9 <body>
10 <Navbar />
11 {children}
12 <Footer />
13 </body>
14 </html>
15 )
16}
10

What is middleware in Next.js?

Middleware allows you to run code *before* a request is completed. Based on the incoming request, you can rewrite, redirect, modify the request/response headers, or respond directly. It runs on the Edge Runtime (lighter than Node.js) and is commonly used for authentication, geolocation-based redirects, and A/B testing.

Next.js / TypeScript
1// middleware.ts
2import { NextResponse } from 'next/server'
3import type { NextRequest } from 'next/server'
4
5export function middleware(request: NextRequest) {
6 // Redirect if not authenticated
7 if (!request.cookies.has('token')) {
8 return NextResponse.redirect(new URL('/login', request.url))
9 }
10}
11
12export const config = {
13 matcher: '/dashboard/:path*',
14}
11

Difference between App Router and Pages Router.

**Pages Router**: Uses file-system based routing in `pages/` directory. Relies on `_app`, `_document`, and `getStaticProps`/`getServerSideProps`. **App Router**: New paradigm in `app/` directory. Uses React Server Components (RSC) by default. Features nested layouts (`layout.tsx`), optimized data fetching (async components), and built-in SEO support (`metadata`). It supports streaming and is the recommended way to build new Next.js apps.

Next.js / TypeScript
1// Pages Router Data Fetching
2export async function getServerSideProps() { ... }
3
4// App Router Data Fetching
5// (Directly in component)
6export default async function Page() {
7 const data = await fetchData();
8 return <div>{data.title}</div>
9}
12

What are Server Components in Next.js?

Server Components allow you to render components strictly on the server. They have zero impact on the client-side bundle size (JS sent to browser) and can access server resources (database, filesystem) directly. In the App Router, all components are Server Components by default. You opt-in to Client Components (interactive elements with hooks/state) using the `'use client'` directive.

Next.js / TypeScript
1// defaults to Server Component
2import { db } from './database';
3
4export default async function Page() {
5 const users = await db.query('SELECT * FROM users');
6
7 return (
8 <ul>
9 {users.map(user => <li key={user.id}>{user.name}</li>)}
10 </ul>
11 );
12}
13

How to handle SEO in Next.js?

Next.js is built for SEO compared to plain React SPA. **App Router:** Export a `metadata` object or `generateMetadata` function from a `layout.tsx` or `page.tsx` file to define title, description, and open graph tags. **Pages Router:** Use the `<Head>` component to inject tags into the document head.

Next.js / TypeScript
1// app/page.tsx (App Router)
2import type { Metadata } from 'next';
3
4export const metadata: Metadata = {
5 title: 'Home Page',
6 description: 'Welcome to my site',
7 openGraph: {
8 images: ['/og-image.png'],
9 },
10};
11
12export default function Page() { ... }
14

What is `next.config.js`?

`next.config.js` is a standard configuration file used to customize Next.js behavior. You can configure redirects, rewrites, custom webpack configs, environment variables, image domains (for `next/image`), and internationalized routing (i18n). It runs only on the server during the build process.

Next.js / TypeScript
1/** @type {import('next').NextConfig} */
2const nextConfig = {
3 reactStrictMode: true,
4 images: {
5 domains: ['example.com'], // Allow external images
6 },
7 async redirects() {
8 return [
9 {
10 source: '/old-blog/:slug',
11 destination: '/news/:slug',
12 permanent: true,
13 },
14 ]
15 },
16}
17
18module.exports = nextConfig
15

How to handle CSS in Next.js (Global vs Modules)?

**Global CSS:** Import a standard `.css` file in the root `layout.tsx` (App Router) or `_app.js` (Pages Router). Applies to the whole app. **CSS Modules:** Files named `*.module.css`. They scope classes locally by generating unique class names (e.g., `btn_123xyz`). Import them into specific components. Avoids naming conflicts.

Next.js / TypeScript
1/* styles/Button.module.css */
2.error {
3 color: red;
4}
5
6// Button.tsx
7import styles from './Button.module.css';
8
9export function Button() {
10 // Compiles to specific class string
11 return <button className={styles.error}>Error</button>;
12}
16

What is Fast Refresh?

Fast Refresh is a Next.js feature that gives you instantaneous feedback on edits made to your React components. When you modify a file, Next.js only re-renders that component, preserving its state (e.g., text in an input field or a counter value) without reloading the entire page. If you make a syntax error, it displays an overlay; effectively fixing it cleans the overlay automatically.

Next.js / TypeScript
1// Try changing "Count" text or logic
2// The state (count) will NOT reset to 0
3function Counter() {
4 const [count, setCount] = useState(0);
5 return <button onClick={() => setCount(c => c+1)}>{count}</button>
6}
17

How does Font Optimization work (`next/font`)?

`next/font` automatically optimizes your fonts (including custom fonts and Google Fonts) and removes external network requests for improved privacy and performance. Fonts are downloaded at build time and self-hosted with the other static assets. It also uses CSS size-adjust to prevent Layout Shift (CLS) while fonts are loading.

Next.js / TypeScript
1// app/layout.tsx
2import { Inter } from 'next/font/google';
3
4// Configures subset and variable font
5const inter = Inter({ subsets: ['latin'] });
6
7export default function RootLayout({ children }) {
8 return (
9 <html lang="en">
10 <body className={inter.className}>{children}</body>
11 </html>
12 );
13}
18

Script Optimization (`next/script`).

Standard `<script>` tags block rendering. The `next/script` component allows you to load third-party scripts (analytics, ads) efficiently. You can set the loading strategy: `beforeInteractive` (critical), `afterInteractive` (default, after hydration), `lazyOnload` (idle time), or `worker` (web worker).

Next.js / TypeScript
1import Script from 'next/script';
2
3export default function Layout() {
4 return (
5 <>
6 <Script
7 src="https://www.google-analytics.com/analytics.js"
8 strategy="lazyOnload"
9 />
10 </>
11 )
12}
19

How to handle 404 and 500 errors?

In App Router, create a `not-found.tsx` file for 404 errors (triggers when `notFound()` is called or route doesn't exist). Create an `error.tsx` file to handle runtime errors (must be a Client Component). It receives `error` and `reset` props. In Pages Router, create `pages/404.js` and `pages/500.js`.

Next.js / TypeScript
1// app/not-found.tsx
2import Link from 'next/link';
3
4export default function NotFound() {
5 return (
6 <div>
7 <h2>Not Found</h2>
8 <Link href="/">Return Home</Link>
9 </div>
10 );
11}
20

What are Route Handlers?

Route Handlers (introduced in App Router) allow you to create custom Request Handlers for a given route using the Web Request and Response APIs. They are defined in a `route.ts` (or `route.js`) file inside the `app` directory. They are the equivalent of API Routes in the Pages directory but run on standard Web APIs.

Next.js / TypeScript
1// app/items/route.ts
2export async function GET(request: Request) {
3 const { searchParams } = new URL(request.url);
4 const id = searchParams.get('id');
5 const res = await fetch(`https://data.mongodb.com/items/${id}`);
6 const data = await res.json();
7
8 return Response.json({ data });
9}

Ready to Build Full-Stack Apps?

Combine these Next.js skills with our React and TypeScript resources to become a complete frontend engineer.

Explore More Topics

© 2026 GyaanSetu. Helping developers ace their interviews.