Next.js Interview Questions: From Junior to Principal Engineer (2026)
By Ahsan Hafeez · 2026-11-10
Whether you are preparing for your first frontend role or a principal engineer interview, Next.js questions go far beyond "what is SSR." This guide covers 50+ questions organized by seniority level, starting from core concepts and going all the way up to platform architecture decisions.
Core Foundations
Q: How does server-side rendering work in Next.js under the hood?
When a request hits a Next.js server, it executes the React component tree on the server, serializes it into HTML, and sends that HTML to the browser. The browser then downloads the JavaScript bundle and "hydrates" the static HTML into a fully interactive React application. This gives users an immediate visual response while JavaScript loads in the background.
Q: What is the difference between SSR, SSG, ISR and CSR in Next.js?
SSG (Static Site Generation) pre-renders pages at build time and serves them from a CDN. SSR (Server-Side Rendering) generates HTML on every request. ISR (Incremental Static Regeneration) combines both: it serves a static page but revalidates it in the background after a configured interval. CSR (Client-Side Rendering) skips server rendering entirely and builds the page in the browser using JavaScript.
Q: How does the App Router differ from the Pages Router?
The Pages Router uses a pages/ directory where each file is a route, and data fetching happens through getServerSideProps, getStaticProps, or getInitialProps. The App Router uses an app/ directory with nested layouts, React Server Components by default, and colocated data fetching using async components. The App Router also introduces conventions like loading.tsx, error.tsx, and not-found.tsx that the Pages Router does not have.
Q: How does file-based routing work in Next.js?
Every page.tsx file inside the app/ directory maps to a URL segment based on its folder path. A file at app/blog/[slug]/page.tsx creates a dynamic route matching /blog/anything. Route groups using (folderName) let you organize code without affecting the URL path, and catch-all segments like [...slug] match multiple path segments at once.
Q: What are React Server Components and how do they differ from client components?
React Server Components run only on the server and never ship their JavaScript to the browser. They can directly access databases, file systems, and environment variables without exposing them to the client. Client components are marked with "use client" at the top of the file and run in the browser, which is required for hooks like useState, useEffect, and event handlers.
Q: How does hydration work in Next.js?
The server sends pre-rendered HTML to the browser so users see content immediately. React then takes over that HTML by attaching event listeners and making it interactive, a process called hydration. If the server-rendered HTML does not match what React expects on the client, you get a hydration mismatch error, which is a common source of bugs.
Q: What happens during the Next.js build process?
Running next build analyzes your routes and determines which pages can be statically generated and which need server rendering. Static pages are pre-rendered to HTML files, server components are compiled into their serialized format, and client component JavaScript is bundled and code-split automatically. At runtime, the server handles dynamic routes while static assets are served directly from the CDN.
Q: How do streaming and Suspense work in Next.js?
Streaming lets the server send HTML in chunks as each part of the page becomes ready instead of waiting for the entire page. You wrap slow components in a <Suspense> boundary with a fallback, and the rest of the page ships immediately while the suspended content streams in later. This reduces Time to First Byte (TTFB) and lets users interact with fast parts of the page while slow parts load.
Junior Level
Q: How do you create pages and layouts in the App Router?
Create a page.tsx file inside a folder under app/ to define a route. Create a layout.tsx in the same folder to wrap that page and all its child routes with shared UI like headers and sidebars. Layouts do not re-render when navigating between child pages, which preserves state and avoids unnecessary work.
Q: How does the Link component work and why should you use it over anchor tags?
The <Link> component from next/link enables client-side navigation without a full page reload. It automatically prefetches linked pages in the background when they appear in the viewport. Using a regular <a> tag causes a full page refresh, losing client state and making navigation slower.
Q: How do you fetch data in server components?
In the App Router, server components are async by default, so you can use fetch() or query a database directly at the top level of your component. There is no need for getServerSideProps or useEffect. The data is fetched on the server and the rendered result is sent to the client without exposing your data-fetching logic.
Q: What are loading.tsx and error.tsx conventions?
A loading.tsx file exports a React component that displays automatically while the page or layout is loading, powered by Suspense under the hood. An error.tsx file catches runtime errors in its route segment and renders a fallback UI instead of crashing the whole app. Both are scoped to their route segment, so a loading state in /dashboard does not affect /settings.
Q: How does next/image optimize images?
The <Image> component automatically resizes images to the correct dimensions for each device, serves modern formats like WebP and AVIF, and lazy-loads images below the fold. It requires width and height props (or fill) to reserve space and prevent layout shift. Images are optimized on-demand and cached on the server.
Q: What is the difference between public and server environment variables?
Variables prefixed with NEXT_PUBLIC_ are inlined into the client bundle at build time and visible to anyone inspecting the page source. Variables without that prefix are only available on the server and never reach the browser. Never put secrets like API keys or database passwords in NEXT_PUBLIC_ variables.
Q: How do you create API routes in the App Router?
Create a route.ts file inside app/api/ that exports named functions matching HTTP methods: GET, POST, PUT, DELETE. Each function receives a Request object and returns a Response or NextResponse. These routes run on the server and are useful for webhooks, form handling, or proxying third-party APIs.
Q: How do you handle metadata and SEO in Next.js?
Export a metadata object or a generateMetadata function from any page or layout to set title, description, Open Graph tags, and more. Metadata merges from parent layouts to child pages, so you can set site-wide defaults in the root layout and override per page. Next.js also supports robots.ts, sitemap.ts, and JSON-LD structured data for advanced SEO.
Mid Level
Q: What are the different caching layers in Next.js?
Next.js has four caching layers: the Request Memoization cache deduplicates identical fetch calls within a single render, the Data Cache persists fetch results across requests, the Full Route Cache stores the complete rendered HTML of static routes, and the Router Cache keeps prefetched routes in the browser. Each layer has different invalidation rules, and understanding them prevents stale data bugs.
Q: How do you use middleware in Next.js?
Create a middleware.ts file at the project root. It runs before every matched request and can rewrite URLs, redirect users, set headers, or read cookies. Middleware executes at the edge, so it must use the Web APIs subset: no Node.js-specific modules like fs or database drivers. Use the matcher config to limit which routes trigger your middleware.
Q: What are parallel routes and intercepting routes?
Parallel routes let you render multiple pages simultaneously in the same layout using named slots like @dashboard and @analytics. Intercepting routes use the (..) convention to load a route in a modal or overlay while keeping the background page visible. A common pattern is intercepting /photo/[id] to show it in a modal from a feed, while the direct URL shows the full page.
Q: How do server actions work for form handling?
Server actions are async functions marked with "use server" that execute on the server when called from the client. You pass them directly to a form's action prop, and Next.js handles the serialization and network request. They support progressive enhancement: forms work even without JavaScript, and you can call revalidatePath or revalidateTag inside them to refresh cached data.
Q: How does authentication work with Next.js and Auth.js?
Auth.js (formerly NextAuth) handles sessions, OAuth providers, and token management. In the App Router, you check the session in server components using auth() and in middleware for route protection. The session can be stored in a JWT (stateless) or a database (stateful), and middleware redirects unauthenticated users before the page even starts rendering.
Q: How do you decide between dynamic and static rendering?
A route is static by default unless it uses cookies(), headers(), searchParams, or uncached fetch calls, which force dynamic rendering. Check the build output: Next.js labels each route as static or dynamic. Prefer static rendering for content that does not change per request, and use revalidate to get the benefits of static with periodic freshness.
Q: What is the difference between time-based and on-demand revalidation?
Time-based revalidation sets a TTL on cached data using revalidate: 60 in fetch options or route segment config, regenerating the page after 60 seconds when the next request arrives. On-demand revalidation uses revalidateTag() or revalidatePath() to purge specific cached data immediately, typically triggered by a webhook or CMS publish event. On-demand is more precise but requires you to wire up the triggers.
Q: What is the difference between the Edge runtime and the Node.js runtime?
The Edge runtime runs on V8 isolates close to the user with near-zero cold starts, but it only supports Web APIs: no fs, no native Node modules, and limited package compatibility. The Node.js runtime supports the full Node API and all npm packages but has slower cold starts in serverless. Choose Edge for lightweight middleware and personalization, Node.js for database-heavy or compute-intensive routes.
Senior Level
Q: How do you optimize performance in a large Next.js application?
Start with next build output to identify large bundles and dynamic vs static routes. Use @next/bundle-analyzer to find heavy client dependencies and move them behind dynamic imports with next/dynamic. Enable streaming with Suspense boundaries for slow data, and use the staleTimes config to control how long the router cache keeps prefetched data.
Q: How do you handle database connection pooling in serverless Next.js?
Every serverless function invocation can create a new database connection, which exhausts pool limits quickly. Use a connection pooler like PgBouncer or Prisma Accelerate between your functions and the database. In development, store the connection on globalThis to survive hot reloads without leaking connections. Set your database pool size to match your serverless concurrency limit.
Q: How would you design a multi-tenant Next.js application?
Use middleware to read the tenant from the subdomain or a custom header, then pass it through the request context. Store tenant config in a database and cache it aggressively. Rewrites in middleware can map tenant.example.com to /app/[tenant]/ routes without the tenant seeing the path. Keep tenant data isolated at the database level and validate the tenant ID on every server request.
Q: How do you implement internationalization in Next.js?
Use the [locale] dynamic segment as a top-level route group and detect the user's locale in middleware using the Accept-Language header or a cookie. Libraries like next-intl handle message loading, date formatting, and pluralization. Keep translation files as JSON, load only the needed locale on the server, and use generateStaticParams to pre-render all locale variants at build time.
Q: How do you add monitoring and observability to a Next.js app?
Use OpenTelemetry with instrumentation.ts to trace server-side requests from middleware through data fetching to rendering. Track Web Vitals on the client using useReportWebVitals or a RUM tool like Vercel Analytics. Log structured JSON in server components and API routes, and set up alerts on error rates, TTFB, and function duration in your monitoring platform.
Q: How do you handle complex cache invalidation patterns?
Tag your fetch calls with descriptive cache tags like fetch(url, { next: { tags: ['posts', 'post-123'] } }). When a post updates, call revalidateTag('post-123') to invalidate just that entry, and revalidateTag('posts') to refresh list pages. For cross-route invalidation, trigger revalidation from server actions or webhooks rather than relying on time-based expiry.
Q: How do you test server components?
Render server components in tests by awaiting them directly since they are async functions that return JSX. Use a test database or mock your data layer, not the components themselves. For integration tests, use Playwright to verify the full server-rendered output including streaming behavior. Unit test server actions separately by calling them as functions and asserting on their side effects.
Q: How should error handling be architected across a Next.js app?
Use error.tsx boundaries at each route segment to catch rendering errors and show contextual fallback UI. In server actions, return structured error objects instead of throwing, and let the client component display them inline. For global errors like auth failures or server crashes, use global-error.tsx at the root. Log all server errors with request context for debugging.
Team Lead
Q: When should you self-host Next.js instead of deploying to Vercel?
Self-host when you need to keep traffic inside your own network, have compliance requirements that restrict cloud vendors, or want to avoid per-seat and bandwidth pricing at scale. Use the standalone output mode to generate a minimal Node.js server you can containerize. You lose automatic edge functions, image optimization (use a CDN or Sharp), and analytics, so weigh those tradeoffs against your constraints.
Q: How do you establish Next.js conventions across multiple teams?
Create a shared ESLint config that enforces file naming, import boundaries, and component patterns. Write an architecture decision record (ADR) covering when to use server vs client components, where data fetching lives, and how routes are organized. Use a monorepo with a shared packages/ui library and enforce the conventions in CI with lint rules and build checks.
Q: How do you manage a Pages Router to App Router migration?
Migrate incrementally: both routers work side by side in the same project. Start with leaf pages that have no shared layout dependencies, convert them to the App Router, and verify behavior. Move layouts next, converting _app.tsx and _document.tsx into root layout.tsx. Migrate data fetching from getServerSideProps to async server components last, testing each conversion thoroughly.
Q: How do you set and enforce performance budgets?
Define budgets for bundle size (per-route JS), Largest Contentful Paint, and Cumulative Layout Shift. Add @next/bundle-analyzer and a size-limit check to CI that fails the build if a route exceeds its budget. Track real user metrics with a RUM tool and review them in sprint retrospectives. Performance budgets only work if they block merges, not if they only log warnings.
Q: How do you optimize CI/CD pipelines for Next.js?
Cache node_modules and the .next/cache directory between CI runs to speed up installs and builds. Use Turborepo or Nx for monorepo caching so only changed packages rebuild. Run type-checking, linting, and tests in parallel jobs. Deploy preview builds for every PR using Vercel preview deployments or a self-hosted equivalent so reviewers can verify changes visually.
Q: What code organization patterns work at scale for Next.js?
Group by feature, not by type: app/(dashboard)/settings/ contains the page, its components, actions, and tests together. Shared UI lives in packages/ui, shared utilities in packages/lib, and shared types in packages/types. Keep the app/ directory thin: pages should compose feature modules, not contain business logic. This structure makes code ownership clear across teams.
Principal Engineer
Q: When would you choose Next.js over Remix or Astro?
Choose Next.js for complex apps that need a mix of static and dynamic pages, heavy React ecosystem integration, and a mature deployment story. Choose Remix when you want fine-grained control over HTTP caching, nested route loaders, and progressive enhancement with minimal JavaScript. Choose Astro for content-heavy sites where you want zero JavaScript by default and can opt into interactivity per component.
Q: How would you implement a micro-frontend strategy with Next.js?
Use Module Federation (available in Next.js via the @module-federation/nextjs-mf plugin) to share components between independently deployed Next.js apps. Each team owns a Next.js app that exposes specific components or pages, and a shell app composes them at runtime. Alternatively, use a monorepo with shared packages and deploy each app independently to avoid the runtime complexity of federation.
Q: How do you optimize infrastructure costs for Next.js at scale?
Maximize static generation to serve pages from the CDN and reduce serverless invocations. Set aggressive s-maxage and stale-while-revalidate cache headers so CDN edge nodes absorb traffic spikes. Move image optimization to a dedicated service or CDN (like Cloudflare Images) instead of processing on every function invocation. Monitor per-route function duration and memory to right-size your serverless configuration.
Q: How do you design a CDN and edge computing strategy for a global Next.js app?
Put static assets and ISR pages on a CDN with edge nodes in your key markets. Use middleware at the edge for geolocation, A/B testing, and authentication checks that do not need a database round trip. Keep data-heavy rendering in serverless functions close to your database region to avoid cross-region latency. Use edge config or key-value stores for feature flags that need to be read at the edge without a cold origin fetch.
Q: How do you set up a monorepo for multiple Next.js applications?
Use Turborepo with shared packages/ui, packages/config, and packages/types workspaces. Each Next.js app lives in apps/ and imports shared packages using workspace dependencies. Configure turbo.json to cache build outputs per app and only rebuild what changed. Pin shared dependency versions across all workspaces to avoid duplicate bundles, and use a shared tsconfig.base.json for consistent TypeScript settings.
Q: How do you design a platform architecture that supports 50+ developers working on Next.js?
Split the product into domain-aligned Next.js apps in a monorepo, each owned by a team with its own CI pipeline and deployment schedule. Create a platform team that maintains shared packages: the design system, authentication, analytics, and infrastructure-as-code templates. Enforce boundaries with package-level ESLint import restrictions and CODEOWNERS files. Standardize on a golden path for new apps using a generator template so every team starts with consistent conventions.
Rapid Fire: Practical Q&A
Q: What are Server Actions in Next.js?
Server Actions are async functions that run on the server, defined with the "use server" directive. You call them directly from client components or form actions without writing a separate API route. Next.js handles the network request, serialization, and error handling behind the scenes. They replace most traditional POST API routes for mutations like form submissions or database writes.
Use Case: Submitting a contact form that saves data to a database without creating an /api/contact route.
Real-Time Example: A user fills out a checkout form on an e-commerce site, and the server action validates payment, creates the order in the database, and returns the confirmation - all in one function call.
Q: What are Core Web Vitals (LCP, FID, CLS)?
Core Web Vitals are three metrics Google uses to measure real-world user experience. LCP (Largest Contentful Paint) measures how fast the main content loads - target under 2.5 seconds. FID (First Input Delay) measures responsiveness when a user first interacts - target under 100ms (replaced by INP in 2024). CLS (Cumulative Layout Shift) measures visual stability - target under 0.1.
Use Case: Diagnosing why a landing page ranks poorly in Google search despite good content. Real-Time Example: A news site fixes CLS by adding width/height to all images and reserving space for ad slots, jumping from a 0.35 CLS score to 0.04 and improving search rankings within weeks.
Q: Which HTML tag is used to show 3 different images on 3 different screen sizes (mobile, tablet, desktop)?
The <picture> element with multiple <source> tags handles this. Each <source> has a media attribute with a breakpoint and a srcSet pointing to the right image. The browser picks the first matching source and falls back to the <img> tag inside. This saves bandwidth by serving smaller images to mobile devices.
Use Case: Showing a cropped portrait hero image on mobile but a wide landscape version on desktop.
Real-Time Example: An e-commerce product page uses <picture> to serve a 400px-wide image on phones, 800px on tablets, and 1200px on desktops, reducing mobile page load time by 60%.
Q: Which tag of Next.js is used for SEO?
Next.js uses the <Head> component from next/head (Pages Router) or the metadata export and generateMetadata function (App Router). In the App Router, you export a metadata object from layout.tsx or page.tsx with title, description, openGraph, and other fields. Next.js automatically renders these as <meta> tags in the HTML head. For dynamic pages, use generateMetadata which receives the route params.
Use Case: Setting unique title, description, and Open Graph image for each blog post page.
Real-Time Example: A SaaS marketing site exports generateMetadata in its /pricing page to set the title as "Pricing - AppName" and the OG image to a screenshot of the pricing table, so shared links on LinkedIn show a rich preview.
Q: What is the difference between CSR, SSR, SSG, and ISR?
CSR (Client-Side Rendering) sends an empty HTML shell and renders everything in the browser with JavaScript. SSR (Server-Side Rendering) generates HTML on the server for every request. SSG (Static Site Generation) generates HTML at build time once and serves it from a CDN. ISR (Incremental Static Regeneration) is SSG with a revalidation timer: it serves the cached page and rebuilds it in the background after the timer expires.
Use Case: Choosing the right rendering strategy for different pages in the same app based on how often data changes. Real-Time Example: An e-commerce store uses SSG for the about page (never changes), ISR with 60-second revalidation for product listings (changes daily), SSR for the cart page (user-specific), and CSR for the real-time order tracking dashboard.
Q: What are the tools used to check website performance?
Google Lighthouse (built into Chrome DevTools) gives scores for performance, accessibility, SEO, and best practices. PageSpeed Insights shows real-user data from the Chrome UX Report alongside Lighthouse results. WebPageTest runs tests from multiple locations and network conditions with waterfall charts. The Performance tab in Chrome DevTools records runtime traces to find layout thrashing, long tasks, and rendering bottlenecks.
Use Case: Running a performance audit before launching a redesigned marketing site. Real-Time Example: A development team runs Lighthouse in CI on every pull request with a performance budget of 90+, blocking merges that drop below the threshold and catching regressions before they reach production.