Next.js
Recruitment and knowledge question base. Filter, search and test your knowledge.
mediumnextjsrenderingssr+1
Answer
SSR renders HTML on each request so it can use per‑request data like auth and headers, but costs server time. SSG pre‑renders at build time and serves static files, making pages very fast and cacheable, but data is as fresh as your build or ISR revalidate window.
mediumapp-routerserver-componentsclient-components+1
Answer
Server Components render on the server, can access backend resources directly, and don’t ship their code to the browser; they can’t use React client hooks. Client Components are marked with 'use client', run in the browser, support hooks/state and interactivity, but add to the JS bundle.
easyroutinglayoutssegments+1
Answer
In the App Router each folder is a route segment that maps to the URL. A layout.tsx in a segment wraps all child pages and layouts below it; nested layouts compose and can persist between navigations, enabling shared UI like navbars or sidebars.
mediumisrssgcaching+1
Answer
ISR lets you serve a statically generated page but revalidate it in the background after a set interval. Users get cached content fast, and when it’s stale Next.js regenerates the page without a full redeploy. Use it for mostly static pages with occasional updates.
hardcachingrevalidationfetch+1
Answer
Next.js caches server fetches by default based on request and route settings. You can opt out with cache: 'no-store' or set a revalidate time to refresh data periodically. revalidatePath/revalidateTag let you invalidate cached pages or data on demand.
export const revalidate = 60
const res = await fetch('https://api.example.com/posts', { next: { revalidate: 60 } })
const posts = await res.json()easynextjsapp-routerrsc+1
Answer
Server Components render on the server, can access backend resources directly, and don’t support client hooks/events. Client Components run in the browser, can use `useState/useEffect` and event handlers, but add JS to the bundle.
easyuse-clientclient-componentreact
Answer
It marks a file as a Client Component boundary. The component (and its dependencies) are bundled for the browser, so you can use hooks and event handlers there.
easyroutingdynamic-routeparams
Answer
Create a folder like `app/posts/[id]/page.tsx`. In a Server Component, read it from the `params` prop; in a Client Component you can use `useParams()`.
export default function Page({ params }: { params: { id: string } }) {
return <div>Post id: {params.id}</div>
}mediumssrssgisr+1
Answer
SSR renders on every request, SSG renders at build time, and ISR regenerates pages in the background after a revalidate interval. It’s a trade-off between freshness, speed, and build time.
mediumfetchrevalidatecache
Answer
In Server Components, Next can cache `fetch()` results and dedupe requests. You can opt out with `cache: 'no-store'` or set revalidation with `next: { revalidate: seconds }` to control freshness.
const res = await fetch('https://example.com/api', {
next: { revalidate: 60 },
})mediummiddlewareedgeredirect
Answer
Middleware runs before a route (often at the edge) and can redirect/rewrite (e.g., locale routing, auth gates). It should be lightweight and has runtime limitations compared to full Node.js (not all APIs are available).
hardhydrationssrreact+1
Answer
It happens when the server-rendered HTML differs from the client’s first render (e.g., `Math.random()`, `Date.now()`, `window` branches, locale formatting). Fix by making initial render deterministic or moving client-only values to `useEffect`/client components.
hardstreamingsuspenseloading
Answer
With streaming, the server can send HTML in chunks as data resolves. `Suspense` boundaries (and `loading.tsx`) show a fallback while a segment loads, improving perceived performance and TTFB.
hardserver-actionssecurityvalidation
Answer
Server Actions are functions that run on the server and can be invoked from forms or client components. Treat them like public endpoints: validate input and enforce auth/authorization on the server (don’t rely on the UI).
hardperformancebundlingnext-image
Answer
Keep as much as possible in Server Components (less JS), and split heavy client code with dynamic imports. Also use `next/image` for optimized images and avoid huge providers on the client.
easynextjslinkrouting
Answer
`Link` enables client-side navigation (no full page reload) and can prefetch routes, making navigation faster and preserving app state. Use `<a>` mainly for external links.
mediumapp-routeruseRouternavigation
Answer
In a Client Component, use `useRouter()` from `next/navigation` and call `router.push()` / `router.replace()`. In Server Components you usually redirect with `redirect()`.
'use client'
import { useRouter } from 'next/navigation'
export function GoButton() {
const router = useRouter()
return (
<button onClick={() => router.push('/en')}>Go</button>
)
}mediumparamssearch-paramshooks+1
Answer
`useParams()` reads dynamic route params (like `[id]`), and `useSearchParams()` reads the query string. Both are client hooks, so they must be used in Client Components.
hardedgeruntimenodejs+1
Answer
Edge runtime runs closer to users and can reduce latency for lightweight logic (redirects, simple auth). Node.js runtime is more flexible (full Node APIs, heavier dependencies) and is better for complex server work like DB drivers and heavy computation.
harddata-fetchingpromise-allsuspense+1
Answer
Start independent requests in parallel (e.g., `Promise.all`) instead of awaiting sequentially, and use `Suspense` boundaries to stream UI as data resolves. This improves total latency and perceived performance.
easycode-splittingdynamic-importperformance
Answer
Code splitting loads code only when needed instead of shipping one big bundle. `next/dynamic` lets you lazy-load heavy components (and optionally disable SSR for them), improving initial load performance.
mediumcookiesheadersserver-components
Answer
Use `cookies()` and `headers()` from `next/headers` in a Server Component. They read the incoming request on the server; in the browser you read cookies differently (and headers aren’t available the same way).
import { cookies, headers } from 'next/headers'
export default function Page() {
const cookieStore = cookies()
const theme = cookieStore.get('theme')?.value
const ua = headers().get('user-agent')
return <div>{theme} {ua}</div>
}mediumroute-handlersapiapp-router
Answer
A Route Handler is a server endpoint inside the App Router (e.g., `app/api/x/route.ts`). Use it when you need a custom HTTP API (webhooks, file uploads, public endpoints) or when a client must call via fetch.
hardserver-actionsroute-handlerssecurity+1
Answer
Use Server Actions for server-only mutations tied to forms/UI (you still validate and authorize). Use Route Handlers when you need a general HTTP API (public clients, webhooks, third parties, custom methods/headers) or non-form flows like uploads.
hardssrdynamiccache+1
Answer
If a route depends on per-request data (cookies/headers/auth), it must be dynamic. You can force it by using `fetch(..., { cache: 'no-store' })`, reading `cookies()/headers()`, or setting `export const dynamic = 'force-dynamic'`.
easynextjsimagesperformance+1
Answer
`next/image` optimizes images automatically: it serves the right size, supports modern formats, lazy-loads by default, and helps prevent layout shifts when you provide dimensions. It improves performance compared to shipping one huge image everywhere.
mediumnextjsmetadataseo+1
Answer
`generateMetadata` lets you create per-route SEO metadata (title/description/open graph) based on params or fetched data. It runs on the server, so you can generate correct metadata for dynamic routes (e.g., a product page) without duplicating logic.
mediumnextjsenvsecurity+1
Answer
Only variables prefixed with `NEXT_PUBLIC_` are exposed to the browser bundle. Variables without that prefix are server-only. Rule of thumb: never put secrets (API keys, DB passwords) into `NEXT_PUBLIC_` variables.
hardnextjsrouterrefresh+1
Answer
`router.refresh()` triggers a re-render of the current route and re-fetches Server Components data (respecting caching). Use it after a mutation (often after a Server Action) when you need the server-rendered UI to reflect the latest data without a full page reload.
hardnextjsauthcookies+1
Answer
Keep sessions in httpOnly cookies and validate them on the server (Server Components and Route Handlers). Use middleware mainly for routing/redirects, but still enforce auth in server code. Avoid relying only on client checks, and be careful with static rendering when content depends on the user.
easynextjsapp-routererror-boundary+1
Answer
`error.tsx` is a route-segment error boundary UI for runtime errors and can show a fallback with a reset action. `not-found.tsx` is rendered when you call `notFound()` or a route can’t be resolved, to show a 404-like page for that segment.
mediumnextjsroutingroute-groups+1
Answer
Route Groups let you group routes and share layouts without affecting the URL path. The folder name in parentheses is not part of the route. It’s useful for organizing large apps (e.g., separate marketing vs app) while keeping clean URLs.
mediumnextjsfontsperformance+1
Answer
`next/font` helps you load fonts in an optimized way (self-hosting, automatic CSS, optional subsetting and preloading). It reduces CLS by making font loading more predictable and avoiding late “font swap” surprises that change text metrics.
hardnextjsreacthydration+1
Answer
It happens when the server renders one UI (e.g., light icon) but the client renders another after reading localStorage or system theme, so HTML differs. Fixes: make the server know the theme (cookie), or render theme-dependent UI only after mount (client-side), or use a stable placeholder and update it in `useEffect` (optionally with `suppressHydrationWarning`).
hardnextjsserver-componentsclient-components+1
Answer
Keep the browser-only code in a Client Component (`'use client'`). If the library touches `window` at import time, load it with `dynamic(() => import(...), { ssr: false })`. Avoid importing browser-only modules from Server Components, and keep the client boundary as small as possible to limit shipped JS.
easynextjsserver-componentsclient-components+1
Answer
Server Components are the default in the App Router and run on the server, so they’re great for data fetching and reducing client JS. Client Components are needed for state, effects, event handlers, or browser APIs. Use `'use client'` only where necessary.
mediumnextjsserver-actionsmutations+1
Answer
Server Actions are functions that run on the server and can be invoked from forms or client components. They’re useful for mutations without building a separate API endpoint. Common restrictions: they must be async, arguments must be serializable, and they can’t access browser‑only APIs.
mediumnextjsloadingsuspense+1
Answer
`loading.tsx` provides a route‑segment loading UI that is shown while the segment is being streamed or suspended. It works with React Suspense and lets users see partial UI earlier instead of waiting for the whole page.
mediumnextjsssgdynamic-routes+1
Answer
`generateStaticParams` tells Next.js which dynamic route params to prebuild at build time (SSG). It returns a list of params for the segment. Routes not returned can be rendered on demand depending on your dynamic/SSG settings.
hardnextjscacherevalidate+1
Answer
`revalidatePath` invalidates cached data for a specific route path; `revalidateTag` invalidates all cached fetches tagged with that tag. They’re used after mutations (often in Server Actions) to refresh server‑rendered data without a full reload.
easynextjsroute-handlersapi+1
Answer
You create a `route.ts`/`route.js` file and export HTTP methods like `GET`, `POST`. Handlers use the Web `Request`/`Response` APIs. They’re used for custom APIs, webhooks, or backend logic without a separate server.
export async function GET() {
return Response.json({ ok: true })
}mediumnextjsmiddlewareedge+1
Answer
Middleware runs before a request is completed (often at the edge) and is great for redirects, rewrites, and auth gating. Limitations: it runs in an Edge‑like runtime (no Node‑specific APIs), should be fast, and is not a place for heavy DB access.
easynextjslinkprefetch+1
Answer
`next/link` can prefetch routes in the viewport to make navigation faster. You can disable it with `prefetch={false}` if it’s unnecessary or too costly. Prefetching usually happens in the background and respects caching.
mediumnextjsrenderingstatic+1
Answer
A route becomes dynamic when it uses request‑specific data (cookies, headers), or opts out of caching (`cache: 'no-store'`). You can force behavior with segment config like `dynamic = 'force-static'` or `dynamic = 'force-dynamic'`.
mediumnextjsfetchcache+1
Answer
`cache: 'no-store'` opts out of caching and always fetches fresh data. `revalidate` sets a TTL for cached data, enabling ISR‑like behavior where data is refreshed after N seconds. Both control how Next caches fetches on the server.