Thuta Learning
Next.js
ExercisesWeb DevelopmentIntermediate

Practice Set 2 — Data Fetching, Server Actions, and Caching Exercises

Next.jsLesson 3345 min

What you'll walk away with

  • Write a Route Handler as a Request-to-Response function that returns 200, 201 and 400 correctly
  • Test a Route Handler in Node by calling it directly with new Request()
  • Connect a (prevState, formData) Server Action to useActionState and show error or success messages
  • Choose updateTag in Server Actions and revalidateTag(tag, "max") in Route Handlers

Explain it simply

Explain it simply

Practice Set 1 was about how pages appear. Set 2 is about how data gets in, how it changes, and how the cache is cleared afterwards. All four tasks build on a small app that collects quotes.

In library terms, a Route Handler is the lending counter, a Server Action is the membership form, and a cache tag is the note saying "re-sort this shelf". For every task you test both the working case and a bad-input case.

Problem → Why → Solution

The problem: an API tested only on the happy path

In the first draft, the POST handler calls await request.json() without a try/catch and returns { error } with a 200 status when validation fails. Testing from the browser, everything looks fine.

Real clients reveal two problems. A body that is not JSON makes request.json() throw, which becomes a server error (500). And because validation errors come back as 200, a client that checks response.ok believes the save succeeded and clears its form.

app/api/quotes/route.ts (first draft)
export async function POST(request: Request) {
  const body = await request.json();        // throws on "not json" -> 500
  if (typeof body.text !== "string" || body.text.length <= 3) {
    return Response.json({ error: "text is too short" }); // status 200!
  }
  quotes.push({ text: body.text, author: body.author ?? "Unknown" });
  return Response.json({ ok: true });                     // should be 201
}

Status codes are the API's contract

Code that calls an API usually looks at the status before reading the body: 2xx means success, 4xx means the client sent something wrong, 5xx means the server broke. A wrong status makes every client take the wrong decision.

Core concept: the rules behind the four tasks

You can keep using the Practice Set 1 project or start a new one. For each task, first write down which input should produce which status or state. That list is your test plan, and once the code exists you check it line by line. The table below lists the minimum cases for each task.

TaskWhat you buildCases to test
1GET in app/api/quotes/route.ts200 with the quote array
2POST with validation201 / 400 short text / 400 not JSON
3subscribe Server Action + formBad email / success / duplicate
4Cache tag + invalidationFresh data appears after a change

A Route Handler takes a Request and returns a Response

route.ts exports functions named after HTTP methods such as GET and POST. Each one receives a Web-standard Request and returns a Response. Nothing Next.js-specific is required, so in Node 22 you can call them directly with new Request() and test them. Set the status yourself with Response.json(data, { status }).

A Server Action plus useActionState

An action used with useActionState(action, initialState) receives (prevState, formData) and returns the next state; the hook hands back [state, formAction, isPending]. The useFormState from react-dom seen in older tutorials was replaced in React 19 by useActionState from the react package.

Where a tag is attached and where it is cleared

A tag can only be attached to cached data: with cacheTag("quotes") inside a "use cache" function as in the caching lesson, or with fetch(url, { cache: "force-cache", next: { tags: ["quotes"] } }). In a Server Action, updateTag("quotes") expires it immediately so users see their own change at once. In a Route Handler such as a webhook, updateTag is not allowed; use revalidateTag("quotes", "max").

Mental model: door, check, answer, clean up
  1. A Request or FormData arrives
  2. Check types and values on the server
  3. Return the right status or state
  4. Clear the tag of the changed data

Skipping any step is a bug; the second and the fourth are the ones most often forgotten.

General pattern: a method handler

typescript
// app/api/<resource>/route.ts
export async function POST(request: Request) {
  let body: unknown;
  try { body = await request.json(); }
  catch { return Response.json({ error: "Invalid JSON" }, { status: 400 }); }
  if (!isValid(body)) return Response.json({ error: "..." }, { status: 400 });
  const saved = await save(body);
  return Response.json(saved, { status: 201 });
}

Return 400 when parsing fails, 400 when validation fails, and 201 after creating something. A GET returns its data with 200.

Tasks 1-2: testing the Route Handler in Node

The top of this file is exactly app/api/quotes/route.ts from the Next.js project. The test part at the bottom builds a new Request() and calls POST() directly, just as Next.js would. In the project, remove the test part and check it with curl -X POST -d '{"text":"hi"}' http://localhost:3000/api/quotes -i.

app/api/quotes/route.ts (+ test)
// app/api/quotes/route.ts - Route Handlers are plain Web Request -> Response
// functions, so this file runs in Node as-is (the test calls are at the bottom).
type Quote = { text: string; author: string };

const quotes: Quote[] = [
  { text: "Make it work, make it right, make it fast.", author: "Kent Beck" },
];

export async function GET() {
  return Response.json(quotes);
}

export async function POST(request: Request) {
  let body: unknown;
  try {
    body = await request.json();
  } catch {
    return Response.json({ error: "Body must be JSON" }, { status: 400 });
  }
  const { text, author } = (body ?? {}) as Partial<Record<string, unknown>>;
  if (typeof text !== "string" || text.trim().length <= 3) {
    const error = "text must be longer than 3 characters";
    return Response.json({ error }, { status: 400 });
  }
  const quote: Quote = {
    text: text.trim(),
    author: typeof author === "string" && author.trim() ? author.trim() : "Unknown",
  };
  quotes.push(quote);
  return Response.json(quote, { status: 201 });
}

// --- quick test: call the handlers the way Next.js would ---
const post = (body: string) =>
  POST(new Request("http://localhost/api/quotes", { method: "POST", body }));

async function main() {
  const bodies = [
    JSON.stringify({ text: "Simple is better than complex." }),
    JSON.stringify({ text: "hi" }),
    "not json",
  ];
  for (const body of bodies) {
    const res = await post(body);
    console.log(res.status, JSON.stringify(await res.json()));
  }
  const list = await GET();
  const all: Quote[] = await list.json();
  console.log(list.status, all.length, "quotes");
}

main();

Code breakdown

  1. Parse failures are the client's faultreturn Response.json({ error: "Body must be JSON" }, { status: 400 });

    request.json() throws on invalid JSON. Uncaught, that is a 500, which claims the server broke; catching it and returning 400 tells the client that its request needs fixing.

  2. Treat the body as unknownconst { text, author } = (body ?? {}) as Partial<Record<string, unknown>>;

    A client can send anything, so every field starts as unknown and is checked with typeof. body ?? {} guards against a JSON body of null.

  3. Validation with a 400if (typeof text !== "string" || text.trim().length <= 3) {

    "hi" has only 2 characters, so it gets a 400. Because of trim(), a text made of four spaces is rejected too.

  4. 201 with the created resourcereturn Response.json(quote, { status: 201 });

    201 Created means a new resource exists. Returning the stored quote instead of { ok: true } lets the client see that author became "Unknown".

  5. Calling the handler directlyPOST(new Request("http://localhost/api/quotes", { method: "POST", body }));

    Handlers are Web-standard functions, so they can be unit-tested without starting a server. Using NextRequest-only extras would make this less simple.

You should see
201 {"text":"Simple is better than complex.","author":"Unknown"}
400 {"error":"text must be longer than 3 characters"}
400 {"error":"Body must be JSON"}
200 2 quotes

Task 3: the subscribe form with useActionState

You write the action's logic in the challenge; here is the form side. The form must be a Client Component because useActionState is a hook. It reads state.status to show an error or a success message, and role="alert" plus aria-live let screen readers announce the change.

app/subscribe/SubscribeForm.tsx
"use client";
import { useActionState } from "react";
import { subscribe } from "@/app/actions"; // "use server" file

export function SubscribeForm() {
  const [state, formAction, pending] = useActionState(subscribe, { status: "idle" });
  return (
    <form action={formAction}>
      <label htmlFor="email">Email</label>
      <input id="email" name="email" type="email" />
      <button type="submit" disabled={pending}>Subscribe</button>
      <p role="alert" aria-live="polite">
        {state.status === "idle" ? "" : state.message}
      </p>
    </form>
  );
}

Task 4: tagging cached data and invalidating it

lib/quotes.ts + app/actions.ts + route.ts
// lib/quotes.ts - needs cacheComponents: true (see the caching lesson)
import { cacheTag } from "next/cache";
export async function getQuotes() {
  "use cache";
  cacheTag("quotes");
  return db.quote.findMany();
}

// app/actions.ts - a Server Action: the user should see their change at once
"use server";
import { updateTag } from "next/cache";
export async function addQuote(formData: FormData) {
  await db.quote.create({ data: { text: String(formData.get("text")) } });
  updateTag("quotes");
}

// app/api/quotes/route.ts - Route Handlers cannot call updateTag
import { revalidateTag } from "next/cache";
// ...after quotes.push(quote) in POST:
revalidateTag("quotes", "max");

revalidateTag("quotes", "max") only marks the data as stale: the next visitor briefly gets the old version while fresh data loads in the background. When it must be gone immediately, the docs suggest { expire: 0 } as the second argument. The old single-argument form revalidateTag("quotes") is deprecated. The small model below shows the core idea of tag-based caching: new data stays invisible until its tag is invalidated.

tag-cache-model.ts (a model, not Next.js)
type Entry = { value: string[]; tags: string[] };

const cache = new Map<string, Entry>();
let dbQuotes = ["Make it work, make it right, make it fast."];
let loads = 0;

function cached(key: string, tags: string[], load: () => string[]): string[] {
  const hit = cache.get(key);
  if (hit) return hit.value;
  loads++;
  const value = load();
  cache.set(key, { value, tags });
  return value;
}

function invalidateTag(tag: string): void {
  for (const [key, entry] of cache) if (entry.tags.includes(tag)) cache.delete(key);
}

const getQuotes = () => cached("quotes:list", ["quotes"], () => [...dbQuotes]);

console.log(getQuotes().length, "loads:", loads);
dbQuotes = [...dbQuotes, "Simple is better than complex."];
console.log(getQuotes().length, "loads:", loads, "(stale: tag not invalidated)");
invalidateTag("quotes");
console.log(getQuotes().length, "loads:", loads, "(fresh after invalidation)");

In real projects

In real projects

Route Handlers are typically called by mobile apps, outside partners, or webhooks from services like Stripe. Those clients decide whether to retry or show an error from the status code alone, so getting it right really matters. For your own app's forms, teams reach for Server Actions rather than API routes, and a Server Component that needs data calls the data function directly instead of fetching its own Route Handler.

On CMS-driven blogs, publishing a post makes the CMS call a Route Handler through a webhook, which uses revalidateTag to refresh the affected pages. New content appears within moments without rebuilding the whole site, and readers never notice that anything was regenerated.

Common mistakes

Common mistakes

Forgetting to await request.json()

With const body = request.json(), body is a Promise and body.text is always undefined, so validation always fails and every request gets a 400. Because the value is typed as any, TypeScript often stays silent.

Returning errors with status 200

Response.json({ error }) without a status defaults to 200, so fetch's response.ok is true and the client misses the error. Give every error response a status such as { status: 400 }.

Thinking a tag alone makes data cached

A tag is only a handle for removing cached data. With fetch, caching is opt-in, so without cache: "force-cache" (or "use cache") there may be no entry to invalidate at all. The reverse mistake, tagging data but never invalidating it, keeps old data on screen.

Calling updateTag in a Route Handler

updateTag may only be called inside Server Actions; in a Route Handler it throws. Use revalidateTag(tag, "max") there instead.

Best practices

Habits worth building while practising

  • Keep the curl commands for each endpoint in a text file and rerun them after every change
  • Move validation out of route.ts and actions.ts into pure functions in lib/, which you can test without the framework
  • After writing a mutation, ask yourself which pages show that data and which tag must be cleared

Mini challenge

Write the subscribe action's logic

Write Task 3's subscribe Server Action in the (prevState, formData) => state shape that useActionState expects. Clean up the email, check its format, reject duplicates, and return one of three states: idle, error or success. Use a Set in place of a database.

  • Model SubscribeState as a discriminated union on status
  • Trim and lowercase the email before testing it with the regex
  • Include the email the user typed in the error state
  • Feed each state into the next call, as useActionState does, for three inputs
subscribe.ts
type SubscribeState =
  | { status: "idle" }
  | { status: "error"; message: string; email: string }
  | { status: "success"; message: string };

const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
const subscribers = new Set<string>();

async function subscribe(
  _prev: SubscribeState,
  formData: FormData,
): Promise<SubscribeState> {
  // TODO: read "email", trim it, lowercase it
  // TODO: invalid format -> error state; already in the Set -> error state
  // TODO: otherwise add it and return a success state
}

// TODO: loop over three inputs, passing the previous state each time

Expected: "not-an-email" gives an error state, " Ko.Aung@Example.com " gives the success state "Subscribed ko.aung@example.com", "ko.aung@example.com" gives an already-subscribed error, and the last line is subscribers: 1.

Show hint

String(formData.get("email") ?? "") guards against null. Lowercasing is what makes "Ko.Aung@Example.com" and "ko.aung@example.com" count as the same address.

Show solution
subscribe.ts
type SubscribeState =
  | { status: "idle" }
  | { status: "error"; message: string; email: string }
  | { status: "success"; message: string };

const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
const subscribers = new Set<string>(); // stands in for a database table

async function subscribe(
  _prev: SubscribeState,
  formData: FormData,
): Promise<SubscribeState> {
  const email = String(formData.get("email") ?? "").trim().toLowerCase();
  if (!EMAIL.test(email)) {
    return { status: "error", message: "Enter a valid email address", email };
  }
  if (subscribers.has(email)) {
    return { status: "error", message: "That email is already subscribed", email };
  }
  subscribers.add(email);
  return { status: "success", message: `Subscribed ${email}` };
}

// Simulate what useActionState does: feed each result into the next call.
async function main() {
  let state: SubscribeState = { status: "idle" };
  for (const input of ["not-an-email", " Ko.Aung@Example.com ", "ko.aung@example.com"]) {
    const form = new FormData();
    form.set("email", input);
    state = await subscribe(state, form);
    console.log(JSON.stringify(input), "->", JSON.stringify(state));
  }
  console.log("subscribers:", subscribers.size);
}

main();

Quick quiz 1 / 3

The first draft's POST (no try/catch) receives the body "not json". What status does the client get?

Quick quiz 2 / 3

With useActionState(subscribe, { status: "idle" }), what is subscribe's first argument?

Quick quiz 3 / 3

Inside app/api/revalidate/route.ts, called by a CMS webhook, what should invalidate the "quotes" tag?

What to remember

  • A Route Handler is a Request-to-Response function, so you can test it directly with new Request()
  • Return 400 for invalid JSON and failed validation, and 201 for a created resource
  • With useActionState, the action receives (prevState, formData) and returns the next state
  • Attach tags to cached data, then clear them with updateTag in Server Actions or revalidateTag(tag, "max") in Route Handlers

Next.js Documentation — Next.js

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Practice Set 2 — Data Fetching, Server Actions, and Caching Exercises | Thuta Learning