60 Questions

Next.js Interview Questions for 2–5 Years Experience (2026)

calendar_todayLast Updated: June 2026verified_userReviewed by: PrepEdge Tech Editorial BoardscheduleReading time: ~15 mins

Prepare for your Next.js developer interview with our curated collection of frequently asked questions. From fundamentals to advanced system scaling and architecture patterns — practice with AI-powered mock interviews that adapt to your skill level.

What is Next.js and Why is it Critical in Modern Engineering?

Next.js has emerged as a cornerstone of modern software development, specifically designed to address complex engineering and delivery challenges at scale. As a software engineer, preparing for a Next.js technical interview for Mid-Level Developers requires a structured, comprehensive understanding of its execution context, runtime performance, and underlying design philosophies. Master Next.js interview questions. Practice with comprehensive beginner and experienced Q&A covering App Router Routing, Static and Dynamic Rendering, Caching Invalidation, Server Actions Security, Partial Prerendering.

At the mid-level (typically 2 to 5 years of professional experience), companies expect you to demonstrate strong hands-on capabilities, solid project structure implementation, performance optimization skills, modern debugging techniques, and robust API design architectures. In this extensive guide, we dive deep into the top concepts, operational paradigms, and best practices that interviewers at top-tier companies look for. By mastering these interview questions and answers, you will not only pass the technical screening but also showcase real-world engineering mastery.

Next.js Lifecycle Visualizer

Client RequestEdge RouterMiddlewareAuth / RewritesEdge runtimeRSC RenderingStatic / DynamicServer Query DBStream HTMLHTML payloadSuspense shellsHydratedInteractive

Click Simulate Flow to see NextJS Request rendering. Router requests pass through Edge middleware, trigger RSC server-side render, and stream down to client hydration.

Core Architectural Concepts in Next.js

When preparing for Next.js technical interviews, you must demonstrate a deep command over its core building blocks. These are the fundamental abstractions that dictate how the technology behaves under heavy loads, concurrent workloads, and complex configurations:

App Router Routing

File-system layout routing optimizes code splitting and template reuse. Nested layout structures prevent full-page resets when switching dashboard tabs.

Static and Dynamic Rendering

Dynamic rendering models cache static blocks at the edge (CDN) while fetching dynamic widgets asynchronously, matching e-commerce site speeds.

Caching Invalidation

Declarative fetch cache controls validate edge content on-demand (ISR), avoiding full site rebuilds when content updates in headless CMSs.

Server Actions Security

Server actions act as secure server endpoints. Enforcing Zod input validation and session checks inside actions prevents CSRF and unauthorized DB mutations.

Partial Prerendering

Static shells render instantly on the client while dynamic blocks stream in via Suspense, combining static speed with dynamic personalized widgets.

Having a theoretical understanding of these concepts is good, but being able to relate them to real-world projects, describing how you used them to solve actual performance issues or modularize code, will set you apart from other candidates.

check_circleWhy Modern Companies Choose Next.js

  • checkBuilding SEO-optimized production web applications.
  • checkCreating server-rendered dynamic websites.
  • checkDeveloping static blogs and portals with sub-second page loads.

When explaining these points, always frame them around scalability, developer productivity, and overall cost of infrastructure. Interviewers love to see candidates who understand the direct connection between technical decisions and business outcomes.

lightbulbStrategic Preparation Tips

  • trending_flatUnderstand App Router file structure conventions (page, layout, error).
  • trending_flatDifferentiate server components and client components strictly.
  • trending_flatStudy the multi-level cache model and on-demand revalidation.

Make sure to practice coding these scenarios under time constraints. Mock interviews are an excellent way to build confidence and refine your technical vocabulary. Focus on explaining *why* you chose a specific solution over alternatives, including the time and space complexity analysis.

errorCrucial Mistakes to Avoid

  • closeAvoid: Executing server-only DB queries in components marked client-side.
  • closeAvoid: Failing to authorize actions, exposing server actions as unsecured endpoints.
  • closeAvoid: Creating database connection pools inside inline server action handlers.

Before jumping straight into coding or detailing a system design, always clarify requirements with your interviewer. This demonstrates a professional engineering workflow and prevents you from building the wrong solution.

trending_upHiring Trends & Career Outlook (2026)

Adoption of Partial Prerendering (PPR) for combined static/dynamic loading. Edge runtime executions for sub-millisecond middleware redirects. Deep integration of Server Actions for direct database forms.

The job market in 2026 demands highly capable engineers who understand security, performance, and distributed systems. Companies are actively looking for developers who can bridge the gap between frontend user interactivity, backend services, and database schemas. Staying ahead of these trends will position you for high-impact roles and competitive offers.

search

Basics

20 Questions

What is Next.js and how does its file-based routing system work in the App Router?

expand_more
EasyBasics
Next.js is a production-ready React framework created by Vercel. In Next.js 13+, the App Router uses the filesystem to define route paths. Any folder nested inside the app/ directory automatically becomes a URL path segment. Special files are used: page.tsx defines the UI at that route, layout.tsx defines a shared persistent wrapper, loading.tsx defines a fallback UI using Suspense, and error.tsx acts as an error boundary. Dynamic routes use brackets: app/blog/[id]/page.tsx maps to /blog/123, passing the parameter to page props.

Explain the difference between Static Site Generation (SSG) and Server-Side Rendering (SSR) in Next.js.

expand_more
EasyBasics
Static Site Generation (SSG) builds HTML pages at build time. These pages are cached on a CDN, resulting in extremely fast load times (TTFB). Server-Side Rendering (SSR) generates HTML on the server at request time for every incoming request, which is ideal for dynamic, user-specific data. In the App Router, SSG is achieved by default for static pages, while SSR is triggered by calling dynamic APIs (like cookies() or headers()) or setting force-dynamic route segment options.

What is Incremental Static Regeneration (ISR) and how do you configure it?

expand_more
EasyBasics
ISR allows you to update static pages after you have built your site, without rebuilding the entire application. It combines the speed of SSG with fresh data. You configure it by setting the revalidate property on fetch requests or using route segment configuration:
export const revalidate = 3600; // revalidate every hour
When a request comes in, the cached static page is served. After the revalidation period, a background build updates the cache, ensuring sub-second response times with fresh updates.

What are React Server Components (RSC) and why are they the default in App Router?

expand_more
EasyBasics
RSC allows components to render on the server and stream pre-compiled structure to the browser. They are the default in App Router because they keep client bundle sizes zero (server-only npm modules are not sent to the client), allow secure direct database queries, and reduce client-side rendering waterfalls by loading data closer to the database.

Explain the purpose of the next/image component and its optimization benefits.

expand_more
EasyBasics
The next/image component optimizes images automatically to improve Web Vitals (specifically Largest Contentful Paint). It automatically serves images in modern formats (WebP/AVIF), resizes images based on viewport sizes, prevents cumulative layout shift (CLS) by requiring explicit dimensions or layout placeholders, and lazy-loads images outside the viewport.

What is the next/link component and how does it optimize routing?

expand_more
EasyBasics
The next/link component wraps standard HTML anchor tags to enable client-side navigation. It optimizes routing by prefetching code and data for the linked page in the background as soon as the link enters the viewport, making page transitions feel instantaneous when the user clicks.

What are Route Handlers in Next.js and how do you write one?

expand_more
EasyBasics
Route Handlers let you create custom request handlers for a given route using the Web Request and Response APIs. They are the App Router equivalent of API routes. You write them by exporting HTTP verbs (GET, POST, etc.) from a route.ts file:
export async function GET(request: Request) {
  return Response.json({ message: "Hello World" });
}

How do you handle loading states in Next.js using loading.tsx?

expand_more
EasyBasics
Next.js automatically wraps the page component inside a React Suspense boundary when a loading.tsx file is defined in the folder. While the page component is resolving its asynchronous data, the layout remains interactive and the fallback UI inside loading.tsx (like a skeleton loader) is displayed.

How do you handle errors in Next.js using error.tsx?

expand_more
EasyBasics
Next.js uses error.tsx as a React Error Boundary to catch unexpected exceptions in nested pages and layouts. It must be a Client Component ('use client') and receives the error object and a reset() function to try to recover. If a layout fails, error.tsx isolates the crash, keeping the rest of the application active.

What is the next/font component and how does it prevent Layout Shift?

expand_more
EasyBasics
The next/font component optimizes web fonts by downloading font files at build time and hosting them statically with the application. It injects CSS variables to pre-calculate font dimensions, avoiding the flash of unstyled text (FOUT) and preventing layout shifts during page loading.

Explain dynamic routing parameters and how to parse them in App Router.

expand_more
EasyBasics
Dynamic routing parameters are defined by wrapping a folder name in square brackets, such as [id]. In the corresponding page.tsx component, you parse the values from the dynamic parameters passed as params: export default async function Page({ params }: { params: Promise<{ id: string }> }).

What is the purpose of the public/ folder in Next.js?

expand_more
EasyBasics
The public/ directory stores static assets like images, robots.txt, icons, and fonts. Assets inside this folder are mapped directly to the root path of the application (e.g., public/logo.png is served at /logo.png) and can be cached effectively on CDNs.

How do you configure absolute imports and path aliases in a Next.js project?

expand_more
EasyBasics
Absolute imports and path aliases are configured in tsconfig.json or jsconfig.json under compilerOptions.paths. This maps folders (e.g., @/components/* to components/*), making imports clean and independent of relative folder depths.

What is dynamic metadata in Next.js and how do you generate it?

expand_more
EasyBasics
Dynamic metadata is generated by exporting a generateMetadata function from a page.tsx file. Next.js calls this function with route parameters, allowing you to fetch SEO information dynamically and return titles, descriptions, and OpenGraph tags.

Explain how to configure custom HTTP headers in Next.js.

expand_more
EasyBasics
Custom HTTP headers are configured in next.config.js under the headers() function. This lets you attach security headers (like Content Security Policy, CORS, X-Frame-Options) to specific path matching patterns.

What is runtime configuration in Next.js and when is it useful?

expand_more
EasyBasics
Runtime configuration enables exposing variables to server and client environments. In the App Router, it is preferred to use environment variables prefixed with NEXT_PUBLIC_ for client access, and standard environment variables for secure server-only operations.

How do you configure redirect paths in Next.js?

expand_more
EasyBasics
Redirect paths can be configured in next.config.js using the redirects() method, inside middleware.ts for dynamic session redirects, or using the redirect() helper inside Server Components and Server Actions.

Explain layout nesting in Next.js App Router.

expand_more
EasyBasics
Layouts nest automatically. The root app/layout.tsx wraps all pages. A subfolder layout like app/blog/layout.tsx wraps only routes nested within /blog. Children pages render inside the parent layout's {children} container.

How do you render script tags securely in Next.js?

expand_more
EasyBasics
Use the next/script component. It includes optimization strategies: beforeInteractive for crucial scripts, afterInteractive (default) to load after page hydration, and lazyOnload for non-critical third-party widgets.

What is the route segment configuration property?

expand_more
EasyBasics
Route segment options are configuration variables exported from pages or layouts (e.g. export const dynamic = 'force-dynamic', export const revalidate = 0), which control caching, dynamic runtime setups, and rendering behaviors.

Architecture

9 Questions

What are React Server Actions and how do you implement them?

expand_more
MediumArchitecture
Server Actions are asynchronous RPC (Remote Procedure Call) endpoints defined with the 'use server' directive. They allow client-side components to call backend server actions directly like simple JavaScript functions, handling forms, mutations, and database updates without manual REST endpoint development.

Explain Next.js middleware and its execution lifecycle.

expand_more
MediumArchitecture
Middleware runs before a request is completed, allowing you to modify requests and responses. It runs on the Edge runtime, executing after routing matches but before static files and page data are served, making it ideal for checking auth tokens, injecting headers, and handling localized redirects.

What is the difference between CSS Modules and Tailwind CSS in Next.js?

expand_more
MediumArchitecture
CSS Modules scope CSS locally to the component to prevent class name conflicts, compiled into scoped selectors. Tailwind CSS is a utility-first utility class library compiled into a single optimized utility stylesheet, reducing total CSS volume in large projects.

How do you fetch dynamic headers and cookies inside Server Components?

expand_more
MediumArchitecture
Import and execute the headers() or cookies() functions from next/headers. Calling these functions dynamically opts the parent route into dynamic rendering, causing the page to compile at request time.

What are dynamic routing paths and how do you generate them statically?

expand_more
MediumArchitecture
Dynamic paths are statically pre-rendered using generateStaticParams(). This exports a list of route params at build time, letting Next.js pre-compile dynamic pages (like /blog/[id]) into static HTML files.

How do you build custom API endpoints inside Next.js?

expand_more
MediumArchitecture
Create a route.ts file within a path folder in the app/ directory and export standard HTTP handlers. These handlers receive requests and return standard Response objects, which is useful for handling third-party webhooks.

What is next-auth and how does it integrate into App Router?

expand_more
MediumArchitecture
NextAuth.js is an authentication solution for Next.js. In the App Router, it uses Route Handlers under /api/auth/[...nextauth] to handle OAuth providers, credentials signin, session cookies, and authorization checks.

How do you configure dynamic redirect paths using Middleware?

expand_more
MediumArchitecture
Check cookies or session headers inside middleware.ts. If unauthorized, return a redirect response using NextResponse.redirect(new URL('/login', request.url)), intercepting user requests before page rendering.

What is static exports in Next.js and when is it configured?

expand_more
MediumArchitecture
Static exports (output: 'export' in config) compiles Next.js into a folder containing static HTML, CSS, and JS assets. It is useful when hosting on static providers (S3, GitHub Pages), but disables dynamic features like Server Actions.

Testing

5 Questions

How do you test Server Actions and layout configurations in Next.js applications?

expand_more
MediumTesting
Testing in Next.js requires separating server actions from the components that call them. Since Server Actions are fundamentally asynchronous RPC API endpoints, you can write integration tests that trigger them directly in Node, mock databases, and verify return values. For components that invoke Server Actions, mock router hooks from next/navigation and wrap actions in async blocks. For layout checks, Playwright is preferred to assert real routing updates.

How do you test client components using mocked hook frameworks?

expand_more
MediumTesting
Use React Testing Library. Mock next/navigation hooks using vi.mock('next/navigation', ...) to return mock routers, pathnames, and search parameters, allowing components to run and test actions predictably.

Explain how to handle nested error boundaries inside App Router.

expand_more
MediumTesting
Next.js wraps components in hierarchy boundaries. If an error is thrown in a page, it is caught by error.tsx in the local folder. If that folder lacks one, the error bubbles up to the next parent folder's boundary, terminating at global-error.tsx.

What is Next.js instrumentation and when is it useful?

expand_more
MediumTesting
Instrumentation (instrumentation.ts at the root) runs code once at server startup. It is useful for bootstrapping monitoring tools, initializing connection pools, and registering OpenTelemetry hooks.

How do you measure Web Vitals in Next.js components?

expand_more
MediumTesting
Use the useReportWebVitals client hook. It passes metrics (FCP, LCP, CLS) to a callback function, enabling telemetry metrics export to third-party dashboards like Datadog or Vercel Speed Insights.

Performance

6 Questions

How does the Next.js cache invalidate, and what is revalidation?

expand_more
MediumPerformance
Next.js uses a multi-level cache (Data Cache, Full Route Cache, Router Cache). You invalidate the Data Cache using time-based revalidation (e.g. fetch(url, { next: { revalidate: 60 } })) or on-demand revalidation using revalidatePath('/blog') or revalidateTag('posts') inside Server Actions.

Explain Next.js routing prefetching and how to disable it.

expand_more
MediumPerformance
Next.js automatically prefetches code and data for routes matching next/link components that enter the viewport. To disable prefetching for specific elements (e.g. settings pages that are rarely visited), set the prefetch prop to false: <Link href="/settings" prefetch={false}>.

How do you optimize next/font configurations for custom assets?

expand_more
MediumPerformance
Load fonts locally using localFont from next/font/local and specify src path arrays. This downloads, optimizes, and embeds font binaries inside the pre-rendered styles, preventing layouts from flickering or flashing default fonts.

Explain how image loaders configure custom CDN storage.

expand_more
MediumPerformance
By default, Next.js optimizes images using the local server. For high traffic, configure custom image loaders in next.config.js to delegate image transformation tasks to specialized CDNs like Cloudinary, Imgix, or Akamai.

How does CSS module structure compile under dynamic routes?

expand_more
MediumPerformance
Webpack extracts module imports into scoped styles, appending unique hash IDs to class names. During dynamic route loading, only the CSS modules mapped to active page components are loaded, maximizing download speeds.

Explain the difference between fetch cache options in Next.js.

expand_more
MediumPerformance
In Next.js, fetch defaults to caching requests. You configure caching options using: cache: 'force-cache' (caching data indefinitely), cache: 'no-store' (fetching data dynamically on every request), or setting revalidation bounds.

Rendering Strategies

7 Questions

What is Partial Prerendering (PPR) and how does it optimize core web vitals?

expand_more
HardRendering Strategies
Partial Prerendering (PPR) is an advanced rendering strategy in Next.js that combines static and dynamic rendering. At build time, Next.js pre-compiles a static HTML shell containing headers and layouts. Dynamic components are wrapped in Suspense boundaries. At request time, the static shell is served instantly from edge nodes, resulting in low Time to First Byte (TTFB). The server executes dynamic components in the background and streams the updated HTML chunks over the same connection as they complete.

How does the Next.js Full Route Cache differ from Router Cache?

expand_more
HardRendering Strategies
Full Route Cache is a server-side cache that saves HTML and RSC payloads at build or revalidation time. Router Cache is a client-side, in-memory cache that stores prefetched page segments in the browser during the session. Full Route Cache is shared, whereas Router Cache is local to the active tab.

How do you implement static exports for custom dynamic paths?

expand_more
HardRendering Strategies
Define generateStaticParams() on the dynamic page. This return value dictates the exact static routes generated at build time. Any paths not returned will return 404, preventing runtime render cascades on static servers.

How do you optimize next/image with custom loader engines?

expand_more
HardRendering Strategies
Define loader: 'custom' in next.config.js and export a loader function that builds query parameters. This maps image transformations directly to modern CDN engines, optimizing format delivery without server CPU overhead.

How do you configure dynamic sitemap generation in Next.js?

expand_more
HardRendering Strategies
Create a sitemap.ts file in the root directory and export a sitemap generator function. This function can run database fetches to query dynamic routes, returning a list of URLs that Next.js compiles into sitemap.xml.

Explain the architecture of streaming HTML in Next.js App Router.

expand_more
HardRendering Strategies
Next.js streams HTML pages progressively. It sends the static layout shell first. While the server fetches dynamic data, it keeps the HTTP connection open. Once dynamic sub-components resolve, Next.js streams the final HTML and script tags to swap loaders with real UI.

How do you configure dynamic robots.txt in Next.js?

expand_more
HardRendering Strategies
Create a robots.ts file in the root app/ directory and export a robots configuration function. Next.js dynamically compiles this into a robots.txt path response.

Scalability

6 Questions

Explain Edge Runtime versus Node.js Runtime in Next.js and their architectural trade-offs.

expand_more
HardScalability
Next.js offers two server runtimes: 1. Node.js Runtime: Standard Node execution. Has access to all npm packages, database drivers, and native APIs, but higher start latency. 2. Edge Runtime: Lightweight JavaScript runtime based on V8 engines. Low latency and fast startup, but limited APIs (no fs, child_process, or certain native cryptos). Select Edge for localization or basic middleware, and Node for database queries.

How do you debug hydration mismatches in Next.js production builds?

expand_more
HardScalability
To debug hydration mismatches in production, compare the rendered DOM output against the initial HTML source payload. Hydration mismatches are caused by accessing browser variables (e.g. window, localStorage) during initial render, or using non-deterministic values (like time formatters). Fix them by wrapping client-only components in useEffect trackers.

How do you optimize bundle chunk splits in next.config.js?

expand_more
HardScalability
Configure Webpack module settings in next.config.js using config.optimization.splitChunks. This lets you create custom cache groups for heavy npm dependencies (like chart libraries), improving browser cache efficiency.

Explain the Next.js compilation cycle under Turbopack.

expand_more
HardScalability
Turbopack is a Rust-based bundler. It uses incremental compilation: it only rebuilds files that have changed and compiles them on demand, making development startups and hot-module replacement (HMR) extremely fast.

How do you handle rate-limiting API route handlers in Next.js?

expand_more
HardScalability
Use an in-memory database like Redis. Inside middleware or API handlers, increment request counters mapped to user IP addresses. If request frequency exceeds limits, return a 429 Too Many Requests response.

How do you debug server-side memory leaks in Next.js?

expand_more
HardScalability
Start Next.js in Node inspect mode (NODE_OPTIONS='--inspect' npm run dev). Connect Chrome DevTools to the Node process, capture memory heap snapshots, and run GC commands during load tests to locate retained objects.

Large Application Design

7 Questions

Explain how to secure Server Actions and prevent CSRF / injection vulnerabilities.

expand_more
HardLarge Application Design
To secure Server Actions: 1. Authorization: Verify user sessions inside actions using helper checks. 2. Input Validation: Run input variables through strict validation checks (using Zod schemas) before database execution. 3. Rate Limiting: Apply request rate limits to actions via middleware or custom Redis wrappers to prevent brute force attacks.

How would you design a multi-tenant routing middleware in Next.js at scale?

expand_more
HardLarge Application Design
In multi-tenant setups, check incoming request hostnames inside middleware.ts. Rewrite URLs dynamically (e.g. mapping tenant1.prepedge.com to /tenant1/dashboard using NextResponse.rewrite()). This routes request flows silently without modifying the browser URL.

How would you configure Webpack and Turbopack for large monorepo builds in Next.js?

expand_more
HardLarge Application Design
In monorepos, use transpilePackages: ['@shared/ui', '@shared/utils'] inside next.config.js to instruct the compiler to transpile external workspace dependencies, ensuring TS files and styles compile correctly.

Explain server action database pooling and connection leaks.

expand_more
HardLarge Application Design
Server Actions are executed in a serverless or persistent Node environment. If a connection pool is initialized inside a Server Action callback, every request will create a new pool, leading to database connection exhaustion. Always initialize DB connection pools globally outside the action handler.

How do you prevent data mutation race conditions in Next.js?

expand_more
HardLarge Application Design
Use Server Actions to run database transactions sequentially. Since client actions are asynchronous, wrap forms in optimistic UI states (using useOptimistic) to display updates immediately, and let server updates reconcile final states.

How do you set up distributed session management in Next.js?

expand_more
HardLarge Application Design
Store session state in database records or secure JWT cookies. For serverless backends, use Redis to store session records, allowing multiple server instances to validate requests instantly.

How do you intercept paths in Next.js routing (Parallel Routes)?

expand_more
HardLarge Application Design
Define slots (folders named @folder) inside a layout folder directory. Next.js can render multiple slot directories inside the same layout simultaneously, making dashboard splits and interactive modal overlays clean.

Questions for Other Experience Levels

Freshers (0-1 years)

Core fundamental concepts and frequently asked questions for entry-level developers.

View Questions arrow_forward
Mid-Level (2-5 years)Current Page

Performance bottlenecks, debugging practices, and real-world project scenarios.

Senior (5+ years)

Scale architecture, database design patterns, security, and production system design.

View Questions arrow_forward

Related Interview Topics

Practice Next.js Interview Questions with AI

Reading answers is not enough. Practice explaining these concepts with PrepEdge's AI mock interviews and get surgical feedback on your responses.