{jsonbody.com}

Top 50 Next.js Interview Questions & Answers

Practise 50 Next.js interview questions on the App Router, Server Components, SSR, SSG, ISR, caching, Server Actions, middleware and SEO.

Next.js Fundamentals

Q1. What is Next.js?

Next.js is a React framework made by Vercel for building full-stack web apps. It adds file-based routing, server rendering, static generation, API endpoints and build optimisations on top of React.

Q2. Why use Next.js instead of plain React?

Plain React renders in the browser and leaves routing, data loading and SEO to you. Next.js provides server rendering for faster first loads and better SEO, plus routing, image optimisation and backend code in one project.

Q3. What is the difference between the App Router and the Pages Router?

The Pages Router uses the pages/ folder with functions like getServerSideProps. The App Router uses the app/ folder with React Server Components, nested layouts and streaming, and is the recommended router for new projects.

Q4. How does file-based routing work in the App Router?

Each folder in app/ is a URL segment, and a page.tsx file makes that segment publicly reachable. For example, app/blog/page.tsx serves /blog.

Q5. What are the special files in the App Router?

page renders a route, layout wraps child routes, loading shows a Suspense fallback, error is an error boundary, not-found handles 404s, and route defines an API endpoint.

Q6. What is a layout?

A layout.tsx wraps all pages below it and keeps its state when users navigate between them. The root layout in app/layout.tsx is required and must render the <html> and <body> tags.

Q7. What is the difference between a layout and a template?

A layout stays mounted during navigation, so its state and effects persist. A template.tsx creates a new instance on every navigation, which suits enter animations or resetting state.

Q8. How do dynamic routes work?

Wrap a folder name in brackets, such as app/blog/[slug]/page.tsx. The value arrives in the params prop. [...slug] catches all following segments, and [[...slug]] also matches the parent route.

Q9. What are route groups?

Folders named in parentheses, such as (marketing), organise routes or give them different layouts without adding a segment to the URL.

Q10. How do you navigate between pages?

Use the <Link> component for client-side navigation with automatic prefetching. For navigation in code, call useRouter().push() in a Client Component, or redirect() on the server.

Server and Client Components

Q11. What are React Server Components?

Components that render only on the server and send rendered output to the browser instead of JavaScript. In the App Router, components are Server Components by default.

Q12. What are the benefits of Server Components?

They can read databases and secrets directly, ship no JavaScript for themselves, keep large dependencies off the client, and reduce the work the browser must do.

Q13. What does 'use client' do?

Placed at the top of a file, it marks the file and everything it imports as client code. Use it for components that need state, effects, event handlers or browser APIs.

Q14. Can a Client Component import a Server Component?

Not directly, because importing it would turn it into client code. Instead, pass the Server Component as children or another prop from a Server Component parent.

Q15. What can you not use in Server Components?

Hooks such as useState and useEffect, event handlers like onClick, and browser APIs such as window or localStorage. Those belong in Client Components.

Q16. What props can pass from a Server Component to a Client Component?

Only serialisable values such as strings, numbers, plain objects, arrays, Dates and promises. Functions cannot be passed, except Server Actions.

Q17. What is hydration?

Hydration is when React attaches event handlers and state to the HTML rendered on the server, making it interactive. Only Client Components hydrate.

Q18. What causes a hydration mismatch error?

Server and client rendering different output, for example from Date.now(), Math.random(), reading window during render, or invalid HTML nesting. Move such values into useEffect to fix it.

Q19. How do you protect server-only code?

Import the server-only package in modules that contain secrets or database access. The build fails if a Client Component imports that module by mistake.

Q20. How do you share state between components in the App Router?

Use React Context inside a Client Component provider wrapped around children in a layout. For server data, fetch it where needed, since repeated fetches can be deduplicated.

Data Fetching, Rendering & Caching

Q21. How do you fetch data in the App Router?

Make the Server Component async and await a fetch() call or a database query directly in the component body. No special function like getServerSideProps is needed.

Q22. What is the difference between SSR, SSG and ISR?

SSR renders on every request, SSG renders once at build time, and ISR serves static pages but regenerates them in the background after a set time or on demand.

Q23. How do you create static pages for dynamic routes?

Export generateStaticParams() from the dynamic page. It returns the list of params, such as slugs, and Next.js pre-renders one page for each at build time.

Q24. How do you set revalidation time?

Export const revalidate = 60 from a page or layout, or pass { next: { revalidate: 60 } } to fetch(). The page is then regenerated at most once every 60 seconds.

Q25. What is on-demand revalidation?

Calling revalidatePath('/blog') or revalidateTag('posts') after data changes, usually in a Server Action or webhook. It clears cached data immediately instead of waiting for a timer.

Q26. What makes a route dynamic?

Reading request-time data such as cookies(), headers() or searchParams, or using uncached data, forces the route to render on each request instead of at build time.

Q27. What is streaming in Next.js?

Sending HTML in chunks as parts of the page become ready. A loading.tsx file or a <Suspense> boundary shows a fallback while slower components load.

Q28. What is Partial Prerendering?

A rendering model where a route's static shell is served instantly from the edge and dynamic parts inside Suspense boundaries are streamed in afterwards, in the same response.

Q29. What are Server Actions?

Async functions marked with 'use server' that run on the server and can be called from forms or client code. They handle mutations without writing separate API routes.

Q30. How do you avoid data-fetching waterfalls?

Start independent requests together with Promise.all, fetch in parallel in sibling components, and use Suspense boundaries so slow data does not block the rest of the page.

Routing, APIs & Middleware

Q31. How do you create an API endpoint in the App Router?

Add a route.ts file and export functions named after HTTP methods, such as export async function GET(request). They use the standard Web Request and Response objects.

Q32. What is middleware in Next.js?

A function in middleware.ts at the project root that runs before a request is completed. It can redirect, rewrite, set headers or check authentication, and a matcher config limits which paths it runs on.

Q33. What is the difference between a redirect and a rewrite?

A redirect sends the browser to a new URL, which changes the address bar. A rewrite serves content from another path while the URL the user sees stays the same.

Q34. What are parallel routes?

Named slots defined with @folder that render several pages in the same layout at once, such as a dashboard with independent panels that each load and handle errors separately.

Q35. What are intercepting routes?

Routes using conventions like (.)photo that show another route inside the current layout, for example opening a photo in a modal while the URL changes. A full reload shows the normal page.

Q36. How do you handle errors in the App Router?

Add an error.tsx Client Component to a segment to catch errors in it and offer a reset. global-error.tsx catches errors in the root layout, and notFound() renders the nearest not-found file.

Q37. How do you read search params?

Server pages receive a searchParams prop. Client Components use the useSearchParams() hook, which should be wrapped in Suspense so the rest of the page can still be pre-rendered.

Q38. How do you implement authentication in Next.js?

Use a library such as Auth.js, Clerk or a custom session cookie. Check the session in middleware for quick redirects and again in Server Components or actions before reading private data.

Q39. What is the Edge runtime?

A lightweight runtime based on Web APIs that starts quickly and can run close to users. It does not support all Node.js APIs, so routes needing them use the Node.js runtime instead.

Q40. How do you set environment variables for the browser?

Only variables prefixed with NEXT_PUBLIC_ are included in client bundles. All other variables are available only on the server, which keeps secrets out of the browser.

Optimisation, SEO & Deployment

Q41. What does the next/image component do?

It resizes images, serves modern formats like WebP or AVIF, lazy-loads them and reserves space to prevent layout shift. Mark the main above-the-fold image with priority.

Q42. How does next/font help performance?

It downloads Google or local fonts at build time and self-hosts them, so there is no request to an external font server and no layout shift while the font loads.

Q43. How do you add SEO metadata in the App Router?

Export a metadata object or a generateMetadata() function from a page or layout. Next.js renders the title, description, Open Graph and canonical tags in the HTML head.

Q44. How do you create a sitemap and robots.txt?

Add app/sitemap.ts and app/robots.ts files that return the data. Next.js generates the XML and text files at build time or on request.

Q45. What is the next/script component for?

It loads third-party scripts with a strategy such as afterInteractive or lazyOnload, so analytics and ad scripts do not block the page from rendering.

Q46. What is Turbopack?

A Rust-based bundler built for Next.js that replaces webpack for faster development builds and refreshes. Recent versions of Next.js use it by default.

Q47. How do you reduce JavaScript bundle size in Next.js?

Keep components on the server where possible, move 'use client' down to small interactive leaves, load heavy components with next/dynamic, and inspect bundles with the bundle analyzer.

Q48. What is static export in Next.js?

Setting output: 'export' produces plain HTML, CSS and JS files that any static host can serve. Features that need a server, such as ISR, middleware and Server Actions, are not available.

Q49. How do you deploy Next.js outside Vercel?

Run next build and next start on a Node.js server, or set output: 'standalone' to produce a minimal folder that is ideal for Docker images. Put a CDN in front for static assets.

Q50. How do you measure Core Web Vitals in Next.js?

Use the useReportWebVitals hook to send LCP, INP and CLS to analytics, and check field data in PageSpeed Insights or Search Console to find slow pages.