NEXT JS
NEXT JS Interview Questions and Answers
SECTION 1: Next.js Fundamentals
1. What is Next.js?
Next.js is a React framework that provides server-side rendering (SSR), static site generation (SSG), routing, API routes, and performance optimization.
// pages/index.js
export default function Home() {
return <h1>Welcome to Next.js</h1>;
}
2. What’s the difference between React and Next.js?
React | Next.js |
---|---|
UI Library | Full Framework |
Client-side rendering only | Supports SSR, SSG, ISR |
Manual routing setup | File-based routing |
3. What is Server-Side Rendering (SSR)?
The page is rendered on the server at request time.
export async function getServerSideProps() {
const res = await fetch('https://api.example.com/data');
const data = await res.json();
return { props: { data } };
}
4. What is Static Site Generation (SSG)?
SSG builds the HTML at build time and serves it statically.
export async function getStaticProps() {
return { props: { name: 'Next.js User' } };
}
5. What is Incremental Static Regeneration (ISR)?
ISR allows revalidating static pages after a set interval.
export async function getStaticProps() {
return {
props: { time: new Date().toISOString() },
revalidate: 60, // revalidate every 60s
};
}
6. What is the App Router in Next.js 13+?
The App Router introduces Server Components, Layouts, Streaming, and Server Actions.
// app/page.js
export default function Page() {
return <h1>App Router Example</h1>;
}
7. Difference between pages/
and app/
router?
pages/ | app/ |
---|---|
Older router | Introduced in Next 13 |
Uses getStaticProps/getServerSideProps | Uses Server Components |
No nested layouts | Supports nested layouts |
8. How to create dynamic routes?
// pages/blog/[id].js
export default function Blog({ params }) {
return <h1>Post ID: {params.id}</h1>;
}
9. How do you navigate between pages?
import Link from 'next/link';
<Link href="/about">About</Link>
10. How to use useRouter hook?
import { useRouter } from 'next/router';
const router = useRouter();
console.log(router.query);
SECTION 2: Data Fetching & API Handling
11. How to create API routes in Next.js?
// pages/api/hello.js
export default function handler(req, res) {
res.status(200).json({ message: 'Hello API' });
}
12. How do you fetch data in App Router?
export default async function Page() {
const res = await fetch('https://api.example.com/data', { cache: 'no-store' });
const data = await res.json();
return <pre>{JSON.stringify(data)}</pre>;
}
13. What are caching options for fetch in Next.js?
-
cache: 'force-cache'
(default) -
cache: 'no-store'
-
next: { revalidate: 10 }
14. How to handle dynamic paths with getStaticPaths
?
export async function getStaticPaths() {
return { paths: [{ params: { id: '1' } }], fallback: false };
}
15. How to handle POST requests in API?
export default function handler(req, res) {
if (req.method === 'POST') {
res.status(200).json({ received: req.body });
}
}
16. How to secure API routes?
Use middleware for JWT/session verification.
// middleware.js
import { NextResponse } from 'next/server';
export function middleware(req) {
const token = req.cookies.get('token');
if (!token) return NextResponse.redirect('/login');
}
17. What is middleware used for?
-
Auth checks
-
Rewrites/redirects
-
Header modification
18. How to revalidate pages on-demand?
// pages/api/revalidate.js
export default async function handler(req, res) {
await res.revalidate('/posts/1');
res.json({ revalidated: true });
}
19. How to use environment variables?
.env.local
NEXT_PUBLIC_API_URL=https://api.example.com
process.env.NEXT_PUBLIC_API_URL;
20. How to fetch secure data only on the server?
Use getServerSideProps
or server components.
SECTION 3: Advanced Concepts
21. Explain Server Components vs Client Components.
Server Components run on the server (no JS bundle). Client Components run in the browser.
// client.js
"use client";
import { useState } from 'react';
22. How to optimize performance in Next.js?
-
Use dynamic imports
-
Use ISR
-
Compress images
-
Use React.memo & caching
23. How to do code splitting?
const Chart = dynamic(() => import('../components/Chart'), { ssr: false });
24. How does Next.js handle SEO?
-
Server-side rendering
-
Head
component for meta tags
import Head from 'next/head';
<Head><title>SEO Page</title></Head>
25. How to use next/font for optimized fonts?
import { Inter } from 'next/font/google';
const inter = Inter({ subsets: ['latin'] });
26. What is a layout in App Router?
// app/layout.js
export default function Layout({ children }) {
return <main>{children}</main>;
}
27. What is Suspense and Streaming?
Allows parts of UI to load progressively.
<Suspense fallback={<Loading />}>...</Suspense>
28. What is a Route Handler?
Handle HTTP methods directly in app/api/
.
// app/api/user/route.js
export async function GET() {
return Response.json({ name: 'Sumit' });
}
29. How to handle errors in App Router?
// app/error.js
"use client";
export default function Error({ error, reset }) {
return <button onClick={() => reset()}>Try again</button>;
}
30. How to customize 404 page?
app/not-found.js
or pages/404.js
SECTION 4: Authentication & Security
31. How to integrate authentication?
Use NextAuth.js or custom JWT logic.
32. How to store tokens securely?
Use HttpOnly cookies, not localStorage.
33. How to create protected routes?
Use middleware or getServerSideProps
auth checks.
34. How to handle CORS in API routes?
res.setHeader('Access-Control-Allow-Origin', '*');
35. How to handle CSRF protection?
Use same-site cookies and anti-CSRF tokens.
SECTION 5: Deployment & Optimization
36. How to deploy Next.js on Vercel?
npm run build
npm start
37. How to deploy on custom servers?
Use next start
or integrate with Express.
const express = require('express');
const next = require('next');
38. How to use Edge Functions?
Use export const runtime = 'edge'
in route.
39. What is next.config.js
used for?
module.exports = {
reactStrictMode: true,
images: { domains: ['example.com'] },
};
40. How to handle redirects and rewrites?
async redirects() {
return [{ source: '/old', destination: '/new', permanent: true }];
}
41. How to analyze bundle size?
npm install @next/bundle-analyzer
42. How to optimize images?
import Image from 'next/image';
<Image src="/img.jpg" width={300} height={200} alt="demo" />
43. How to handle internationalization (i18n)?
module.exports = { i18n: { locales: ['en', 'fr'], defaultLocale: 'en' } };
44. How to add headers globally?
async headers() {
return [{ source: '/(.*)', headers: [{ key: 'X-Frame-Options', value: 'DENY' }] }];
}
45. How to use TypeScript in Next.js?
npx create-next-app@latest --typescript
46. How to add Tailwind CSS?
npx tailwindcss init -p
47. How to use Redux or Zustand in Next.js?
Use client components:
"use client";
import { useStore } from '../store';
48. What is On-Demand ISR?
Regenerates a page when triggered by an API route or webhook.
49. What is Edge Middleware?
Lightweight functions that run before a request is completed (for auth, geolocation, etc.).
50. What’s new in Next.js 14?
-
Partial prerendering
-
Enhanced caching
-
Improved server actions
-
Faster builds and hybrid rendering
Notes
A. Design a high-traffic content platform using Next.js (SSG + SSR + ISR)
-
Goal: Serve millions of daily users with low latency and up-to-date content.
-
Architecture sketch:
-
Frontend: Next.js (App Router) deployed on Vercel or edge-enabled CDN.
-
CDN: Global CDN (Vercel Edge Network, Cloudflare) for static assets and ISR cache.
-
Origin: Headless CMS (Contentful/Strapi) + microservices for heavy business logic.
-
Data fetching: Use SSG for most pages, ISR with on-demand revalidation for content updates, SSR for personalization pages.
-
Edge functions for auth checks and geo-routing.
-
-
Trade-offs to mention: build-time cost vs freshness, cache invalidation complexity, and preview workflow for editors.
-
Interview tip: Draw the flow: user → CDN → ISR cached page → origin revalidate webhook → regenerate route.
B. Architecting for low TTFB and fast LCP
-
Tactics:
-
Use server components and streaming to reduce TTFB.
-
Move non-critical scripts off the main thread (defer, dynamic import,
ssr: false
). -
Prioritize LCP elements (critical image preloading,
priority
prop innext/image
). -
Use HTTP/2 or HTTP/3 and Brotli compression.
-
-
Metrics to cite: TTFB, LCP, FID/INP, CLS.
-
Interview tip: Explain an experiment you’d run (A/B test) and how you’d measure improvements with real numbers.
C. Caching strategy across CDN, Edge, and Origin
-
Layered caching:
-
CDN edge: long TTL for static assets and ISR pages.
-
Edge functions: short-lived caches for personalized fragments.
-
Origin: fallback and revalidation endpoints.
-
-
Stale-while-revalidate: Use SWR patterns and ISR to serve stale content while regenerating.
-
Interview tip: Discuss cache invalidation (webhooks, on-demand revalidate) and cache key design.
D. Handling personalization without sacrificing cacheability
-
Pattern: Hybrid rendering — serve cached shell (SSG) + hydrate personalized fragments client-side or via Edge SSR for token-based fragments.
-
Techniques: Edge functions for header-aware rendering, ESI (edge side includes) or streaming server components for partial personalization.
-
Trade-offs: complexity vs performance; avoid full SSR for every request if unnecessary.
E. Design a scalable file upload + image processing pipeline
-
Flow: Browser → signed upload to object storage (S3) → asynchronous image processor (Lambda/Fargate) → CDN origin cache invalidation.
-
Optimizations: use multipart uploads, background queues, multiple sizes generation, AVIF/WebP conversion.
-
Interview tip: Mention idempotency, retries, and how you’d handle large spikes.
F. Migrating large monolith React app to Next.js App Router
-
Strategy:
-
Start with a new Next.js app in a monorepo; gradually move pages and components.
-
Introduce App Router features (layouts, server components) incrementally.
-
Maintain a shared UI library and versioning strategy.
-
-
Pitfalls: Build time increases, SSR differences, and third-party libs that assume browser globals.
-
Interview tip: Explain a phased migration plan with rollback capability.
G. CI/CD, testing, and release strategies for Next.js at scale
-
CI: lint, typecheck, unit tests, e2e tests (Playwright/Cypress), bundle-analyze step.
-
CD: Canary deployments, feature flags (LaunchDarkly), and progressive rollouts.
-
Monitoring: Sentry for errors, real-user monitoring for Core Web Vitals, Prometheus/Grafana for infra metrics.
-
Interview tip: Show knowledge of build caching (turbo/pnpm), and how to keep build times short.
H. Cost optimization for serverless / edge deployments
-
Considerations: execution time (SSR/edge), bandwidth (images/assets), build minutes (CI), and storage.
-
Techniques: efficient caching, avoid expensive per-request SSR, use static generation where possible, opt for regional renderers for heavy workloads.
-
Interview tip: Mention concrete cost-saving levers (e.g., reducing SSR QPS by X% via ISR).
I. Security and compliance considerations
-
Areas: secrets management, secure cookies, rate limiting, input validation, dependency scanning.
-
Regulatory: GDPR data residency (use regional CDNs/regions), logging controls, PII handling.
-
Interview tip: Stress defense-in-depth and how you’d secure SSR endpoints and server actions.
J. Example whiteboard question & high-level answer
Q: Design a news feed that supports real-time updates, personalization, and millions of users — how would you build it with Next.js?
A (high level):
-
Use Next.js for the frontend; SSG for public article pages + ISR; streaming for feed load.
-
Real-time: WebSocket or server-sent events for push updates of personalized feed cards.
-
Personalization: precompute ranking in a recommendation service and store per-user feed snapshots in Redis; serve cached shell via CDN and hydrate user-specific cards via edge SSR or client fetch.
-
Scale: autoscaled microservices, Redis clusters for low-latency reads, message queue (Kafka) for events, and global CDN for assets.
If you want, I can:
-
Add diagrams to this document, or
-
Export the whole sheet as a downloadable PDF, or
-
Convert the bonus section into flashcards for quick interview prep.
Which would you like next?