All topics

QUESTIONS AND ANSWERS

Next.js

How does App Router turn the file structure into routes and screens?

Folders under app/ represent URL segments; page.tsx defines a page, and layout.tsx defines shared UI that wraps descendant pages. A segment such as [slug] enables dynamic routes. Layouts persist across navigations and can preserve state, so keep in them only what truly needs to be shared. Link supports client-side navigation and route prefetching. Layouts and Pages

How do you receive route and search parameters in App Router?

A dynamic segment such as [slug] provides its parameters to the page; searchParams represents the URL query. In current Next.js versions, params and searchParams are promises in Server Components and are read with await; useParams and useSearchParams are available on the client. Choose the API based on whether the value loads server-side content or only filters state already in the browser. Dynamic Segments and Layouts and Pages

What is the difference between a layout, a template, and a route group?

A layout.tsx wraps child routes and normally preserves state across navigation; template.tsx creates a new instance when navigating through its segment, so it resets local state and reruns effects. A route group such as (marketing) organizes files without adding its name to the URL, and can separate layouts. Navigating between different root layouts triggers a full page load. Layouts and Templates and Route Groups

What are Parallel Routes and Intercepting Routes for?

Parallel Routes, declared with @name slots, let a layout render multiple subroutes at once, such as independent dashboard panels. Intercepting Routes let a route open within the current context — such as a photo in a modal — while the same URL can show a full page on refresh or direct navigation. These features help with multi-region or contextual flows; they require fallback states and direct-navigation behavior to be designed as well. Parallel Routes and Intercepting Routes

What is the difference between Server Components and Client Components?

In App Router, components are Server Components by default: they can read data close to its source and keep secrets on the server, and their component JavaScript isn’t sent to the browser. Use Client Components with 'use client' when you need interactive state, event handlers, lifecycle hooks, or browser APIs. The directive establishes a boundary in the module graph; its imports can also become part of the client bundle. Server and Client Components

What is the RSC payload, and what does it mean to hydrate a page?

On the server, Next.js produces a React Server Components payload containing the rendered result of Server Components, references to Client Components, and props that cross that boundary. On the initial load, it also generates HTML that the browser can display before the page is interactive; React hydrates Client Components by attaching their event handlers. The payload and props aren’t a place for secrets: any data serialized to the client can be inspected by the recipient. Server and Client Components

What rendering options does App Router offer, and how do they relate to caching?

A page can prerender content during the build or resolve parts that depend on request-time data. Rendering and caching are related but distinct: a dynamic page can reuse some cached data, and a prerendered page can contain dynamic sections. Reading cookies, headers, or search parameters can require request-time data. Don’t assume the entire route has the same behavior; verify the rules for the project’s version and configuration. Rendering and Dynamic APIs

When are streaming, loading.tsx, and Suspense useful?

Streaming lets Next.js send parts of a route as they become ready instead of waiting for all data to finish. loading.tsx creates a loading UI for a segment and acts as a Suspense boundary; a boundary using the Suspense component closer to a slow operation can let the rest of the page appear without blocking. Design the fallback as a useful representation of what’s loading, and place the boundary around the section that can actually wait. Data Fetching and Streaming and loading.js

How do you fetch data on the server and avoid request waterfalls?

A Server Component can use fetch, an ORM, or a database client in an asynchronous function. When two requests don’t depend on each other, start them in parallel instead of waiting for one before starting the other; to avoid repeating a read during a render, use the memoization tools appropriate for that kind of access. Keep secrets and database credentials in server-only modules. Fetching Data and Data Security

How do you choose a cache policy and keep data fresh?

Decide what can be shared and for how long before caching a read. The API and defaults for fetch, render caching, and revalidation have changed across versions; declaring and verifying them avoids relying on assumptions. User-specific data shouldn’t end up in a shared cache unless its key and isolation rules explicitly account for that. Caching and production checklist

What changes with Cache Components, and how do you use use cache?

In Next.js 16, Cache Components is enabled with cacheComponents in the configuration; use cache then marks a route, component, or function as cacheable, and cacheLife defines its lifetime. cacheTag lets you invalidate by tag. The previous model uses different segment options and APIs, so don’t mix examples from both models without checking whether the flag is enabled and which version is pinned. Data that depends on cookies or other request-specific values shouldn’t accidentally become shared output. Cache Components, use cache, and cacheComponents

How do you update the cache after a mutation?

With Cache Components, cacheTag associates a tag with cached data; updateTag can invalidate it from a Server Action, while revalidateTag can revalidate it with stale-while-revalidate semantics. revalidatePath invalidates data associated with a route. Choose based on whether the user needs to see the new value immediately or can tolerate older content while it refreshes; available APIs and behavior depend on the cache model and version. Revalidating

How does Link navigate, and when should you use useRouter?

Link extends an anchor element with client-side transitions and prefetching, depending on the route and configuration. Shared layouts can remain mounted; dynamic routes can show their loading UI while the server resolves them. Use useRouter for imperative navigation from a Client Component when the flow calls for it, and prefer declarative links for normal, accessible navigation. Linking and Navigating and useRouter

Where should UI state, URL state, and durable data live?

Temporary interaction state, such as whether a menu is open, belongs in the Client Component that controls it. State that must be shared or survive a reload usually belongs in the URL, on the server, or in persistent storage, depending on the use case. Use search parameters for filters or pagination that should be linkable; don’t turn every value into global state or store private information in the browser. React state and Next.js search params

What are Server Actions, and how should a form be processed securely?

A Server Action is an asynchronous function that runs on the server and can be invoked from a client UI or form. It can validate input, perform a mutation, and revalidate the associated UI or data. Browser-side validation improves the experience, but it doesn’t replace server-side validation; treat every Action as an entry point that can receive untrusted requests. Mutating Data and Data Security

When should you use a Route Handler instead of a Server Action?

A Route Handler (route.ts) exposes an HTTP endpoint for methods such as GET or POST, which is useful for an API consumed by other clients, webhooks, or integrations. A Server Action fits mutations tied to an app interaction and its UI update. You don’t need to create an endpoint for every internal read: a Server Component can call the data layer directly. In both cases, authenticate, authorize, and validate input on the server. Route Handlers and Mutating Data

How should you handle errors, missing routes, and loading states?

loading.tsx shows a fallback while work is pending; error.tsx defines an error boundary for a route segment and must be a Client Component; not-found.tsx represents a missing resource and can be triggered with notFound(). Distinguish expected errors — such as rejected validation — from unexpected failures, and don’t expose stack traces or sensitive data to users. When possible, provide a clear way to retry or go back. Error Handling and notFound

How should you choose between unit, component, and end-to-end tests?

Unit tests cover isolated functions and logic; component tests exercise local UI interactions; end-to-end tests run real flows in a browser and server environment. Next.js documents Jest, Vitest, Playwright, and Cypress for different uses. For asynchronous Server Components, the documentation notes that some tools lack full support and recommends end-to-end tests for integrated behavior. Testing and Vitest

How do you separate authentication, session management, and authorization?

Authentication verifies who a person is; session management maintains that state across requests; authorization decides which resources or actions they can use. Hiding a link or redirecting at a superficial layer doesn’t protect data: verify permissions near data access and in every action that changes information. For a new app, Next.js recommends a data access layer that centralizes authorization and returns only permitted fields. Authentication and Data Security

What controls should protect Server Actions, secrets, and transferred data?

Treat every Server Action and Route Handler as a public entry point: authenticate, authorize the operation, and validate every value on the server. A data access layer centralizes those checks and returns minimal DTOs to avoid exposing secrets or private fields. Keep secret variables on the server; only values intentionally made public should use the NEXT_PUBLIC_ prefix. Encrypted action references or hard-to-guess IDs don’t replace authorization. Data Security and Authentication

How can you reduce XSS risks and prevent data exposure through caching?

Don’t insert untrusted HTML without sanitizing it; React escapes text by default, but raw HTML APIs remove that protection. A Content Security Policy (CSP) limits the allowed origins for scripts, styles, and other resources, which can reduce the impact of some injection attacks. Also avoid caching private data across users and don’t serialize secrets from Server Components to Client Components. Content Security Policy and Data Security

How do you limit client-side JavaScript and hydration cost?

Keep parts that don’t need browser interaction as Server Components, and mark the smallest interactive boundary possible with 'use client'. Every import within that boundary can increase the client bundle. Keep client providers as deep in the tree as practical, and lazy-load large components or libraries when bundle analysis shows it would help. Server and Client Components and production checklist

Which image, font, and script optimizations should you check before release?

next/image can optimize images and reserve their layout space to reduce shifts; next/font can serve fonts with the app’s assets, and next/script controls how third-party scripts load. These aren’t substitutes for measurement: check size, formats, priority, and effects on Core Web Vitals. Analyze bundles and measure a production build, since development behavior doesn’t fully reflect what users experience. Production checklist, Image Optimization, and Font Optimization

How do you diagnose differences between development and production, such as a hydration error?

First reproduce the problem with a production build; routes and caches behave differently during development. A hydration error means the initial HTML and the client’s first render don’t match, often because of time, randomness, browser APIs, or mutable data during the initial render. Inspect the message and affected segment, and move browser-only access to a Client Component after hydration when appropriate. React hydration and Next.js production checklist

What do next build, TypeScript, and environment variables check?

next build creates a production build and catches compilation errors that may not appear in the development server. Also run tests and type checks in CI; keep secrets out of source control and remember that NEXT_PUBLIC_ values are exposed to the client in the build. Then run next start to test the artifact in a production-like environment. Production checklist and Environment Variables

What should you validate when deploying Next.js to Node, Docker, or a platform?

Choose a runtime that supports the features you use: Server Actions, server rendering, streaming, revalidation, and caching aren’t available on every static host. Current documentation describes the Node.js server and Docker, and recommends a reverse proxy when self-hosting. Across multiple instances, coordinate cache storage and invalidation; during rolling deployments, consider version skew between client and server. Self-Hosting and Deploying to Platforms

In an interview, how would you fix a dashboard that shows stale data or another user’s data?

First, I’d check whether the response came from a shared cache and what data forms its key; private data must be isolated by user or excluded from shared caching. I’d centralize authorization and reads in the data layer, return a minimal DTO, and test access as different users. Then I’d define the required freshness and invalidate after mutations, and reproduce the case with a production build and logs that don’t reveal sensitive information. Data Security and Revalidating

Versions: The cited pages cover the current Next.js App Router. In current versions, page params and searchParams are asynchronous; older code may use different signatures. Cache Components was introduced in Next.js 16 through the cacheComponents option and changes the cache model; fetch, revalidation, and API behavior depend on the version and that configuration. Dynamic Segments, Cache Components, and migrating to Cache Components