Skip to content

Interview PrepNext.js · Core

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 SPANext.js
Where HTML is madeIn the browser, after JavaScript loadsOn the server or at build time, then hydrated
First load and SEOSlower first paint; crawlers may see an empty pageFast first paint; full HTML for crawlers
RoutingA library such as React RouterFiles and folders in app/
Backend codeSeparate APIServer Components, Server Actions, route handlers in the same project
HostingAny static host or CDNA Node.js server, serverless functions, or a static export
ComplexityLowerHigher: 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.

StrategyHTML is madeData freshnessSpeedGood for
CSRIn the browserLiveSlow first paintDashboards behind a login
SSROn each requestLiveFast paint, server work per requestPersonalised pages, search results
SSGAt build timeAs of the last buildFastest: a file from a CDNDocs, blog posts, landing pages
ISRAt build, then rebuilt periodicallyMinutes oldVery fastProduct 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 }))
}
  1. ISR: the page is static, and regenerated at most every 300 seconds.
  2. params is a promise in recent versions, so it is awaited.
  3. Data is fetched on the server, inside the component (question 68).
  4. 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>.

① serverrenders HTML② paintvisible, not clickable③ JS loadssame components run④ hydratedinteractiveReact's output must match the server's HTML,or it warns and re-renders that part
Show first, wire up second. ① The server sends ready-made HTML. ② The user sees it at once. ③ The JavaScript arrives and React renders the same components. ④ React attaches handlers to the existing elements and the page responds.

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>
}
  1. The server's clock and the browser's clock give different numbers, so the text differs.
  2. Render the same placeholder on both sides, then fill in the browser-only value in an effect, which runs only in the browser.
CauseFix
Date.now(), Math.random() during renderCompute in an effect, or pass from the server
typeof window !== 'undefined' branchesUse an effect, or load the component only on the client
Locale or time-zone formattingFormat 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 pageUsually 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.

ProductPageserver: reads DBProductDetailsserverAddToCartButton'use client'ReviewListserverImageGallery'use client'purple: runs only on the servergreen: code also sent to the browser
Server by default, client where it clicks. Purple components fetch data and render on the server and ship no JavaScript. Green ones are marked '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>
}
  1. Direct database access in the component: no API route needed, and the query code never reaches the browser.
  2. Rendering a Client Component from a Server Component is fine. Props passed across must be serialisable, such as strings and plain objects, not functions.
  3. 'use client' marks this file, and everything it imports, as client code.
  4. State and events work only in Client Components.
Server ComponentClient Component
RunsServer onlyServer for first HTML, then browser
JavaScript sent to the browserNoneIts code
async, database, secretsYesNo
useState, useEffect, onClick, windowNoYes
Can import the other kindYes, Client ComponentsOnly 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)
}
  1. 'use cache' caches the function's result across requests. This needs the cacheComponents option enabled in next.config.ts.
  2. A lifetime preset for how long the entry stays fresh.
  3. A tag, a label to find this entry later.
  4. After an update, expire the tag, so the next request rebuilds the category with fresh data. In Next.js 16, updateTag does this immediately inside a Server Action, so the editor sees their own change at once, while revalidateTag(tag, 'max') marks the entry stale and refreshes it in the background.

Fetching patterns that matter:

PatternWhy
Fetch in the component that needs the dataRequests in one render are de-duplicated, so no prop drilling of data
Start independent fetches togetherPromise.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 liveTanStack 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>
  )
}
  1. Validate on the server. A Server Action is a public HTTP endpoint; anyone can call it with any data.
  2. Check who is calling inside the action when it matters. Being called from your form proves nothing about the user.
  3. 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 ActionRoute handler
Called fromYour own components and formsAny HTTP client
DefinedA function with 'use server'route.ts exporting GET, POST, …
Good forMutations from your UIWebhooks, 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
FileRole
page.tsxThe content for that path
layout.tsxShared wrapper; stays mounted while children change
loading.tsxSuspense fallback for the segment (question 26)
error.tsxError boundary for the segment (question 30), a Client Component
not-found.tsxShown when notFound() is called
route.tsAn 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)
  1. A quick redirect for users without a session cookie.
  2. Adding a header to every matching response.
  3. 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.

Combine chapters into one PDF

Pick the chapters you want. They print in the order you pick them.

Interview Prep
React, Vite & Next.js
React
State and data
Vite
Next.js
Other topics
Nothing picked yet