56 questions with detailed answers
Q1. What is Next.js?
Answer: Next.js is a React framework for full-stack web apps. It adds file-based routing, SSR/SSG/ISR, API route handlers, image/font optimization, and deployment tooling on top of React.
Q2. How do you create a new Next.js project?
Answer: Run npx create-next-app@latest and follow the prompts (TypeScript, App Router, Tailwind, ESLint). Prefer the App Router for new projects.
Q3. What is file-based routing in Next.js?
Answer: Routes come from the folder/file tree under app/ (App Router) or pages/ (Pages Router). Special files like page.tsx, layout.tsx, and route.ts define UI and API endpoints without a separate router config.
Q4. What are the key features of Next.js?
Answer: SSR, SSG, ISR, CSR, file-based routing, Route Handlers, React Server Components, Middleware, next/image and next/font, automatic code splitting, Fast Refresh, and first-class TypeScript support.
Q5. How does Next.js differ from plain React?
Answer: React is a UI library with CSR by default and no built-in routing or SSR. Next.js is a framework: file-based routing, multiple rendering modes, Route Handlers, and built-in image/font/script optimizations.
Q6. What is the difference between CSR and SSR in Next.js?
Answer: CSR ships JS and builds HTML in the browser — slower first paint, weaker SEO unless hydrated carefully. SSR generates HTML on the server per request, so users and crawlers get content immediately.
Q7. What is Static Site Generation (SSG)?
Answer: SSG pre-renders HTML at build time. Pages stay fast and cacheable; use ISR or on-demand revalidation when content must update without a full rebuild.
Q8. What is Incremental Static Regeneration (ISR)?
Answer: ISR serves a static page and regenerates it in the background after a revalidate window (or on-demand). You get static performance with periodically fresh data.
Q9. SSG vs SSR — when do you choose each?
Answer: Use SSG/ISR for mostly static or slowly changing content (blogs, marketing, catalogs). Use SSR (or force-dynamic) when every request needs fresh, user-specific, or highly dynamic data.
Q10. What is the Link component in Next.js?
Answer: next/link enables client-side navigation with prefetching. Prefer <Link href="/about"> over <a> for internal routes so you keep SPA-like transitions without full reloads.
Q11. What is useRouter and how do push vs replace differ?
Answer: useRouter (from next/navigation in App Router) lets you navigate programmatically. push adds a history entry; replace swaps the current entry so Back skips the previous URL.
Q12. What is the App Router?
Answer: Introduced in Next.js 13, the App Router uses the app/ directory with nested layouts, Server Components by default, loading/error/not-found UI, streaming, and Route Handlers.
Q13. What is the Pages Router?
Answer: The classic pages/ system: one file ≈ one route, with getStaticProps, getServerSideProps, and getStaticPaths. Still supported, but new features land primarily on the App Router.
Q14. Explain the core architectural differences between the Pages Router and App Router in Next.js 13+.
Answer: Routing: Pages maps each pages/* file to a route; App Router uses app/ folders with page.js per segment and first-class nested layouts. Rendering: Pages components are Client Components by default and rely on getServerSideProps/getStaticProps/getInitialProps; App Router defaults to React Server Components and opts into client with "use client". Layouts: Pages composes via _app/_document or HOCs; App Router uses layout.js that persist across navigations. Data: Pages uses Next-specific data functions; App Router fetches in async Server Components (and Server Actions for mutations). Streaming: App Router streams with React 18 and loading.js; Pages has no native streaming model. Prefer App Router for new apps; keep Pages for legacy get*Props-heavy codebases.
Q15. How does the Server Components architecture in the App Router impact rendering, hydration, and client interactivity?
Answer: Rendering: Server Components run only on the server; their output is sent as HTML/RSC payload and their code is not shipped in the client JS bundle. Hydration: only Client Components hydrate — Server Components stay static on the client, so less JS means faster hydration. Interactivity: hooks, event handlers, and browser APIs require "use client". Keep that boundary as low as possible. Composition: Server Components can pass serializable props into Client Components, and can also pass Server Components as children into Client Components; Client Components cannot import Server Components directly.
Q16. What does "use client" do?
Answer: It marks a module and its imports as a Client Component boundary. Use it for state, effects, event handlers, and browser-only APIs. Keep it as low in the tree as possible.
Q17. What does "use server" do?
Answer: It marks async functions as Server Actions — callable from the client (e.g. form action) but executed on the server with access to databases and secrets.
Q18. What are Server Actions and why use them?
Answer: Server Actions are server functions for mutations (forms, updates) without hand-rolling an API route. Benefits: less client JS, secrets stay server-side, and you can revalidatePath/revalidateTag after writes. Trade-off: network round-trips and careful validation still required.
Q19. How does the metadata export work in the App Router?
Answer: Export a metadata object or generateMetadata function from layout/page to set title, description, Open Graph, robots, etc. Prefer this over next/head (Pages) or the old head.js convention.
Q20. What is generateStaticParams?
Answer: In App Router dynamic segments ([slug]), generateStaticParams returns param objects to pre-render at build time — the App Router equivalent of getStaticPaths.
Q21. How do fetch cache options work in the App Router?
Answer: Server fetch is cached by default. Use cache: "no-store" for always-fresh data, cache: "force-cache" to prefer cache, or next: { revalidate: N } for time-based ISR-style revalidation.
Q22. What does export const dynamic do?
Answer: It overrides rendering: "force-dynamic" always renders per request, "force-static" prefers static, "auto" lets Next.js decide from APIs used (cookies, headers, no-store fetch, etc.).
Q23. What are layout.js, template.js, and loading.js?
Answer: layout.js wraps segments and preserves state across navigations. template.js remounts on each navigation (good for enter animations). loading.js wraps the segment in Suspense and shows instant loading UI.
Q24. How do error.js and not-found.js work?
Answer: error.js is a Client Component error boundary with error and reset props. not-found.js renders when notFound() is called or no matching route exists. Both can be nested per segment.
Q25. How would you implement route grouping, parallel routes, and intercepting routes in a large-scale App Router app?
Answer: Route groups: use (marketing)/(dashboard) folders to split concerns and layouts without changing URLs — e.g. app/(marketing)/about/page.tsx → /about. Parallel routes: add @inbox and @chat slots and accept them as props in layout.js so panels navigate independently inside one shell. Intercepting routes: soft-navigate into a modal with a convention like app/feed/@modal/(.)post/[id]/page.tsx while keeping a full-page app/post/[id]/page.tsx for shared links. In multi-team apps, groups segment ownership, parallel slots power multi-panel UIs, and intercepts keep overlays without losing surrounding context.
Q26. What are Route Handlers vs Pages API routes?
Answer: Pages used pages/api/*.js with (req, res). App Router uses app/api/.../route.ts exporting GET/POST/etc. with Web Request/Response APIs. Same idea — backend endpoints in the Next app.
Q27. How do you use the Edge Runtime for a route?
Answer: Export const runtime = "edge" in a Route Handler or page. Edge is great for low-latency global work; use Node (default) when you need Node APIs, native modules, or heavy CPU.
Q28. What is Middleware in Next.js?
Answer: middleware.ts at the project root (or src/) runs before a matched request completes. Use it for redirects, rewrites, header tweaks, and coarse auth gates via NextResponse. Keep it light — it runs on the Edge by default.
Q29. What is the public folder?
Answer: Static files under public/ are served from the site root. public/images/logo.png is available at /images/logo.png. Do not import from public for hashed assets that belong in the module graph — use imports or next/image.
Q30. How do environment variables work in Next.js?
Answer: Put secrets in .env.local and read them as process.env.ONLY_ON_SERVER. Only variables prefixed with NEXT_PUBLIC_ are exposed to the browser — never put API secrets there.
Q31. What is next/image used for?
Answer: The Image component resizes, optimizes formats, lazy-loads, and prevents layout shift when width/height (or fill) are set. Use placeholder="blur" with static imports or a blurDataURL for better perceived performance.
Q32. How do you optimize fonts in Next.js?
Answer: Use next/font (Google or local) to self-host fonts, eliminate layout shift, and avoid extra network round-trips to font CDNs.
Q33. What is next/script?
Answer: A component to load third-party scripts with strategies like beforeInteractive, afterInteractive, and lazyOnload — better control than raw <script> tags for analytics and widgets.
Q34. What is next/dynamic and ssr: false?
Answer: dynamic(() => import(...)) code-splits components. { ssr: false } skips server rendering for browser-only libs (charts, maps) that break during SSR.
Q35. What is next.config.js used for?
Answer: Project configuration: redirects, rewrites, headers, images.remotePatterns, webpack/turbopack tweaks, output: "export" for static export, and experimental flags.
Q36. How do you handle redirects in Next.js?
Answer: Configure async redirects() in next.config, use NextResponse.redirect in Middleware, or call redirect() from next/navigation in Server Components/Actions.
Q37. How do you add global CSS in the App Router?
Answer: Import globals.css once from the root app/layout.tsx. For component-scoped styles use CSS Modules (*.module.css) or your CSS framework of choice.
Q38. getStaticProps vs getServerSideProps vs getStaticPaths?
Answer: Pages Router only: getStaticProps runs at build (optional revalidate for ISR), getServerSideProps runs per request, getStaticPaths lists dynamic paths to pre-render and sets fallback behavior.
Q39. What does fallback mean in getStaticPaths?
Answer: false → unknown paths 404. true → serve a fallback shell then hydrate. "blocking" → wait for SSR generation then cache like a static page.
Q40. What are _app.js and _document.js?
Answer: Pages Router: _app wraps every page (global providers/styles). _document customizes the HTML/body shell. App Router replaces both with root layout.tsx.
Q41. How do you stream UI with Suspense in the App Router?
Answer: Wrap slow async Server Components in <Suspense fallback={...}>. Next streams the shell first, then fills in resolved segments — better TTFB perception and progressive rendering.
Q42. How do you read and set cookies in the App Router?
Answer: On the server, use cookies() from next/headers to read. Set cookies in Route Handlers/Server Actions via cookies().set or Set-Cookie on the Response. Prefer HttpOnly Secure cookies for auth tokens.
Q43. How should you secure Next.js apps?
Answer: HTTPS everywhere, validate/sanitize inputs, keep secrets server-only, authz checks in Middleware and again in handlers/actions, secure cookies, CSP headers, dependency updates, and never trust client-supplied roles.
Q44. How do you prevent unauthorized API access?
Answer: API routes are public URLs — hide nothing by obscurity. Verify session/JWT/API keys on every request, enforce method and input validation, and rate-limit sensitive endpoints.
Q45. How does Auth.js / NextAuth fit the App Router?
Answer: Install next-auth (Auth.js), add a catch-all Route Handler under app/api/auth/[...nextauth]/route.ts, configure providers and secret, and protect pages via Middleware or server-side auth() helpers.
Q46. How do you handle form submissions in the App Router?
Answer: Prefer a Server Action as the form's action={fn} with FormData, or POST to a Route Handler from a Client Component. Always validate on the server and revalidate cached data after mutations.
Q47. How do you handle file uploads?
Answer: Use multipart forms with FormData in a Server Action or Route Handler, then stream/store the file (S3, local disk in Node runtime). Validate type/size server-side; Edge runtimes have tighter limits.
Q48. List common Next.js performance techniques.
Answer: Prefer Server Components, SSG/ISR where possible, next/image and next/font, dynamic imports for heavy client widgets, streaming/Suspense, cache/revalidate wisely, and avoid unnecessary "use client".
Q49. How do you deploy a Next.js app?
Answer: Connect the repo to Vercel for zero-config Node/Edge deploy, or self-host with next build && next start behind Node. For fully static sites set output: "export" (limited features — no SSR/ISR/server actions).
Q50. What is Fast Refresh?
Answer: Next.js Fast Refresh hot-updates React components during development while trying to preserve component state, giving near-instant feedback without full reloads.
Q51. How do you change the default port?
Answer: Use next dev -p 8080 / next start -p 8080 in package.json scripts, or set the PORT environment variable in many hosts.
Q52. Can App Router and Pages Router coexist?
Answer: Yes — both directories can exist during migration. Prefer not to duplicate the same route in both. New work should go in app/ unless constrained by legacy Pages code.
Q53. How do you implement optimistic UI with the App Router?
Answer: Update Client Component state immediately, call a Server Action or API, then router.refresh() / revalidate on success and roll back local state on failure. useOptimistic helps with this pattern.
Q54. How do you choose Edge vs Node for Route Handlers?
Answer: Edge: cold-start friendly, globally distributed, Web APIs only. Node: filesystem, native modules, longer CPU work, familiar Node libraries. Default is Node unless you opt into edge.
Q55. Why is Next.js considered full-stack?
Answer: One codebase can own UI, server rendering, Route Handlers/Server Actions, Middleware, and integration with databases/auth — front and back without a separate framework for many apps.
Q56. How does layout nesting work in the App Router?
Answer: Every folder under app/ can define a layout.js; layouts nest by route hierarchy. Visiting /dashboard/analytics renders RootLayout → DashboardLayout → AnalyticsPage. Shared chrome (nav, sidebar) lives in the nearest layout and persists across navigations inside that subtree, so only the page (and deeper segments) remount — better UX and less rework than re-wrapping every page in Pages Router _app patterns.