Skip to the code

Edit and delete your own reviews

The mobile app shows each review at /api/reviews/<id> and lets its author fix or remove it. Write three handlers in app/api/reviews/[id]/route.ts, one exported function per method: GET, PATCH, and DELETE. Next.js answers POST and PUT here with 405 by itself.

GET is public: answer the review from getReview(id) in @/lib/reviews (the id as a number), or 404 with { error: "Review not found" }.

PATCH and DELETE need a signed-in user. The app sends its token as Authorization: Bearer <token>, and userForToken(token) from @/lib/auth says whose it is. With no such header, another scheme, or a token nobody has, answer 401 with { error: "Sign in to change reviews" } and the header WWW-Authenticate: Bearer. After that, a review that doesn't exist gets the same 404 as GET, and someone else's review gets 403 with { error: "You can only change your own reviews" }.

PATCH takes a JSON object with rating, text, or both, checked as when a review is written: rating a whole number from 1 to 5 (Rating must be a whole number from 1 to 5), and text 10 to 500 characters long once trimmed (Text must be 10 to 500 characters). Wrong fields get 400 with { errors } and nothing is saved; a body that isn't a JSON object, or has neither field, gets 400 with { error: "Send a rating or a text to change" }. Save only those two fields with updateReview, and answer 200 with the review as saved.

DELETE removes the review with deleteReview and answers 204 No Content, with no body.

PATCH /api/reviews/1    Authorization: Bearer token-ana
{ "text": "Even better iced." }
→ 200 { id: 1, tea: "mint", author: "ana", rating: 5, text: "Even better iced." }
 
DELETE /api/reviews/1   Authorization: Bearer token-ben
→ 403 { error: "You can only change your own reviews" }

The app's other files

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

export type User = { id: string; name: string };
 
const tokens = new Map<string, User>([
  ["token-ana", { id: "ana", name: "Ana" }],
  ["token-ben", { id: "ben", name: "Ben" }],
]);
 
/** The user an API token belongs to, or undefined for a token nobody has. */
export async function userForToken(token: string): Promise<User | undefined> {
  return tokens.get(token);
}

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

export type Review = { id: number; tea: string; author: string; rating: number; text: string };
 
/** Every review, with the id of the user who wrote it. A real shop keeps them in its database. */
export const reviews: Review[] = [
  { id: 1, tea: "mint", author: "ana", rating: 5, text: "Cool, sweet, and fresh." },
  { id: 2, tea: "oolong", author: "ben", rating: 4, text: "Rich, with a long finish." },
];
 
/** The review with this id, or undefined when there's none. */
export async function getReview(id: number): Promise<Review | undefined> {
  return reviews.find((review) => review.id === id);
}
 
/** Saves these changes to the review with this id, and returns it as saved. */
export async function updateReview(id: number, changes: Partial<Review>): Promise<Review | undefined> {
  const review = reviews.find((item) => item.id === id);
  if (review) Object.assign(review, changes);
  return review;
}
 
/** Removes the review with this id. */
export async function deleteReview(id: number) {
  const index = reviews.findIndex((review) => review.id === id);
  if (index !== -1) reviews.splice(index, 1);
}

What the tests check

  1. GET answers a review to anyone, and 404 for one that isn't there
    const response = await GET(request("/api/reviews/2"), { params: params({ id: "2" }) });
    expect(response.status).toBe(200);
    expect(await response.json()).toEqual({ id: 2, tea: "oolong", author: "ben", rating: 4, text: "Rich, with a long finish." });
    const missing = await GET(request("/api/reviews/9"), { params: params({ id: "9" }) });
    expect(missing.status).toBe(404);
    expect(await missing.json()).toEqual({ error: "Review not found" });
    
  2. PATCH and DELETE answer 401 first, with WWW-Authenticate, without a valid token
    const before = JSON.stringify(reviews);
    for (const authorization of [null, "token-ana", "Basic token-ana", "Bearer nobody", "Bearer "]) {
      const headers = { "content-type": "application/json" };
      if (authorization !== null) headers.authorization = authorization;
      const patch = await PATCH(request("/api/reviews/1", { method: "PATCH", headers, body: JSON.stringify({ rating: 1 }) }), { params: params({ id: "1" }) });
      const remove = await DELETE(request("/api/reviews/1", { method: "DELETE", headers }), { params: params({ id: "1" }) });
      for (const response of [patch, remove]) {
        expect(response.status).toBe(401);
        expect(response.headers.get("www-authenticate")).toBe("Bearer");
        expect(await response.json()).toEqual({ error: "Sign in to change reviews" });
      }
    }
    expect(JSON.stringify(reviews)).toBe(before);
    const missing = await DELETE(request("/api/reviews/9", { method: "DELETE" }), { params: params({ id: "9" }) });
    expect(missing.status).toBe(401);
    
  3. PATCH changes the author's own review, and only its rating and text
    const patch = (body) =>
      PATCH(request("/api/reviews/1", { method: "PATCH", headers: { authorization: "Bearer token-ana", "content-type": "application/json" }, body: JSON.stringify(body) }), {
        params: params({ id: "1" }),
      });
    const response = await patch({ text: "  Even better iced.  ", author: "ben", id: 7 });
    expect(response.status).toBe(200);
    const saved = { id: 1, tea: "mint", author: "ana", rating: 5, text: "Even better iced." };
    expect(await response.json()).toEqual(saved);
    expect(reviews[0]).toEqual(saved);
    const rated = await patch({ rating: 3 });
    expect(await rated.json()).toEqual({ ...saved, rating: 3 });
    
  4. PATCH answers 400 for changes it can't take, and saves none of them
    const send = async (body) => {
      const response = await PATCH(
        request("/api/reviews/2", { method: "PATCH", headers: { authorization: "Bearer token-ben", "content-type": "application/json" }, body }),
        { params: params({ id: "2" }) },
      );
      expect(response.status).toBe(400);
      return response.json();
    };
    expect(await send(JSON.stringify({ rating: 9 }))).toEqual({ errors: { rating: "Rating must be a whole number from 1 to 5" } });
    expect(await send(JSON.stringify({ rating: 2, text: "Meh" }))).toEqual({ errors: { text: "Text must be 10 to 500 characters" } });
    for (const body of [JSON.stringify({}), JSON.stringify({ stars: 5 }), "[]", "not json"]) {
      expect(await send(body)).toEqual({ error: "Send a rating or a text to change" });
    }
    expect(reviews[1]).toEqual({ id: 2, tea: "oolong", author: "ben", rating: 4, text: "Rich, with a long finish." });
    
  5. answers 403 for someone else's review, and 404 for one that isn't there
    const as = (method, id) =>
      (method === "PATCH" ? PATCH : DELETE)(
        request("/api/reviews/" + id, {
          method,
          headers: { authorization: "Bearer token-ben", "content-type": "application/json" },
          body: method === "PATCH" ? JSON.stringify({ rating: 1 }) : undefined,
        }),
        { params: params({ id: String(id) }) },
      );
    for (const method of ["PATCH", "DELETE"]) {
      const response = await as(method, 1);
      expect(response.status).toBe(403);
      expect(await response.json()).toEqual({ error: "You can only change your own reviews" });
      const missing = await as(method, 9);
      expect(missing.status).toBe(404);
      expect(await missing.json()).toEqual({ error: "Review not found" });
    }
    expect(reviews.map((review) => review.id)).toEqual([1, 2]);
    expect(reviews[0].rating).toBe(5);
    
  6. DELETE removes the author's own review and answers 204 with no body
    const response = await DELETE(request("/api/reviews/2", { method: "DELETE", headers: { authorization: "Bearer token-ben" } }), { params: params({ id: "2" }) });
    expect(response.status).toBe(204);
    expect(await response.text()).toBe("");
    expect(reviews.map((review) => review.id)).toEqual([1]);
    expect((await GET(request("/api/reviews/2"), { params: params({ id: "2" }) })).status).toBe(404);
    

Learn more

app/api/reviews/[id]/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).