Skip to content

Next.js (App Router)

Q (basic): App Router vs Pages Router?

Say this (30 sec): The Pages Router (pages/) is the older model: every page is a client-hydrated React component, and data is fetched with getServerSideProps/getStaticProps. The App Router (app/) is built on React Server Components: components render on the server by default, you fetch data directly with async/await inside components, and you get nested layouts, streaming, loading/error files, and server actions. App Router is the recommended approach for new projects; both can coexist in one app.

Follow-ups they ask: Benefit of server components? → Less JavaScript shipped to the browser, direct access to DB/secrets on the server, no client-server waterfalls for initial data.

Q (basic): What are the special files in the App Router?

Say this (30 sec):

  • page.tsx — the UI for a route; makes the folder publicly routable.
  • layout.tsx — shared UI that wraps children and persists across navigation (doesn’t re-mount, keeps state).
  • template.tsx — like layout but re-mounts on every navigation.
  • loading.tsx — automatic Suspense fallback while the segment loads.
  • error.tsx — error boundary for the segment (must be a client component, gets error and reset).
  • not-found.tsx — rendered by notFound() or unmatched routes.
  • route.ts — API endpoint (route handler).
  • Folders: [id] dynamic, [...slug] catch-all, (group) route groups that don’t affect the URL, _private folders excluded from routing, @slot parallel routes.

Follow-ups they ask: Does error.tsx catch errors in its own layout? → No, it wraps the page and children, not the layout at the same level. Use the parent’s error.tsx or global-error.tsx for root layout errors.

Q (basic): Server components vs client components?

Say this (30 sec): Server components run only on the server: they can be async, fetch data, read env secrets and the database, and send zero JS for themselves. They can’t use state, effects, event handlers or browser APIs. Client components ("use client") are pre-rendered to HTML on the server too, then hydrated in the browser so they can be interactive. Rule: keep things server by default and push "use client" down to the smallest interactive leaves.

Example:

// app/products/page.tsx — server component
export default async function ProductsPage() {
const products = await db.product.findMany(); // direct DB access
return <ProductList products={products} />;
}
// components/AddToCart.tsx
"use client";
export function AddToCart({ id }: { id: string }) {
const [added, setAdded] = useState(false);
return <button onClick={() => setAdded(true)}>{added ? "Added" : "Add"}</button>;
}

Common wrong answer: “Client components only render in the browser.” They are also server-rendered to HTML for the first load; they just also ship JS and hydrate.

Q (mid): What exactly does "use client" do? Can a client component render a server component?

Say this (30 sec): "use client" marks a module as the entry to the client bundle — that file and everything it imports become client code. You don’t need it in every file, only at the boundary. A client component can’t import a server component, but it can receive one as children or another prop, because the server renders it first and passes the result in.

Example:

// app/page.tsx (server)
<ClientModal>
<ServerCart /> {/* rendered on server, passed in as children */}
</ClientModal>

Follow-ups they ask: What props can pass from server to client? → Only serializable ones: primitives, plain objects/arrays, Dates, Promises, and server actions. Not regular functions or class instances. How to keep server-only code out of the client? → import "server-only" in that module makes the build fail if a client component imports it.

Q (mid): How do layouts and navigation work? What is Link prefetching?

Say this (30 sec): Layouts nest according to folders and wrap their child segments; on navigation only the changed segments re-render — the layout keeps its state. <Link> does client-side navigation and prefetches routes when they enter the viewport in production, so navigation feels instant. For programmatic navigation, use useRouter() from next/navigation in client components, or redirect() in server code.

Q (basic): Explain CSR, SSR, SSG and ISR.

Say this (30 sec):

  • CSR — browser downloads JS and renders everything. Slow first paint, weak SEO. Fine for dashboards behind login.
  • SSR — HTML rendered on the server per request. Fresh, personalized data; costs server time per request.
  • SSG — HTML generated at build time, served from CDN. Fastest; data is as old as the last build.
  • ISR — SSG plus background regeneration after a time (revalidate) or on demand (revalidatePath/revalidateTag). Users get cached pages while fresh ones are built (stale-while-revalidate).

Example (App Router):

// ISR: regenerate at most every 60s
export const revalidate = 60;
// SSG for dynamic routes
export async function generateStaticParams() {
const posts = await getPosts();
return posts.map((p) => ({ slug: p.slug }));
}
// force per-request rendering
export const dynamic = "force-dynamic";

Follow-ups they ask: What makes a route dynamic automatically? → using request-time APIs: cookies(), headers(), searchParams, connection(), or uncached data under Cache Components.

Q (mid): What is streaming?

Say this (30 sec): Instead of waiting for all data before sending any HTML, the server sends the page shell immediately and streams slower parts as they resolve, each wrapped in a Suspense boundary with a fallback. loading.tsx does this for a whole segment; <Suspense> does it for individual components. It improves time to first byte and perceived speed.

Example:

export default function Dashboard() {
return (
<>
<Header />
<Suspense fallback={<Skeleton />}>
<SlowRevenueChart /> {/* async server component */}
</Suspense>
</>
);
}
Q (mid): What is Partial Prerendering / Cache Components?

Say this (30 sec): In Next 16, enabling cacheComponents makes data fetching dynamic by default, and you opt into caching explicitly with the "use cache" directive on a function, component or page, with cacheLife for duration and cacheTag for invalidation. Combined with Suspense, a single route can have a static shell prerendered and served instantly, with dynamic holes streamed per request — that’s Partial Prerendering.

Example:

async function getProducts() {
"use cache";
cacheLife("hours");
cacheTag("products");
return db.product.findMany();
}
Q (mid): How does caching work in Next.js 15/16?

Say this (30 sec): Key layers:

  1. Data cache — results of fetch (or "use cache" functions) persisted across requests. Since Next 15, fetch is not cached by default; opt in with { cache: "force-cache" } or { next: { revalidate: 60, tags: ["posts"] } }.
  2. Full route cache — prerendered HTML + RSC payload of static routes.
  3. Router cache — client-side cache of visited/prefetched segments for fast back/forward.
  4. Request memoization — identical fetch calls in one render are deduped; for non-fetch functions use React’s cache().

Invalidate with revalidatePath("/blog") or revalidateTag("posts") (from server actions or route handlers), or time-based revalidate.

Example:

const res = await fetch("https://api.example.com/posts", {
next: { revalidate: 300, tags: ["posts"] },
});
// in a server action after creating a post
revalidateTag("posts");

Follow-ups they ask: Why did Next 15 change defaults? → Next 14’s aggressive default caching confused developers with stale data. Note: In Next 16, revalidateTag takes a cacheLife profile as a second argument, and updateTag was added for read-your-own-writes in server actions.

Common wrong answer: “Next caches all fetch requests by default.” That was Next 13/14 behavior.

Q (mid): How do you fetch data in the App Router? How do you avoid waterfalls?

Say this (30 sec): In server components, just await the data directly — from fetch, an ORM, or an SDK. Avoid sequential awaits for independent data: start them in parallel with Promise.all, or split into separate components each wrapped in Suspense so they stream independently. For client-side data that changes after load (polling, infinite scroll), use TanStack Query/SWR in client components.

Example:

export default async function Page({ params }: { params: Promise<{ id: string }> }) {
const { id } = await params; // async in Next 15+
const [user, orders] = await Promise.all([getUser(id), getOrders(id)]);
return <Profile user={user} orders={orders} />;
}
Q (basic): What are server actions?

Say this (30 sec): Async functions marked with "use server" that run on the server but can be called from client code — usually as a form’s action or from an event handler. Next.js turns them into POST endpoints automatically. Great for mutations: no need to write an API route. After mutating, call revalidatePath/revalidateTag or redirect. Forms work even before JavaScript loads (progressive enhancement).

Example:

app/actions.ts
"use server";
import { z } from "zod";
const Schema = z.object({ title: z.string().min(1) });
export async function createTodo(prevState: unknown, formData: FormData) {
const session = await auth();
if (!session) return { error: "Unauthorized" }; // always authorize
const parsed = Schema.safeParse({ title: formData.get("title") });
if (!parsed.success) return { error: "Title required" }; // always validate
await db.todo.create({ data: { ...parsed.data, userId: session.user.id } });
revalidatePath("/todos");
return { error: null };
}

Follow-ups they ask: Are they secure? → They’re public HTTP endpoints, so anyone can call them with any input. Next includes some protections (encrypted action IDs, origin check), but auth and validation are your job.

Q (basic): What are route handlers? When use them instead of server actions?

Say this (30 sec): app/api/.../route.ts files exporting GET, POST, etc. using the Web Request/Response APIs. Use them for things that need a real HTTP API: webhooks (Stripe, Razorpay), public APIs consumed by mobile apps or third parties, file downloads, OAuth callbacks. Use server actions for mutations from your own UI.

Example:

app/api/users/[id]/route.ts
export async function GET(req: Request, { params }: { params: Promise<{ id: string }> }) {
const { id } = await params;
const user = await getUser(id);
if (!user) return Response.json({ error: "Not found" }, { status: 404 });
return Response.json(user);
}

Follow-ups they ask: Are GET handlers cached? → Not by default since Next 15.

Q (mid): What is middleware (proxy in Next 16)? What is it used for?

Say this (30 sec): A function that runs before a request is matched to a route. It can redirect, rewrite, set headers/cookies, or return a response. Common uses: auth redirects (no session cookie → /login), i18n locale routing, A/B testing, bot blocking. Use matcher to limit which paths it runs on. In Next 16, middleware.ts is renamed proxy.ts (the old name is deprecated) and it runs on the Node.js runtime. Keep it lightweight — it runs on every matched request — and don’t rely on it as the only auth check; verify in the server component/action/route too.

Example:

// proxy.ts (middleware.ts before Next 16)
import { NextResponse, type NextRequest } from "next/server";
export function proxy(req: NextRequest) {
if (!req.cookies.get("session")) {
return NextResponse.redirect(new URL("/login", req.url));
}
return NextResponse.next();
}
export const config = { matcher: ["/dashboard/:path*"] };
Q (basic): How do you handle SEO and metadata in the App Router?

Say this (30 sec): Export a static metadata object or an async generateMetadata function from a layout or page. Next merges metadata down the tree and renders the <head> tags. File conventions handle the rest: sitemap.ts, robots.ts, opengraph-image.tsx, icon.png. Server rendering itself helps SEO since crawlers get full HTML.

Example:

export async function generateMetadata({ params }: { params: Promise<{ slug: string }> }) {
const { slug } = await params;
const post = await getPost(slug);
return {
title: post.title,
description: post.excerpt,
openGraph: { images: [post.cover] },
};
}
Q (basic): What does next/image do?

Say this (30 sec): It serves resized, modern-format (WebP/AVIF) images per device using srcset, lazy-loads images by default, and requires width/height (or fill) so space is reserved and there’s no layout shift. For the above-the-fold hero image (usually the LCP element), mark it with priority (renamed preload in Next 16) so it’s not lazy-loaded. Remote images need images.remotePatterns in config. Use sizes with responsive layouts so the browser downloads the right size.

Follow-ups they ask: On Cloudflare? → Optimization needs a backend; with OpenNext you configure the Cloudflare Images binding, or use a custom loader / unoptimized.

Q (basic): What does next/font do?

Say this (30 sec): It downloads Google or local fonts at build time and self-hosts them with your assets — no request to Google at runtime — and generates fallback font metrics (size-adjust) to minimize layout shift when the font swaps in. It exposes a class/CSS variable to use with Tailwind.

Q (mid): Edge runtime vs Node.js runtime?

Say this (30 sec): The Node.js runtime (the default) has full Node APIs and npm compatibility — fs, native modules, most ORMs. The Edge runtime is a lighter runtime built on Web APIs (fetch, Request, crypto.subtle) with fast cold starts, but a limited API and code size — no fs, many Node packages won’t work. Next.js now recommends the Node.js runtime for most cases. You select it per route with export const runtime = "edge".

Follow-ups they ask: Is Edge the same as Cloudflare Workers? → Similar idea (V8 isolates, Web APIs), but Next’s “edge runtime” is a Next.js-specific API subset. With OpenNext on Cloudflare you actually run Next’s Node.js runtime inside a Worker, so you should remove runtime = "edge".

Q (mid): How did you deploy Next.js to Cloudflare? What does @opennextjs/cloudflare do?

Say this (30 sec): Next.js builds output designed for Node servers or Vercel. The @opennextjs/cloudflare adapter takes the normal next build output and transforms it into a Cloudflare Worker: it bundles the server code into a single worker script running with the nodejs_compat flag (so Next’s Node.js runtime works), puts static assets in Workers Static Assets, and plugs Next’s caching into Cloudflare services — for example R2 or KV for the incremental (ISR) cache, D1 or Durable Objects for tag revalidation, and a Durable Object queue for background revalidation. You build with opennextjs-cloudflare build, test with preview (runs in the real workerd runtime locally), and ship with deploy (uses Wrangler).

Example:

open-next.config.ts
import { defineCloudflareConfig } from "@opennextjs/cloudflare";
import r2IncrementalCache from "@opennextjs/cloudflare/overrides/incremental-cache/r2-incremental-cache";
export default defineCloudflareConfig({ incrementalCache: r2IncrementalCache });
// wrangler.jsonc (key parts)
{
"main": ".open-next/worker.js",
"compatibility_flags": ["nodejs_compat"],
"assets": { "directory": ".open-next/assets", "binding": "ASSETS" }
}
// accessing bindings (KV, D1, R2, env vars) in server code
import { getCloudflareContext } from "@opennextjs/cloudflare";
const { env } = getCloudflareContext();

Follow-ups they ask: Why not @cloudflare/next-on-pages? → That older adapter required the Edge runtime for every route and is deprecated; OpenNext supports the Node.js runtime and is the recommended path. Why Cloudflare over Vercel? → Cost, global edge network, generous free tier, and direct access to Cloudflare services (D1, R2, KV) via bindings.

Q (mid): What are the limitations of running Next.js on Cloudflare Workers?

Say this (30 sec):

  • Worker size limit — the compressed bundle must fit Cloudflare’s limit (3 MiB on free, 10 MiB on paid), so heavy dependencies can be a problem.
  • No persistent filesystem — can’t write files at runtime; ISR cache must go to R2/KV, not disk.
  • Not every Node API/package works — nodejs_compat covers most, but native addons (.node binaries, e.g. sharp) and some APIs don’t.
  • Edge runtime routes aren’t supported by the adapter — use Node.js runtime.
  • CPU time and memory limits per request (128 MB memory per isolate).
  • Image optimization needs the Cloudflare Images binding or a custom loader.
  • Database connections — use HTTP-based drivers, D1, or Hyperdrive for Postgres rather than long-lived TCP pools.
  • New Next.js features can lag a little behind until the adapter supports them.

Common wrong answer: “It runs on Edge runtime.” It runs the Node.js runtime on Workers with nodejs_compat.

Q (mid): How do you handle environment variables in Next.js?

Say this (30 sec): Variables in .env files are server-only by default. Only those prefixed with NEXT_PUBLIC_ are inlined into the client bundle at build time — so never put secrets there, and changing them requires a rebuild. On Cloudflare, runtime secrets come from Wrangler/dashboard vars and bindings (accessible via getCloudflareContext().env), and .dev.vars is used locally.

Q (mid): How do you handle authentication in the App Router?

Say this (30 sec): Use a library (Auth.js, Better Auth, Clerk) or session cookies. Store the session in an httpOnly, secure, SameSite cookie. Do an optimistic redirect in middleware/proxy for UX, but do the real check close to the data — in server components, server actions and route handlers via a getSession()/data-access layer — because middleware alone can be bypassed or misconfigured.

Q (mid): How do you optimize a Next.js app's performance?

Say this (30 sec): Keep components on the server to ship less JS; push "use client" to leaves. Use next/image with correct sizes and priority for the LCP image, next/font for zero-shift fonts. Stream slow sections with Suspense. Cache data with revalidate/"use cache". Lazy-load heavy client components with next/dynamic. Check the bundle with @next/bundle-analyzer. Avoid making a whole route dynamic just because one small part reads cookies.