Next.js quick reference for interviews

The essentials of the topic on a couple of pages: key concepts by section and the pitfalls interviewers like to ask about.

App Router and files

Routing by folders.
A folder in app/ is a URL segment, and page.tsx makes it a page. Only page and route files are public; other files in the folder are not routes.
layout.tsx.
Shared UI for a segment and its children. On navigation a layout isn't re-rendered and keeps its state. The root layout contains <html> and <body>.
Dynamic segments.
[slug] is one parameter, [...slug] catches all segments, [[...slug]] also matches the route without them.
Groups and private folders.
(group) organizes routes and layouts without changing the URL. _folder is excluded from routing.
Parallel and intercepting routes.
@slot renders several pages in one layout at once. (.)photo intercepts a route, for example to show a photo in a modal while keeping the full page for direct visits.
Special files.
loading.tsx is a Suspense fallback, error.tsx is an error boundary (a client component with error and retry), not-found.tsx is shown for notFound(), route.ts is an API endpoint.
app/
  layout.tsx          // root layout
  page.tsx            // /
  (marketing)/
    about/page.tsx    // /about
  blog/[slug]/
    page.tsx          // /blog/hello
    loading.tsx
    error.tsx
  api/users/route.ts  // GET /api/users

Server and Client Components

Server by default.
Components in app/ are Server Components: they render on the server, can be async, read a database or secrets, and send no JS to the browser.
'use client'.
Needed for state, effects, event handlers and browser APIs. It marks a boundary: everything the file imports becomes client code too.
Composition.
A Server Component can be passed into a Client Component as children or another prop and stays on the server.
Props across the boundary.
Props from server to client must be serializable: plain objects, arrays, dates, promises. Functions can't be passed, except Server Functions.
Secrets.
The server-only package breaks the build if a module gets into the client bundle. Only NEXT_PUBLIC_ variables reach the browser, and they are inlined at build time.

Navigation

<Link>.
Client-side navigation without a full reload. In production, links in the viewport are prefetched.
next/navigation hooks.
useRouter (push, replace, back, refresh), usePathname, useSearchParams, useParams. They work only in Client Components.
params and searchParams.
In pages and layouts they are promises: const { slug } = await params. In a Client Component, unwrap them with use.
redirect and notFound.
redirect(), permanentRedirect() and notFound() work by throwing a special error, so code after them doesn't run.
export default async function Page({
  params,
}: PageProps<"/blog/[slug]">) {
  const { slug } = await params;
  const post = await getPost(slug);
  if (!post) notFound();
  return <h1>{post.title}</h1>;
}

Fetching data

In the component.
An async Server Component awaits fetch or a database call directly, without useEffect or API routes.
Not cached by default.
fetch and database calls run on every request. To cache them, use use cache; to avoid blocking the page, wrap the component in <Suspense>.
Parallel requests.
Independent requests are started together with Promise.all, otherwise each await waits for the previous one (a waterfall).
Streaming.
<Suspense> and loading.tsx send the ready part of the page right away, and slow parts arrive as they load.
Request deduplication.
React cache() lets several components call the same function within one request without repeating the query.
Promise into the client.
A Server Component can pass a promise without await, and a Client Component reads it with use inside <Suspense>.

Caching (Cache Components)

Enabling.
cacheComponents: true in next.config.ts. It replaces the old route options dynamic, revalidate and fetchCache.
use cache.
The directive caches the result of an async function, component or whole file. Arguments and captured values become part of the cache key.
cacheLife and cacheTag.
cacheLife("hours") sets the lifetime of an entry, cacheTag("products") names it for on-demand invalidation.
Static shell.
Everything that doesn't depend on the request is prerendered into a static shell. The dynamic parts stream in at request time inside <Suspense> (Partial Prerendering).
Runtime APIs.
cookies(), headers(), searchParams and uncached data are known only at request time, so components that read them go inside <Suspense>.
generateStaticParams.
Lists the dynamic parameter values to prerender at build time.
import { cacheLife, cacheTag } from "next/cache";

export async function getProducts() {
  "use cache";
  cacheLife("hours");
  cacheTag("products");
  return db.product.findMany();
}

Mutations and Server Actions

Server Functions.
An async function with 'use server' runs on the server and is called from the client like a regular function. Used for forms and mutations, these are Server Actions.
Forms.
<form action={createPost}> works even before JS loads. useActionState gives the result and the pending state, useFormStatus gives the pending state in a child component.
updateTag.
Only in Server Actions: expires the tag immediately, so the user sees their own change right away.
revalidateTag and revalidatePath.
revalidateTag("products", "max") marks data as stale and refreshes it in the background. revalidatePath invalidates a whole route.
refresh.
refresh() from next/cache re-renders the current page with fresh data after a mutation.
Security.
Each Server Action is a public POST endpoint. Check the session and validate the input inside every one.
"use server";
import { updateTag } from "next/cache";

export async function addProduct(data: FormData) {
  const session = await auth();
  if (!session) throw new Error("Unauthorized");
  const name = String(data.get("name") ?? "");
  await db.product.create({ data: { name } });
  updateTag("products");
}

Rendering

Static and dynamic.
A static page is built once and served from the CDN. A dynamic page is rendered per request because it depends on cookies, headers or fresh data.
ISR.
A cached page is regenerated in the background after its lifetime expires, while visitors get the previous version.
SSR and hydration.
Client Components are also rendered to HTML on the server, and then React attaches handlers in the browser (hydration).
Hydration mismatch.
Happens when the server and the browser render different markup: Date.now(), Math.random(), window, locale formatting. Move such code into an effect or compute it on the server.

Proxy and Route Handlers

proxy.ts.
Formerly middleware.ts. Runs before a route is rendered: redirects, rewrites, headers, cookies. Uses the Node.js runtime. One file per project.
matcher.
config.matcher limits the paths. Without it the proxy runs on every request, including static files and prefetches.
Light checks only.
In the proxy, check only whether a session cookie exists. Do the database check closer to the data.
route.ts.
Exports GET, POST and other methods that take a Request and return a Response. Can't be in the same folder as page.tsx.
after.
after() runs work after the response is sent: logging, analytics.
// proxy.ts
import {
  NextResponse,
  type NextRequest,
} from "next/server";

export function proxy(request: NextRequest) {
  if (!request.cookies.has("session")) {
    const url = new URL("/login", request.url);
    return NextResponse.redirect(url);
  }
}

export const config = { matcher: "/dashboard/:path*" };

Optimization and SEO

next/image.
Resizes images, serves modern formats and lazy-loads them. Needs width and height or fill; sizes for responsive images. Since Next.js 16, preload replaces priority for the main image.
next/font.
Self-hosts Google and local fonts at build time with no layout shift and no requests to Google.
Metadata.
The metadata object or generateMetadata in a page or layout. Files opengraph-image, sitemap.ts, robots.ts generate the rest.
Lazy loading.
next/dynamic or lazy loads a heavy Client Component only when needed.
Tooling.
Turbopack is the default bundler for next dev and next build. reactCompiler: true enables automatic memoization.

Common pitfalls

  • params and searchParams are promises: without await you get a promise instead of values.
  • 'use client' high in the tree turns the whole subtree into client code and ships its JS.
  • A function or class instance passed from a Server Component to a Client Component fails: props must be serializable.
  • Database or secret code imported into a Client Component ends up in the bundle. Use server-only; only NEXT_PUBLIC_ variables are public.
  • redirect() inside try/catch doesn't work: catch swallows the special error it throws.
  • Expecting fetch to be cached: it isn't by default, every request goes to the source.
  • A database query in the proxy slows down every request, including prefetches and static files.
  • A Server Action without an auth check: anyone can call it with a POST request.
  • Date.now(), Math.random() or window in render cause a hydration mismatch.

Cheat sheet