Appearance
Next.js Essentials
64. What is Next.js, and when would you choose it over a Vite SPA?
The short answer
Next.js is a React framework: it adds file-based routing, rendering on the server, static generation, data fetching on the server, API endpoints, image and font optimisation, and a production build and server, all configured for you. Choose it when pages must be fast on first load and indexed by search engines, such as a shop, a marketing site or a blog, or when you want server-side data access in the same project. A Vite single-page app is simpler and enough for apps behind a login, such as dashboards and admin tools, where SEO does not matter.
| Vite SPA | Next.js | |
|---|---|---|
| Where HTML is made | In the browser, after JavaScript loads | On the server or at build time, then hydrated |
| First load and SEO | Slower first paint; crawlers may see an empty page | Fast first paint; full HTML for crawlers |
| Routing | A library such as React Router | Files and folders in app/ |
| Backend code | Separate API | Server Components, Server Actions, route handlers in the same project |
| Hosting | Any static host or CDN | A Node.js server, serverless functions, or a static export |
| Complexity | Lower | Higher: two environments, caching rules |
A sensible rule of thumb:
- Public, content-heavy, SEO matters → Next.js, or another server-rendering framework such as React Router's framework mode.
- Logged-in app, rich interactivity, a separate backend already exists → Vite SPA (question 54).
Current version, late 2025 onwards: Next.js 16 made Turbopack the default bundler, introduced Cache Components with the use cache directive, and renamed middleware.ts to proxy.ts. It requires Node.js 20.9 or newer.
65. What are CSR, SSR, SSG and ISR?
The short answer
They are four answers to "when is the page's HTML made?". Client-side rendering, CSR, builds it in the browser with JavaScript. Server-side rendering, SSR, builds it on the server for every request, so data is always fresh. Static site generation, SSG, builds it once at build time and serves the same file to everyone, which is the fastest. Incremental static regeneration, ISR, serves static pages but rebuilds them in the background after a set time or when told to, giving static speed with reasonably fresh data.
| Strategy | HTML is made | Data freshness | Speed | Good for |
|---|---|---|---|---|
| CSR | In the browser | Live | Slow first paint | Dashboards behind a login |
| SSR | On each request | Live | Fast paint, server work per request | Personalised pages, search results |
| SSG | At build time | As of the last build | Fastest: a file from a CDN | Docs, blog posts, landing pages |
| ISR | At build, then rebuilt periodically | Minutes old | Very fast | Product pages, category listings |
In the App Router, you mostly choose by how the page fetches data:
tsx
// app/products/[slug]/page.tsx
export const revalidate = 300 // (1)
export default async function ProductPage({ params }: { params: Promise<{ slug: string }> }) {
const { slug } = await params // (2)
const product = await getProduct(slug) // (3)
return <ProductView product={product} />
}
export async function generateStaticParams() { // (4)
const top = await getTopProducts(100)
return top.map((p) => ({ slug: p.slug }))
}- ISR: the page is static, and regenerated at most every 300 seconds.
paramsis a promise in recent versions, so it is awaited.- Data is fetched on the server, inside the component (question 68).
- Pre-build the top 100 product pages at build time; others are built on their first request.
Reading cookies or headers, for example to personalise, makes a page dynamic, rendered per request. Next.js also streams: the static shell of a page is sent at once and slower parts arrive as they are ready, through Suspense boundaries.
66. What is hydration, and what causes hydration errors?
The short answer
Hydration is React taking over HTML that was rendered on the server: the browser shows the server's HTML immediately, then React runs the same components in the browser, attaches event handlers to the existing elements, and from then on the page is interactive. A hydration error happens when the HTML React produces in the browser does not match the server's HTML, for example because of the current time, random values, window checks, browser extensions, or invalid nesting such as a <div> inside a <p>.
A typical mismatch, and the fix:
tsx
'use client'
function DeliveryEstimate() {
return <p>Order in the next {60 - new Date().getMinutes()} minutes</p> // (1) mismatch
}
function DeliveryEstimateFixed() {
const [minutes, setMinutes] = useState<number | null>(null)
useEffect(() => setMinutes(60 - new Date().getMinutes()), []) // (2)
return <p>{minutes === null ? 'Order soon' : `Order in the next ${minutes} minutes`}</p>
}- The server's clock and the browser's clock give different numbers, so the text differs.
- Render the same placeholder on both sides, then fill in the browser-only value in an effect, which runs only in the browser.
| Cause | Fix |
|---|---|
Date.now(), Math.random() during render | Compute in an effect, or pass from the server |
typeof window !== 'undefined' branches | Use an effect, or load the component only on the client |
| Locale or time-zone formatting | Format on the server with a fixed time zone, or in an effect |
Invalid HTML nesting, such as <div> inside <p> | Fix the markup; browsers rearrange invalid HTML |
| Browser extensions that edit the page | Usually harmless; check in a clean profile |
67. What are Server Components and Client Components?
The short answer
In the App Router, components are Server Components by default: they run only on the server, can be async, can read databases and secrets directly, and send only their rendered result to the browser, with none of their code. Client Components are marked with 'use client' at the top of the file; they also render on the server for the first HTML, but their code is sent to the browser so they can use state, effects, event handlers and browser APIs. Keep most of the page as Server Components and make only the interactive pieces Client Components.
'use client' and are hydrated in the browser to handle interaction.tsx
// app/products/[slug]/page.tsx: a Server Component
import { notFound } from 'next/navigation'
import { db } from '@/lib/db'
import { AddToCartButton } from './AddToCartButton'
export default async function ProductPage({ params }: { params: Promise<{ slug: string }> }) {
const { slug } = await params
const product = await db.product.findUnique({ where: { slug } }) // (1)
if (!product) notFound()
return (
<article>
<h1>{product.name}</h1>
<p>{product.description}</p>
<AddToCartButton sku={product.sku} /> {/* (2) */}
</article>
)
}
// app/products/[slug]/AddToCartButton.tsx: a Client Component
'use client' // (3)
import { useState } from 'react'
export function AddToCartButton({ sku }: { sku: string }) {
const [added, setAdded] = useState(false) // (4)
return <button onClick={() => { addToCart(sku); setAdded(true) }}>{added ? 'Added ✓' : 'Add to cart'}</button>
}- Direct database access in the component: no API route needed, and the query code never reaches the browser.
- Rendering a Client Component from a Server Component is fine. Props passed across must be serialisable, such as strings and plain objects, not functions.
'use client'marks this file, and everything it imports, as client code.- State and events work only in Client Components.
| Server Component | Client Component | |
|---|---|---|
| Runs | Server only | Server for first HTML, then browser |
| JavaScript sent to the browser | None | Its code |
async, database, secrets | Yes | No |
useState, useEffect, onClick, window | No | Yes |
| Can import the other kind | Yes, Client Components | Only Server Components passed in as children |
Keep secrets on the server. Code in a Server Component is not sent to the browser, but anything you pass as props to a Client Component is. Never pass a full user record with a password hash down as a prop.
Keep frameworks patched. Server Components run framework code on your server for every request; in December 2025 a critical remote code execution flaw in React Server Components affected Next.js App Router apps, fixed by upgrading React and Next.js.
68. How does data fetching and caching work in the App Router?
The short answer
You fetch data directly inside async Server Components with await, using fetch or a database client, so data is ready when the HTML is built. Requests for the same data within one render are de-duplicated. Whether results are cached between requests is your choice: in recent versions, fetches are not cached by default, and with Cache Components in Next.js 16 you mark functions or components with 'use cache', give them a lifetime, tag them, and expire the tag after a change, with updateTag, revalidateTag or revalidatePath.
tsx
// lib/products.ts
import { cacheLife, cacheTag } from 'next/cache'
export async function getCategory(slug: string) {
'use cache' // (1)
cacheLife('hours') // (2)
cacheTag(`category-${slug}`) // (3)
return db.category.findUnique({ where: { slug }, include: { products: true } })
}
// app/admin/actions.ts
'use server'
import { updateTag } from 'next/cache'
export async function updateProduct(id: string, data: ProductInput) {
const product = await db.product.update({ where: { id }, data })
updateTag(`category-${product.categorySlug}`) // (4)
}'use cache'caches the function's result across requests. This needs thecacheComponentsoption enabled innext.config.ts.- A lifetime preset for how long the entry stays fresh.
- A tag, a label to find this entry later.
- After an update, expire the tag, so the next request rebuilds the category with fresh data. In Next.js 16,
updateTagdoes this immediately inside a Server Action, so the editor sees their own change at once, whilerevalidateTag(tag, 'max')marks the entry stale and refreshes it in the background.
Fetching patterns that matter:
| Pattern | Why |
|---|---|
| Fetch in the component that needs the data | Requests in one render are de-duplicated, so no prop drilling of data |
| Start independent fetches together | Promise.all, to avoid server-side waterfalls (question 58) |
Wrap slow parts in <Suspense> | The rest of the page streams first |
| Client-side data that changes live | TanStack Query in a Client Component (question 47) |
Caching rules have changed across versions, which is why interviewers ask about them: earlier versions cached fetch by default, later ones stopped, and Next.js 16 moved to explicit 'use cache'. Say which version you mean.
69. What are Server Actions and route handlers?
The short answer
A Server Action is an async function marked with 'use server' that runs on the server but can be called from a component, typically as a form's action, so you handle form submissions and mutations without writing an API endpoint; Next.js creates the endpoint for you. A route handler is a file, app/api/…/route.ts, exporting functions such as GET and POST that respond to HTTP requests, for webhooks, mobile apps and other clients that need a normal HTTP API.
A Server Action for a newsletter form:
tsx
// app/actions.ts
'use server'
import { z } from 'zod'
const Email = z.string().email()
export async function subscribe(_prev: { error?: string }, formData: FormData) {
const parsed = Email.safeParse(formData.get('email')) // (1)
if (!parsed.success) return { error: 'Please enter a valid email' }
const user = await getCurrentUser() // (2)
await db.subscriber.upsert({ where: { email: parsed.data }, create: { email: parsed.data, userId: user?.id }, update: {} })
return {}
}
// app/Newsletter.tsx
'use client'
import { useActionState } from 'react'
import { subscribe } from './actions'
export function Newsletter() {
const [state, action, pending] = useActionState(subscribe, {}) // (3)
return (
<form action={action}>
<input name="email" type="email" />
<button disabled={pending}>Subscribe</button>
{state.error && <p role="alert">{state.error}</p>}
</form>
)
}- Validate on the server. A Server Action is a public HTTP endpoint; anyone can call it with any data.
- Check who is calling inside the action when it matters. Being called from your form proves nothing about the user.
- Wire it to the form with React 19's
useActionState(question 22).
A route handler for a payment webhook:
ts
// app/api/webhooks/payments/route.ts
export async function POST(request: Request) {
const signature = request.headers.get('payment-signature')
const body = await request.text()
if (!verifySignature(body, signature)) return new Response('bad signature', { status: 400 })
await markOrderPaid(JSON.parse(body).orderId)
return Response.json({ received: true })
}| Server Action | Route handler | |
|---|---|---|
| Called from | Your own components and forms | Any HTTP client |
| Defined | A function with 'use server' | route.ts exporting GET, POST, … |
| Good for | Mutations from your UI | Webhooks, public APIs, mobile apps |
70. How does routing work in the App Router?
The short answer
Folders inside app/ define URL segments, and a page.tsx file in a folder makes that path a page. layout.tsx wraps all pages below it and keeps its state across navigation, loading.tsx shows a Suspense fallback, error.tsx is an error boundary, and not-found.tsx handles missing pages. Square brackets make dynamic segments, such as [slug], and parentheses make route groups that organise files without affecting the URL. <Link> navigates on the client and prefetches pages in view.
text
app/
layout.tsx root layout: <html>, header, footer
page.tsx /
(shop)/ a route group: not part of the URL
products/
page.tsx /products
[slug]/
page.tsx /products/teapot
loading.tsx fallback while the page loads
error.tsx error boundary for this segment
account/
layout.tsx shared layout for /account/*
orders/
page.tsx /account/orders
api/
webhooks/payments/route.ts POST /api/webhooks/payments| File | Role |
|---|---|
page.tsx | The content for that path |
layout.tsx | Shared wrapper; stays mounted while children change |
loading.tsx | Suspense fallback for the segment (question 26) |
error.tsx | Error boundary for the segment (question 30), a Client Component |
not-found.tsx | Shown when notFound() is called |
route.ts | An HTTP endpoint (question 69) |
Navigation: <Link href="/products/teapot"> changes the page without a full reload and prefetches linked pages that appear on screen. In Client Components, useRouter(), usePathname() and useSearchParams() give programmatic access.
71. What is proxy.ts, formerly middleware, used for?
The short answer
proxy.ts, called middleware.ts before Next.js 16, is code that runs before a request reaches a page or route, at the network boundary. It can redirect, rewrite to another path, set headers and cookies, or block a request, based on the URL, headers or cookies. Typical uses are redirecting signed-out users to the login page, choosing a language, A/B test assignment and adding security headers. Keep it small and fast, and never rely on it as the only authorisation check.
ts
// proxy.ts, at the project root
import { NextResponse, type NextRequest } from 'next/server'
export function proxy(request: NextRequest) {
const session = request.cookies.get('session')?.value
if (!session && request.nextUrl.pathname.startsWith('/account')) { // (1)
const login = new URL('/login', request.url)
login.searchParams.set('next', request.nextUrl.pathname)
return NextResponse.redirect(login)
}
const res = NextResponse.next()
res.headers.set('X-Frame-Options', 'DENY') // (2)
return res
}
export const config = { matcher: ['/account/:path*', '/checkout/:path*'] } // (3)- A quick redirect for users without a session cookie.
- Adding a header to every matching response.
- The matcher limits which paths run the proxy, so static files are not slowed down.
Why it is not enough for security. It only checks that a cookie exists, quickly, before the page. The page, Server Action or API must still verify the session and the user's permissions on the server, because requests can reach them in other ways, and a flaw in proxy logic would otherwise open everything. In March 2025, a vulnerability let attackers skip Next.js middleware entirely with a crafted header, which is exactly why the real check belongs in the data layer.