1. What is getStaticProps?

Definition

getStaticProps is a Next.js function used to fetch data at build time and generate static HTML.

How It Works

  • Runs during build
  • Fetches data once
  • Generates static page
  • Served via CDN

Example

export async function getStaticProps() {
const data = await fetch('https://api.example.com').then(res => res.json())

return {
props: { data }
}
}

Use Cases

  • Blogs
  • Documentation
  • Marketing pages

Benefits

  • Very fast performance
  • SEO-friendly
  • Low server load

2. What is getServerSideProps?

Definition

getServerSideProps fetches data on every request at the server.

How It Works

  • Runs on each request
  • Fetches fresh data
  • Generates HTML dynamically

Example

export async function getServerSideProps() {
const data = await fetch('https://api.example.com').then(res => res.json())

return {
props: { data }
}
}

Use Cases

  • Dashboards
  • User-specific content
  • Real-time data

Drawbacks

  • Slower than static generation
  • Higher server cost

3. Difference between getStaticProps and getServerSideProps?

Comparison

FeaturegetStaticPropsgetServerSideProps
Execution TimeBuild timeRequest time
PerformanceVery fastSlower
Data FreshnessStaticAlways fresh
SEOExcellentExcellent
Server LoadLowHigh

Key Insight

  • getStaticProps = performance-first
  • getServerSideProps = freshness-first

4. What is getStaticPaths?

Definition

getStaticPaths is used with dynamic routes to define which paths should be pre-rendered at build time.

Example

export async function getStaticPaths() {
return {
paths: [
{ params: { id: '1' } },
{ params: { id: '2' } }
],
fallback: false
}
}

How It Works

  • Generates pages for given paths
  • Used with [id].js dynamic routes

Use Case

  • Blog posts
  • Product pages

5. What is fallback in getStaticPaths?

Definition

fallback controls what happens when a path is not pre-rendered at build time.

Options

1. false

  • Only defined paths are valid
  • Others → 404

2. true

  • Page generated on first request
  • Shows loading state

3. blocking

  • Page generated on request
  • No loading state (waits for HTML)

Interview Insight

  • blocking is preferred for SEO
  • true is useful for UX with loading states

6. When should you use SSG vs SSR?

Decision Table

ScenarioUse
Static contentSSG
Frequently changing dataSSR
SEO criticalBoth
User-specific dataSSR

Explanation

  • Use SSG when data rarely changes
  • Use SSR when data must always be fresh

Rule of Thumb

If you can pre-build → use SSG
If you need real-time → use SSR


7. How does ISR (Incremental Static Regeneration) work?

Definition

ISR allows static pages to be updated after deployment without rebuilding the entire site.

Core Idea

Static + Revalidation

Example

export async function getStaticProps() {
return {
props: { data: "Updated Data" },
revalidate: 10
}
}

Flow

  1. Page built at build time
  2. User requests page
  3. After revalidate time:
    • Next request triggers regeneration
    • Old page served
    • New page generated in background

Benefit

Combines performance of SSG with freshness of SSR.


8. How does caching work in Next.js?

Types of Caching

1. Static Cache

  • SSG pages cached at CDN
  • Served instantly

2. ISR Cache

  • Cached pages updated after revalidation

3. Server Cache

  • SSR responses can be cached using headers

4. Browser Cache

  • Controlled via HTTP headers

Key Insight

Next.js uses multi-layer caching:

  • CDN
  • Server
  • Browser

Example

res.setHeader('Cache-Control', 's-maxage=10')

9. How do you decide between CSR, SSR, SSG, ISR?

Comparison Table

StrategyWhen to Use
CSRUser-only data, no SEO
SSRReal-time, dynamic data
SSGStatic, rarely changing
ISRMostly static but needs updates

Decision Flow

  1. Is SEO needed?
    • Yes → SSR/SSG/ISR
  2. Is data dynamic?
    • Yes → SSR
  3. Can data be pre-built?
    • Yes → SSG
  4. Needs periodic updates?
    • Yes → ISR

Interview Insight

This decision is a key system design question.


10. How does hydration work?

Definition

Hydration is the process where React attaches event listeners to pre-rendered HTML on the client.

Flow

  1. Server sends HTML
  2. Browser displays content
  3. React loads JavaScript
  4. React "hydrates" the page

Example

  • SSR page loads → static HTML visible
  • React attaches interactivity

Key Concept

HTML → Static
Hydration → Interactive

Why It Matters

  • Faster perceived performance
  • Combines SSR + CSR benefits

Problem (Hydration Mismatch)

Occurs when server and client HTML differ.


Final Summary (Interview Tip)

  • getStaticProps → build-time (fast)

11. What is streaming in Next.js?

Definition

Streaming is a rendering technique where HTML is sent to the browser in chunks, instead of waiting for the entire page to be ready.

How It Works

  • Server starts rendering
  • Sends partial HTML immediately
  • Remaining content streams as it becomes ready

Example Concept

  • Header loads first
  • Data-heavy section loads later

Benefits

  • Faster perceived performance
  • Better user experience
  • Reduces time-to-first-byte (TTFB) impact

Interview Insight

Streaming is powered by React Server Components + Suspense in the App Router.


12. How does client-side navigation work?

Definition

Client-side navigation allows moving between pages without full page reload.

How It Works

  1. User clicks a link (next/link)
  2. Next.js intercepts request
  3. Fetches required JS/data
  4. Updates UI without reload

Key Components

  • next/link
  • useRouter

Benefits

  • Faster navigation
  • Preserves application state
  • Smooth user experience

13. What is prefetching?

Definition

Prefetching is the process of loading resources in advance before the user navigates.

How Next.js Handles It

  • Automatically prefetches links in viewport
  • Uses idle time to fetch page data

Example

<Link href="/about">About</Link>

Next.js preloads /about page in background.

Benefits

  • Instant navigation
  • Reduced latency

Interview Insight

Prefetching is enabled by default in production.


14. How does Next.js optimize routing?

Techniques Used

1. File-Based Routing

  • No runtime route configuration

2. Code Splitting

  • Loads only required page code

3. Prefetching

  • Preloads future routes

4. Dynamic Imports

  • Lazy loads components

5. Caching

  • Reuses previously loaded pages

Result

Efficient, fast, and scalable routing system.


15. What is App Router?

Definition

App Router is the modern routing system introduced in Next.js 13+, located in the /app directory.

Key Features

  • React Server Components by default
  • Nested layouts
  • Streaming and Suspense
  • Improved data fetching

Structure Example

app/
├── page.js
├── layout.js
└── dashboard/
└── page.js

Advantage

More scalable and performant than the Pages Router.


16. Difference between App Router and Pages Router?

Comparison

FeatureApp RouterPages Router
Directory/app/pages
RenderingServer ComponentsClient Components
LayoutsNested layoutsManual
Data FetchingNew APIsgetStaticProps, etc.
StreamingSupportedNot supported

Key Insight

  • App Router = Modern, flexible
  • Pages Router = Traditional, simpler

17. What are layouts?

Definition

Layouts are shared UI structures that wrap multiple pages.

Example

// app/layout.js
export default function Layout({ children }) {
return (
<div>
<header>Header</header>
{children}
</div>
)
}

Features

  • Persistent across routes
  • Do not re-render unnecessarily
  • Can be nested

Use Cases

  • Navbar
  • Sidebar
  • Footer

18. What are templates?

Definition

Templates are similar to layouts but re-render on every navigation.

Example

// app/template.js
export default function Template({ children }) {
return <div>{children}</div>
}

Key Behavior

  • Re-created on route change
  • Does not preserve state

Use Case

  • Animations
  • Page transitions

19. Difference between layout and template?

Comparison

FeatureLayoutTemplate
Re-renderNoYes
State PreservationYesNo
PerformanceBetterSlightly lower
Use CaseShared UITransitions

Explanation

  • Layout = persistent structure
  • Template = dynamic wrapper

20. What is loading.js?

Definition

loading.js is used to define a loading UI for a route segment.

Example

// app/loading.js
export default function Loading() {
return <p>Loading...</p>
}

How It Works

  • Automatically shown during:
    • Data fetching
    • Streaming

Benefits

  • Improves UX
  • Works with Suspense
  • No manual loading state needed

Interview Insight

It is part of the App Router’s built-in loading mechanism.


21. What is error.js?

Definition

error.js is a special file in the App Router used to handle runtime errors in a specific route segment.

How It Works

  • Placed inside a route folder
  • Automatically catches errors in that segment
  • Acts like a React Error Boundary

Example

'use client'

export default function Error({ error, reset }) {
return (
<div>
<h2>Something went wrong</h2>
<button onClick={() => reset()}>Try again</button>
</div>
)
}

Key Points

  • Must be a Client Component
  • Can recover using reset()
  • Scoped to route segment

Use Case

  • Graceful error handling
  • Better user experience

22. What is not-found.js?

Definition

not-found.js is used to render a custom 404 UI for a route segment.

How It Works

  • Automatically shown when route is not found
  • Can be triggered manually

Example

export default function NotFound() {
return <h1>Page Not Found</h1>
}

Triggering

import { notFound } from 'next/navigation'

notFound()

Key Points

  • Route-specific 404 handling
  • Works with dynamic routes

23. What is useEffect and its role?

Definition

useEffect is a React hook used to perform side effects in components.

Example

import { useEffect } from 'react'

useEffect(() => {
console.log('Component mounted')
}, [])

Role in Next.js

  • Client-side data fetching
  • Event listeners
  • DOM manipulation

Key Insight

  • Runs only on the client
  • Not executed in Server Components

24. What are Server Components?

Definition

Server Components are React components that run only on the server.

Key Features

  • No client-side JavaScript
  • Can access databases directly
  • Smaller bundle size

Example

export default async function Page() {
const data = await fetch('https://api.example.com').then(res => res.json())
return <div>{data.title}</div>
}

Benefits

  • Better performance
  • Improved security
  • Reduced client bundle

25. What are Client Components?

Definition

Client Components are components that run in the browser.

Features

  • Support interactivity
  • Use hooks like useState, useEffect
  • Include event handlers

Example

'use client'

import { useState } from 'react'

export default function Counter() {
const [count, setCount] = useState(0)
return <button onClick={() => setCount(count + 1)}>{count}</button>
}

Use Case

  • Forms
  • Buttons
  • Interactive UI

26. What is "use client" directive?

Definition

"use client" is a directive that marks a component as a Client Component.

Example

'use client'

export default function Component() {
return <button>Click</button>
}

Why It’s Needed

  • App Router defaults to Server Components
  • Required for interactivity

Key Insight

Without "use client", hooks like useState will not work.


27. What is code splitting?

Definition

Code splitting is the process of splitting JavaScript into smaller bundles that load on demand.

How Next.js Implements It

  • Automatic per-page splitting
  • Dynamic imports

Example

import dynamic from 'next/dynamic'

const HeavyComponent = dynamic(() => import('./HeavyComponent'))

Benefits

  • Faster initial load
  • Reduced bundle size

28. What is lazy loading?

Definition

Lazy loading is a technique where components or resources are loaded only when needed.

Example

const Component = dynamic(() => import('./Component'))

Difference from Code Splitting

  • Code splitting = splitting bundles
  • Lazy loading = loading them when required

Use Cases

  • Images
  • Heavy components
  • Below-the-fold content

29. How to optimize images?

Techniques in Next.js

1. Use next/image

  • Automatic resizing
  • Lazy loading
  • Responsive images
import Image from 'next/image'

2. Use Proper Formats

  • WebP, AVIF

3. Responsive Images

  • Different sizes for devices

4. Lazy Loading

  • Load images only when visible

Result

  • Faster load time
  • Better performance metrics

30. How to optimize fonts?

Methods

1. Use next/font

  • Built-in font optimization
import { Inter } from 'next/font/google'

const inter = Inter({ subsets: ['latin'] })

2. Self-host Fonts

  • Improves performance

3. Preload Fonts

  • Faster rendering

4. Reduce Font Variants

  • Load only required weights

Benefits

  • Reduced layout shift (CLS)
  • Faster rendering
  • Better UX

31. How to reduce bundle size?

Definition

Bundle size refers to the amount of JavaScript sent to the browser. Reducing it improves load time and performance.

Techniques

1. Code Splitting

  • Automatic in Next.js (per page)
  • Use dynamic imports for heavy components
import dynamic from 'next/dynamic'
const Chart = dynamic(() => import('./Chart'))

2. Remove Unused Code

  • Tree shaking eliminates dead code

3. Use Server Components

  • Avoid sending JS to client

4. Optimize Dependencies

  • Avoid large libraries
  • Use lightweight alternatives

5. Analyze Bundle

npm run build

Interview Insight

Bundle size directly impacts Core Web Vitals and user experience.


32. How do API routes work internally?

Definition

API routes are server-side functions that act as backend endpoints inside Next.js.

Internal Flow

  1. Request hits /api/* route
  2. Next.js maps it to file in pages/api
  3. Runs server-side function
  4. Sends response

Example

export default function handler(req, res) {
res.status(200).json({ message: 'Hello' })
}

Behind the Scenes

  • Runs on Node.js or serverless functions
  • Not included in client bundle

Key Insight

Acts like a lightweight backend within your frontend app.


33. What is serverless deployment?

Definition

Serverless deployment means running code without managing servers, using cloud functions.

How It Works

  • Each API route becomes a function
  • Executes on demand
  • Scales automatically

Examples

  • Vercel Functions
  • AWS Lambda

Benefits

  • Auto-scaling
  • Cost-efficient
  • No server management

Drawback

  • Cold starts (initial delay)

34. What are route handlers?

Definition

Route Handlers are used in the App Router to define custom API endpoints.

Location

app/api/user/route.js

Example

export async function GET() {
return Response.json({ name: 'John' })
}

Supported Methods

  • GET
  • POST
  • PUT
  • DELETE

Key Insight

They replace pages/api in the App Router.


35. How to handle CORS?

Definition

CORS (Cross-Origin Resource Sharing) controls how resources are shared across domains.

Solution

1. Set Headers

res.setHeader('Access-Control-Allow-Origin', '*')
res.setHeader('Access-Control-Allow-Methods', 'GET,POST')

2. Middleware Approach

  • Modify response headers globally

3. Use Libraries

  • cors package

Interview Insight

CORS issues occur when frontend and backend are on different domains.


36. How to manage cookies?

Methods

1. In API Routes

res.setHeader('Set-Cookie', 'token=abc; HttpOnly')

2. In App Router

import { cookies } from 'next/headers'

cookies().set('token', 'abc')

Types

  • HttpOnly (secure)
  • Secure (HTTPS only)

Use Cases

  • Authentication
  • Session management

37. How to secure API routes?

Techniques

1. Authentication

  • JWT tokens
  • Sessions

2. Authorization

  • Role-based access

3. Input Validation

  • Prevent injection attacks

4. Rate Limiting

  • Prevent abuse

5. Secure Headers

  • Use HTTPS
  • Set proper headers

Example

if (!req.headers.authorization) {
return res.status(401).json({ error: 'Unauthorized' })
}

Interview Insight

Security is critical for production-grade apps.


38. How does middleware work?

Definition

Middleware runs before a request reaches a route, allowing you to modify it.

Flow

  1. Request arrives
  2. Middleware executes
  3. Modify request/response
  4. Continue or redirect

Example

import { NextResponse } from 'next/server'

export function middleware(req) {
return NextResponse.next()
}

Key Feature

Runs at the edge (before server logic).


39. Use cases of middleware?

Common Use Cases

1. Authentication

  • Redirect unauthenticated users

2. Authorization

  • Restrict access

3. Redirects

  • URL rewriting

4. Localization

  • Detect user language

5. Logging

  • Track requests

Interview Insight

Middleware is powerful for cross-cutting concerns.


40. What is next.config.js headers?

Definition

Headers in next.config.js allow you to define custom HTTP response headers.

Example

module.exports = {
async headers() {
return [
{
source: '/api/:path*',
headers: [
{ key: 'Access-Control-Allow-Origin', value: '*' }
]
}
]
}
}

Use Cases

  • CORS configuration
  • Security headers (CSP, HSTS)
  • Caching control

Benefits

  • Centralized header management
  • Improves security and performance 

41. What is rewrites?

Definition

Rewrites allow you to map one URL to another internally without changing the URL in the browser.

How It Works

  • User requests /blog
  • Internally served from /api/blog
  • URL remains /blog

Example

module.exports = {
async rewrites() {
return [
{
source: '/blog',
destination: '/api/blog'
}
]
}
}

Use Cases

  • Proxy APIs
  • Clean URLs
  • Backend integration

Key Insight

URL stays the same → only internal routing changes.


42. What is redirects?

Definition

Redirects send users from one URL to another and update the URL in the browser.

Example

module.exports = {
async redirects() {
return [
{
source: '/old',
destination: '/new',
permanent: true
}
]
}
}

Types

  • 301 (permanent)
  • 302 (temporary)

Use Cases

  • URL changes
  • SEO migration
  • Route restructuring

Key Difference from Rewrites

Redirect → URL changes
Rewrite → URL stays same


43. How do you implement authentication?

Common Approaches

1. JWT-Based Auth

  • Token stored in cookie/localStorage

2. Session-Based Auth

  • Server maintains session

3. OAuth Providers

  • Google, GitHub login

Basic Flow

  1. User logs in
  2. Server verifies credentials
  3. Token/session created
  4. User accesses protected routes

Example (API Route)

if (!req.headers.authorization) {
return res.status(401).json({ error: 'Unauthorized' })
}

Best Practice

  • Use secure cookies (HttpOnly)
  • Validate tokens on server

44. JWT vs session-based auth?

Comparison

FeatureJWTSession
StorageClient-sideServer-side
ScalabilityHighModerate
SecurityDependsStrong
StateStatelessStateful

JWT

  • Token contains data
  • No server storage required

Session

  • Stores session on server
  • Uses session ID

Interview Insight

  • JWT → scalable APIs
  • Session → better security control

45. What is NextAuth?

Definition

NextAuth.js is a library for handling authentication in Next.js applications.

Features

  • OAuth providers (Google, GitHub)
  • Email/password login
  • JWT and session support
  • Built-in security

Example

import NextAuth from "next-auth"

export default NextAuth({
providers: []
})

Benefits

  • Easy integration
  • Production-ready
  • Secure by default

46. Styling options in Next.js?

Available Options

  1. Global CSS
  2. CSS Modules
  3. Styled JSX
  4. CSS-in-JS libraries (styled-components)
  5. Tailwind CSS
  6. Sass/SCSS

Key Insight

Next.js supports multiple styling approaches out of the box.


47. CSS-in-JS vs CSS Modules?

Comparison

FeatureCSS-in-JSCSS Modules
Style LocationJS fileCSS file
Dynamic StylingEasyLimited
PerformanceSlight overheadBetter
ScopeComponent-scopedComponent-scoped

CSS-in-JS

  • Styles written inside JS
  • Example: styled-components

CSS Modules

  • Separate CSS files
  • Scoped automatically

Interview Insight

  • CSS Modules → performance
  • CSS-in-JS → flexibility

48. How to debug Next.js apps?

Techniques

1. Console Logging

console.log(data)

2. Browser DevTools

  • Inspect network requests
  • Check errors

3. Next.js Error Overlay

  • Shows runtime errors

4. Debug Server Code

  • Use Node.js debugger

5. Check Logs

  • Server logs
  • Build logs

Best Practice

  • Debug both client and server separately

49. Testing strategies?

Types of Testing

1. Unit Testing

  • Test individual components
  • Tools: Jest

2. Integration Testing

  • Test combined functionality

3. End-to-End Testing

  • Test full user flow
  • Tools: Cypress, Playwright

Example

test('renders component', () => {
expect(true).toBe(true)
})

Interview Insight

Use a combination of all testing types for reliability.


50. How to implement i18n (internationalization)?

Definition

i18n allows applications to support multiple languages and locales.

Setup in Next.js

module.exports = {
i18n: {
locales: ['en', 'fr', 'hi'],
defaultLocale: 'en'
}
}

Usage

  • /en/about
  • /fr/about

Features

  • Automatic locale detection
  • Routing support

Advanced Approach

  • Use libraries like next-intl

Benefits

  • Global audience reach
  • Better UX for different regions

51. What is next-i18next?

Definition

next-i18next is a library that integrates i18next with Next.js to provide advanced internationalization support.

Key Features

  • Translation management
  • Server-side translations
  • Namespace-based translations
  • Works with SSR and SSG

Example

import { useTranslation } from 'next-i18next'

const { t } = useTranslation('common')

Use Case

  • Multi-language applications
  • Complex localization requirements

Interview Insight

More powerful than built-in i18n for large-scale apps.


52. Why use Create Next App?

Definition

Create Next App is an official tool to quickly bootstrap a Next.js project.

Advantages

  • Zero configuration setup
  • Pre-configured tooling
  • TypeScript support
  • ESLint integration

Why It Matters

  • Saves development time
  • Ensures best practices
  • Reduces setup errors

53. What is Fast Refresh vs HMR?

Definitions

  • Fast Refresh → React-specific hot reloading
  • HMR (Hot Module Replacement) → General module replacement system

Comparison

FeatureFast RefreshHMR
ScopeReact componentsAny module
State PreservationYesNot guaranteed
UsageNext.js defaultWebpack feature

Key Insight

Fast Refresh is an improved version of HMR for React apps.


54. What is serverless architecture?

Definition

Serverless architecture is a model where applications run on cloud-managed functions instead of dedicated servers.

How It Works

  • Code deployed as functions
  • Triggered by requests
  • Automatically scaled

Examples

  • Vercel Functions
  • AWS Lambda

Interview Insight

Developers focus on code, not infrastructure.


55. Advantages of serverless?

Benefits

1. Auto Scaling

  • Handles traffic automatically

2. Cost Efficiency

  • Pay only for usage

3. No Server Management

  • No infrastructure setup

4. High Availability

  • Built-in redundancy

5. Faster Deployment

  • Quick updates

Drawbacks

  • Cold starts
  • Limited control

56. What is next/dynamic?

Definition

next/dynamic is used for dynamic imports of components, enabling lazy loading.

Example

import dynamic from 'next/dynamic'

const Chart = dynamic(() => import('./Chart'))

Benefits

  • Reduces initial bundle size
  • Improves performance

57. What is ssr: false?

Definition

ssr: false disables server-side rendering for a dynamically imported component.

Example

const Component = dynamic(() => import('./Component'), {
ssr: false
})

Use Cases

  • Browser-only libraries
  • Components using window or document

Key Insight

Forces component to render only on client side.


58. How to use custom server?

Definition

A custom server allows you to run Next.js with a custom Node.js server (e.g., Express).

Example

const express = require('express')
const next = require('next')

const app = next({ dev: true })
const handle = app.getRequestHandler()

app.prepare().then(() => {
const server = express()

server.get('*', (req, res) => {
return handle(req, res)
})

server.listen(3000)
})

Use Cases

  • Custom routing
  • Middleware integration

Drawbacks

  • Loses serverless benefits
  • More maintenance

59. What is singleton router?

Definition

Singleton Router is a global router instance used outside React components.

Example

import Router from 'next/router'

Router.push('/home')

Use Case

  • Navigation outside components
  • Utility functions

Note

Less commonly used in modern Next.js (prefer hooks).


60. How does Next.js handle environment configs?

Definition

Next.js manages environment configuration using .env files and next.config.js.

Types of Files

  • .env.local
  • .env.development
  • .env.production

Example

NEXT_PUBLIC_API_URL=https://api.example.com

Usage

process.env.NEXT_PUBLIC_API_URL

Key Rules

  • Prefix with NEXT_PUBLIC_ for client-side access
  • Others remain server-only

Integration with next.config.js

module.exports = {
env: {
CUSTOM_KEY: 'value'
}
}

Benefits

  • Secure configuration
  • Environment-specific behavior