Skip to the code

A tea API that answers 304 Not Modified

Leaf and Kettle's mobile app checks a tea's price every few seconds while a customer is looking at it. Nearly always nothing has changed, and sending the same JSON again wastes the customer's data. Write the GET handler in app/api/teas/[slug]/route.ts with ETags, so the app can ask whether the tea has changed and get an empty answer when it hasn't.

For a slug that getTea from @/lib/teas can't find, answer 404 with { error: "No tea called coffee" }, with the slug in the message, whatever the request's other headers say.

Otherwise answer { slug, name, price } with status 200 and two headers. ETag is the tea's slug and version in double quotes, like "green-v3" for version 3 of green tea, so it changes whenever the tea does. Cache-Control: no-cache lets the app keep the answer, but makes it ask the server before using it again.

The app asks by sending the ETag it has in an If-None-Match header. When that matches the tea's current ETag, answer 304 Not Modified, with no body and the same ETag and Cache-Control headers. The header can list several ETags separated by commas, and any of them can match; a weak ETag, written W/"green-v3", matches as well; and * matches any tea that exists.

When nothing matches, because the tea has changed since (setPrice moves its version on), answer 200 with the tea and its new ETag.

GET /api/teas/green
→ 200 { slug: "green", name: "Green tea", price: 4 }    ETag: "green-v3"
 
GET /api/teas/green    If-None-Match: "green-v3"
→ 304, no body                                         ETag: "green-v3"

The app's other files

lib/teas.ts, read-only. Import it as @/lib/teas.

export type Tea = { slug: string; name: string; price: number; version: number };
 
/** The teas, each with a version the database moves on whenever the tea changes. */
export const teas: Tea[] = [
  { slug: "green", name: "Green tea", price: 4, version: 3 },
  { slug: "mint", name: "Mint tea", price: 3, version: 1 },
  { slug: "oolong", name: "Oolong tea", price: 5, version: 7 },
];
 
/** The tea with this slug, or undefined when there's none. */
export async function getTea(slug: string): Promise<Tea | undefined> {
  return teas.find((tea) => tea.slug === slug);
}
 
/** Changes a tea's price, as the shop's admin page does, which moves its version on. */
export async function setPrice(slug: string, price: number) {
  const tea = teas.find((item) => item.slug === slug);
  if (tea) {
    tea.price = price;
    tea.version += 1;
  }
}

What the tests check

  1. answers the tea with an ETag and Cache-Control: no-cache
    const response = await GET(request("/api/teas/green"), { params: params({ slug: "green" }) });
    expect(response.status).toBe(200);
    expect(await response.json()).toEqual({ slug: "green", name: "Green tea", price: 4 });
    expect(response.headers.get("etag")).toBe('"green-v3"');
    expect(response.headers.get("cache-control")).toBe("no-cache");
    
  2. answers 304 with no body when If-None-Match is the current ETag
    const response = await GET(request("/api/teas/oolong", { headers: { "if-none-match": '"oolong-v7"' } }), { params: params({ slug: "oolong" }) });
    expect(response.status).toBe(304);
    expect(await response.text()).toBe("");
    expect(response.headers.get("etag")).toBe('"oolong-v7"');
    expect(response.headers.get("cache-control")).toBe("no-cache");
    
  3. sends the new price and ETag once the tea has changed
    const get = (etag) => GET(request("/api/teas/mint", { headers: etag ? { "if-none-match": etag } : {} }), { params: params({ slug: "mint" }) });
    const first = await get();
    const etag = first.headers.get("etag");
    expect(etag).toBe('"mint-v1"');
    await setPrice("mint", 3.5);
    const changed = await get(etag);
    expect(changed.status).toBe(200);
    expect(await changed.json()).toEqual({ slug: "mint", name: "Mint tea", price: 3.5 });
    expect(changed.headers.get("etag")).toBe('"mint-v2"');
    expect((await get('"mint-v2"')).status).toBe(304);
    
  4. matches any ETag in a list, weak ones, and *
    for (const header of ['"green-v1", "green-v3"', 'W/"green-v3"', '"oolong-v7",W/"green-v3"', "*"]) {
      const response = await GET(request("/api/teas/green", { headers: { "if-none-match": header } }), { params: params({ slug: "green" }) });
      expect(response.status).toBe(304);
    }
    
  5. answers 200 when no ETag in If-None-Match matches
    for (const header of ['"green-v2"', '"mint-v3"', 'W/"green-v30"', '"green-v2", "green-v4"']) {
      const response = await GET(request("/api/teas/green", { headers: { "if-none-match": header } }), { params: params({ slug: "green" }) });
      expect(response.status).toBe(200);
      expect(response.headers.get("etag")).toBe('"green-v3"');
    }
    
  6. answers 404 for an unknown tea, whatever If-None-Match says
    const response = await GET(request("/api/teas/coffee", { headers: { "if-none-match": "*" } }), { params: params({ slug: "coffee" }) });
    expect(response.status).toBe(404);
    expect(await response.json()).toEqual({ error: "No tea called coffee" });
    

Learn more

app/api/teas/[slug]/route.tsSaved in this browser

Run tests runs every test on your code, here in your browser. The problem is solved when they all pass.

Ctrl + Enter runs the tests (⌘ + Enter on a Mac).