Data and mutations in Next.js

Fetching on the server, Server Actions, auth and proxy.ts.

Builds on The Next.js App Router, Server Functions.

The last chapter gave the reading list a shape: folders, layouts, pages. This one gives it data. Data comes in (fetching in Server Components), goes out (Server Actions after a form submit), and in between somebody has to decide who's allowed to see and change it. Chapter 45 taught Server Functions as a React feature and warned that every one of them is a public endpoint. Here you'll see how Next.js wires them into routing and caching, where TanStack Query still fits, where authentication checks belong (not where most people first put them), what proxy.ts is for, and how to run work after the response with after().

The problem: a list, a form and a user#

The reading list app now has three requirements:

  1. /books shows the signed-in user's books, read from a database.
  2. An Add book form inserts a book, and the list shows it right away.
  3. Signed-out users can't read or add books, even if they know the URLs.

In Chapter 39 you solved the first two on the client with TanStack Query: fetch in the browser, cache, invalidate after a mutation. That works, but every visitor downloads the fetching code, waits for JavaScript before the first request starts, and the server is an API you maintain separately. Server Components let the page read the database directly. The interesting parts are what happens after the write, and requirement 3.

Fetching in Server Components#

A Server Component can be async and await whatever it needs: a database query, a file read, a fetch to an internal service. The code never ships to the browser.

app/lib/books.ts
import "server-only";
import { db } from "./db";
import { verifySession } from "./auth";

export type BookDTO = { id: string; title: string; author: string; read: boolean };

export async function getBooks(): Promise<BookDTO[]> {
  const { userId } = await verifySession();
  const rows = await db.book.findMany({ where: { ownerId: userId }, orderBy: { createdAt: "desc" } });
  // Return only what the UI needs, never whole rows.
  return rows.map((b) => ({ id: b.id, title: b.title, author: b.author, read: b.read }));
}

A few rules decide how fast and how correct this is.

fetch isn't cached by default. Since Next.js 15, fetch doesn't store results across requests unless you opt in. (In the previous model a route with no request-time APIs is still prerendered, so its fetch runs once at build; with Cache Components an uncached fetch runs at request time.) Chapter 48 covers caching in depth; for now, assume reads are fresh.

Identical reads in one render are deduplicated. If the layout, the page and three components all fetch the same URL with the same options during one render, the request runs once (React memoizes fetch on the server). For anything that isn't fetch, like an ORM call, wrap the function in React's cache() to get the same per-request deduplication. That's why it's fine for a layout and a page to both call getUser(): you fetch where you need the data instead of drilling props.

Await in parallel, not in sequence. Two awaits in a row are a waterfall: the second request doesn't start until the first finishes. Start both, then await together:

const [book, reviews] = await Promise.all([getBook(id), getReviews(id)]);

Stream what's slow. Wrap a slow component in <Suspense> (or add a loading.tsx) and the rest of the page ships while it loads. With Cache Components on, which is the default for new apps since 16.4, this stops being optional: a component that awaits uncached data outside any Suspense boundary is flagged in development as a blocking route, because it would hold up the whole response. You either stream it or cache it.

A layout that awaits blocks navigation. If a layout awaits uncached data or reads cookies(), a navigation into that layout can't show the page's loading.tsx until the layout finishes. Move the await into the page or behind a Suspense boundary.

Server Actions in Next.js#

A Server Action is a Server Function used as a form action or called from a Client Component (Chapter 45 built them). In Next.js you write them in a file that starts with "use server", or inline in a Server Component.

Here's the second half of the reading list: the action and the form.

app/books/actions.ts
"use server";

import { z } from "zod";
import { updateTag } from "next/cache";
import { verifySession } from "../lib/auth";
import { insertBook } from "../lib/books";

const NewBook = z.object({
  title: z.string().trim().min(1, "Title is required").max(200),
  author: z.string().trim().min(1, "Author is required").max(200),
});

export type AddBookState = { error?: string; ok?: boolean };

export async function addBook(_prev: AddBookState, formData: FormData): Promise<AddBookState> {
  // 1. Authenticate. This is a public POST endpoint, whatever the UI looks like.
  const { userId } = await verifySession();

  // 2. Validate. formData is untrusted input.
  const parsed = NewBook.safeParse({ title: formData.get("title"), author: formData.get("author") });
  if (!parsed.success) return { error: parsed.error.issues[0].message };

  // 3. Write.
  await insertBook(userId, parsed.data);

  // 4. Expire cached data tagged "books" so this user sees the new book now.
  updateTag("books");
  return { ok: true };
}

Most of this is React you already know: useActionState gives you the pending flag and the returned state (Chapter 25), and the form works before hydration because a Server Action has a real endpoint behind it (Chapter 45). What Next.js adds is the part after the write.

Revalidating after a write#

After a mutation, the data on screen is stale. Next.js gives you four tools, and choosing the right one is a common interview question:

CallWhat it doesUse it when
updateTag("books") Next.js 16Expires everything tagged books immediately. The next read waits for fresh data. Server Actions only.The user who made the change must see it now (read-your-writes).
revalidateTag("books", "max")Marks tagged data stale. Readers keep getting the old data while a fresh copy is built in the background. Works in Server Actions and Route Handlers.Eventual consistency is fine, for example a CMS webhook.
revalidatePath("/books")Invalidates whatever renders that path.You think in pages rather than data, or the data isn't tagged.
refresh() Next.js 16Re-runs uncached, dynamic parts of the current route without touching any cache. Server Actions only.Uncached data elsewhere on the page (a notification count) changed.

Tags only matter for cached data, which is the next chapter's subject. But even with no caching at all, calling updateTag, revalidatePath or refresh in a Server Action has a useful side effect: Next.js re-renders the current route on the server and sends the new UI back in the action's response. The client doesn't make a second request to see the new book.

A Server Action, end to end
BrowserServer<form action={addBook}>useActionStateBooks listDune, EmmaaddBook()verifySession, validateDatabaseINSERT bookCachetag: booksRe-render routeRSC payloadPOST
Step 1 of 6

The user submits the Add book form. Its action is a Server Action, so React sends a POST with the form data and the action's id. Before hydration this still works as a plain HTML form post.

Redirecting after a write#

redirect() from next/navigation ends the action and navigates. It works by throwing a special error that Next.js catches, which has two consequences:

app/books/actions.ts
export async function createAndOpen(formData: FormData) {
  const { userId } = await verifySession();
  let id: string;
  try {
    id = await insertBook(userId, parse(formData));
  } catch {
    return { error: "Couldn't save the book" };
  }
  updateTag("books"); // invalidate first...
  redirect(`/books/${id}`); // ...then redirect: nothing after this line runs
}

Call it after revalidating, because nothing after redirect() runs, and outside try/catch, or your catch swallows the redirect.

TanStack Query with the App Router#

Server Components and Server Actions cover most reading and writing. TanStack Query still earns its place when the client owns a lot of the data lifecycle: infinite scroll, polling, optimistic updates across several views, or data you refetch on window focus. The App Router pattern is "prefetch on the server, hydrate into the client cache":

app/get-query-client.ts
import { QueryClient, environmentManager, defaultShouldDehydrateQuery } from "@tanstack/react-query";

function makeQueryClient() {
  return new QueryClient({
    defaultOptions: {
      // Above 0, so the client doesn't refetch what the server just fetched.
      queries: { staleTime: 60 * 1000 },
      dehydrate: {
        // Also send queries that are still pending, so they can stream.
        shouldDehydrateQuery: (query) => defaultShouldDehydrateQuery(query) || query.state.status === "pending",
      },
    },
  });
}

let browserQueryClient: QueryClient | undefined;

export function getQueryClient() {
  // Server: a new client per request, so users never share a cache.
  if (environmentManager.isServer()) return makeQueryClient();
  // Browser: one client for the life of the tab.
  if (!browserQueryClient) browserQueryClient = makeQueryClient();
  return browserQueryClient;
}

The shape matters more than the details. The server creates a new QueryClient per request (a shared one would leak one user's data into another's response), fills it, and serializes it with dehydrate. <HydrationBoundary> puts that data into the browser's long-lived client, and from there it's ordinary TanStack Query. The staleTime above zero keeps the client from immediately refetching what it just received. LiveBookList needs a <Suspense> boundary above it (a loading.tsx works) while the streamed promise resolves.

Two version notes for TanStack Query 5.108, the version in this guide's sandbox: queryClient.query() is the current call, and prefetchQuery (which you'll see in most existing code) is deprecated in its favor. The difference: query() rejects on error, prefetchQuery swallowed errors. That's why the unawaited call above needs a .catch: without it, a failed fetch becomes an unhandled rejection on the server. Likewise environmentManager.isServer() replaces the older isServer export. Both old forms still work in v5.

The trade-off to say out loud: don't render the same data from both a Server Component and a Query cache. After a mutation one of them will be stale. Pick an owner per piece of data: server-rendered data revalidated by tags, or client-cached data invalidated with queryClient.invalidateQueries.

Where to check authentication#

Here's the trap. The obvious place to protect /dashboard/* is the dashboard layout: check the session once, redirect if it's missing, and every page underneath is covered. It feels DRY. It isn't safe, for three reasons.

  1. Layouts don't re-run on navigation. Chapter 46 showed partial rendering: navigating from /dashboard to /dashboard/books renders only the page segment. The docs put it plainly: layouts "don't re-render on navigation, meaning the user session won't be checked on every route change." If the session expired between the two clicks, the layout's check never ran again, and the page happily renders the data.
  2. Server Actions aren't behind your layout at all. Each action is a POST endpoint that can be called directly. A check in a page or layout "does not extend to the Server Actions defined within it".
  3. Parallel slots and child segments render independently. Returning null from a layout doesn't stop a slot or a child segment from rendering and fetching on the server.

The fix is to check where the data is. Next.js's docs call it a Data Access Layer (DAL): a server-only module that every read and write goes through, which verifies the session and returns only what the caller is allowed to see.

app/lib/auth.ts
import "server-only";
import { cache } from "react";
import { cookies } from "next/headers";
import { redirect } from "next/navigation";
import { decrypt } from "./session";

// cache(): many components can call this in one render; the work runs once.
export const verifySession = cache(async () => {
  const token = (await cookies()).get("session")?.value;
  const session = await decrypt(token);
  if (!session?.userId) redirect("/login");
  return { userId: session.userId };
});

import "server-only" makes the build fail if a Client Component ever imports the module, so your session logic and database client can't end up in the browser bundle. cache() deduplicates the check within one server render. Don't count on it outside rendering: React documents cache for Server Components, so in a Route Handler, for example, treat each call as running again. That's harmless for correctness, since the check still runs; it only costs a repeated cookie decrypt.

Then every function in the DAL calls verifySession() first, and checks authorization as well as authentication: not just "is someone logged in" but "does this user own book 42". Skipping the second check is an IDOR (insecure direct object reference) bug, the most common way logged-in users read each other's data. And return DTOs, plain objects with only the fields the UI needs, so a passwordHash or an internal flag never reaches a Client Component prop by accident.

You can still redirect from a layout or page for a nicer experience. Just don't let it be the only check.

Fix itThe check that never ran

This is a simulation of Next.js's partial rendering, not Next.js. load(url) renders every segment, like a full page load. navigate(url) renders only the page and reuses the layout, like a soft navigation. The only auth check is in the layout.

Run it: after the session cookie is cleared, a soft navigation still shows the books, and the Server Action still inserts one. Fix dal.js so both reads and writes check the session, without touching the layout.

import { cookies, redirect } from "./fake-next.js";
import { db } from "./db.js";

// Throws a redirect when there's no session. Nobody calls it yet.
export function verifySession() {
  if (!cookies.session) redirect("/login");
  return { user: cookies.session };
}

export async function getBooks() {
  return db.books.map((b) => ({ id: b.id, title: b.title }));
}

export async function insertBook(title) {
  db.books.push({ id: db.books.length + 1, title });
}
Nothing logged yet.

proxy.ts: code before the route#

proxy.ts Next.js 16 at the project root (or in src/) runs before a request reaches any route. It used to be called middleware.ts; Next.js 16 renamed it to make clear that it's a network boundary, a proxy in front of your app, not a general place for application logic. It runs on the Node.js runtime.

proxy.ts
import { NextResponse, type NextRequest } from "next/server";

export function proxy(request: NextRequest) {
  // Optimistic check: only looks at whether a cookie exists. No database.
  const hasSession = request.cookies.has("session");
  if (!hasSession && request.nextUrl.pathname.startsWith("/dashboard")) {
    return NextResponse.redirect(new URL("/login", request.url));
  }
  return NextResponse.next();
}

export const config = {
  // Skip static files and image optimization.
  matcher: ["/((?!api|_next/static|_next/image|favicon.ico).*)"],
};

The function can return NextResponse.next() (continue, optionally with modified headers), NextResponse.redirect(), NextResponse.rewrite() (serve a different route at the same URL), or a Response directly. Without a matcher it runs on every request, static assets included.

Good uses: redirects that depend on the request (locale detection, old URLs), rewrites for A/B tests or multi-tenant hostnames, setting headers, and optimistic auth redirects based on whether a session cookie exists. Bad uses: database queries, slow fetches, or being your only authorization layer. It runs on every matched request, so anything slow there slows everything.

There's a real incident behind the "not your only layer" advice. In March 2025, CVE-2025-29927 let attackers skip Next.js middleware entirely by sending an internal header (x-middleware-subrequest). Apps that checked auth only in middleware were open; apps that also checked in their data layer weren't. Defense in depth isn't theoretical here.

Migration notes: rename the file and the exported function (middleware to proxy); the codemod npx @next/codemod@canary middleware-to-proxy . does it. middleware.ts still works in 16 for the Edge runtime, but it's deprecated. "use cache" has no effect inside proxy.ts.

after(): work after the response#

Some work shouldn't delay the response: logging, analytics, sending a webhook, warming a cache. after() from next/server schedules a callback that runs once the response (or prerender) has finished, even if the route threw or called redirect or notFound. Calling it doesn't make a route dynamic. It's stable since 15.1.

app/books/actions.ts
import { after } from "next/server";

export async function addBook(_prev: AddBookState, formData: FormData) {
  const { userId } = await verifySession();
  // ...validate and insert...
  updateTag("books");
  after(() => analytics.track("book_added", { userId }));
  return { ok: true };
}

On serverless platforms it's implemented with the platform's waitUntil, so it's bounded by the function's maximum duration. One gotcha: inside a Server Action or Route Handler you can call cookies() and headers() within the callback, but in a Server Component you can't. Read them during rendering and pass the values in.

Pitfalls#

Check your understanding#

PredictThe action that stays put
"use server";
export async function save(formData: FormData) {
  try {
    const id = await insertBook(formData);
    redirect(`/books/${id}`);
  } catch (e) {
    console.error("save failed", e);
    return { error: "Something went wrong" };
  }
}

The insert succeeds. What does the user see, and what's in the server log?

Quick checkWhat belongs in proxy.ts

Which job is the best fit for proxy.ts?

Quick checkPick the call

A user edits their profile in a Server Action. The profile data is cached and tagged user-42. They must see the change immediately. What should the action call?

Explain it out loudWhere does the auth check go?

An interviewer asks: "In a Next.js App Router app, where do you check authentication and authorization, and why not just in the layout?"

Explain it out loudServer Components or TanStack Query?

"You're on the App Router. When would you still reach for TanStack Query, and how do you combine it with server rendering?"

Interview angle

Say it in 30 seconds

In the App Router, Server Components read data directly, with identical reads deduplicated per render and slow parts streamed behind Suspense. Writes go through Server Actions, which are public endpoints: authenticate, validate, write, then invalidate with updateTag for read-your-writes or revalidateTag with a profile for background refresh, and the re-rendered route comes back in the same response. Authentication belongs in a server-only data access layer, not a layout, because layouts don't re-run on navigation and actions bypass them. proxy.ts handles fast request-level redirects and rewrites, and after() runs work once the response is sent.

Why is checking authentication in a Next.js layout not enough?

senior

After a Server Action writes data, how do you get the UI updated? Compare updateTag, revalidateTag, revalidatePath and refresh.

intermediate

What's special about calling redirect() in a Server Action?

basic

What is proxy.ts and what should and shouldn't go in it?

intermediate

How do you use TanStack Query with the App Router?

intermediate

What does after() do, and when would you use it?

basic

Recap#

  • Server Components fetch data directly. fetch is uncached by default, identical reads in one render are deduplicated (cache() for non-fetch calls), and independent reads should run in parallel and stream behind Suspense.
  • Server Actions handle writes. Authenticate, validate, write, then invalidate: updateTag for read-your-writes, revalidateTag(tag, "max") for background refresh, revalidatePath by path, refresh() for uncached data. The updated UI comes back in the same response.
  • redirect() throws: call it after invalidating and outside try/catch.
  • TanStack Query fits client-owned data. Prefetch on the server with a per-request client, pass it through HydrationBoundary, and keep one owner per piece of data.
  • Check auth in a server-only data access layer, not in layouts: layouts don't re-run on navigation and Server Actions bypass them. Check ownership too, and return DTOs.
  • proxy.ts (formerly middleware.ts) is for fast request-level redirects, rewrites and headers. after() runs work once the response is done.

Sources#