devsetswww.devsets.com/en/topics/nextjs/notes
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, andpage.tsxmakes it a page. Onlypageandroutefiles 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._folderis excluded from routing.- Parallel and intercepting routes.
@slotrenders several pages in one layout at once.(.)photointercepts a route, for example to show a photo in a modal while keeping the full page for direct visits.- Special files.
loading.tsxis a Suspense fallback,error.tsxis an error boundary (a client component witherrorandretry),not-found.tsxis shown fornotFound(),route.tsis 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/usersServer and Client Components
- Server by default.
- Components in
app/are Server Components: they render on the server, can beasync, 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
childrenor 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-onlypackage breaks the build if a module gets into the client bundle. OnlyNEXT_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 withuse. - redirect and notFound.
redirect(),permanentRedirect()andnotFound()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
asyncServer Component awaitsfetchor a database call directly, withoutuseEffector API routes. - Not cached by default.
fetchand database calls run on every request. To cache them, useuse cache; to avoid blocking the page, wrap the component in<Suspense>.- Parallel requests.
- Independent requests are started together with
Promise.all, otherwise eachawaitwaits for the previous one (a waterfall). - Streaming.
<Suspense>andloading.tsxsend 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 withuseinside<Suspense>.
Caching (Cache Components)
- Enabling.
cacheComponents: trueinnext.config.ts. It replaces the old route optionsdynamic,revalidateandfetchCache.- 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(),searchParamsand 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.useActionStategives the result and the pending state,useFormStatusgives 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.revalidatePathinvalidates a whole route.- refresh.
refresh()fromnext/cachere-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.matcherlimits 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,POSTand other methods that take aRequestand return aResponse. Can't be in the same folder aspage.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
widthandheightorfill;sizesfor responsive images. Since Next.js 16,preloadreplacespriorityfor 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
metadataobject orgenerateMetadatain a page or layout. Filesopengraph-image,sitemap.ts,robots.tsgenerate the rest. - Lazy loading.
next/dynamicorlazyloads a heavy Client Component only when needed.- Tooling.
- Turbopack is the default bundler for
next devandnext build.reactCompiler: trueenables automatic memoization.
Common pitfalls
paramsandsearchParamsare promises: withoutawaityou 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; onlyNEXT_PUBLIC_variables are public. redirect()insidetry/catchdoesn't work:catchswallows the special error it throws.- Expecting
fetchto 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()orwindowin render cause a hydration mismatch.