Next.jsMedium

How do you test API routes in Next.js?

App Router Route Handlers are plain functions that take a Web Request and return a Response, so you can import GET or POST in a unit test, call it with new Request(...) (or new NextRequest(...)), and assert on response.status and await response.json(). Mock the database and next/headers as needed, and add E2E or HTTP-level tests against a running server for full coverage.

Unit testing Route Handlers

  • Build requests: new NextRequest("http://localhost/api/posts?page=2", { method: "POST", body: JSON.stringify(data) }).
  • Pass the context: { params: Promise.resolve({ id: "1" }) }, because params is a Promise.
  • Mock external services (database client, email) with vi.mock.
  • If the handler uses cookies() or headers(), mock next/headers.
  • Run in the Node test environment, not jsdom.

Pages Router API routes

Use node-mocks-http to create req/res objects, or next-test-api-route-handler, which runs the handler through Next.js's resolver.

Proxy

next/experimental/testing/server exports unstable_doesMiddlewareMatch (matcher checks), isRewrite and getRewrittenUrl to assert Proxy behavior in unit tests.

Integration and E2E

  • Start the app and hit endpoints with Playwright's request fixture or supertest-style HTTP calls.
  • Test auth (401/403), validation (400/422), and rate limiting (429) paths, not only success.

Server Functions

Import them and call them directly with FormData, mocking verifySession and the database. Assert on returned state, and that updateTag or redirect were called (mock next/cache and next/navigation).

Code example

tsx
1// app/api/posts/[id]/route.test.ts (Vitest, environment: node)
2import { describe, it, expect, vi } from "vitest";
3import { NextRequest } from "next/server";
4
5vi.mock("@/lib/db", () => ({
6 db: {
7 post: {
8 findUnique: vi.fn(async ({ where }: { where: { id: string } }) =>
9 where.id === "1" ? { id: "1", title: "Hello" } : null
10 ),
11 },
12 },
13}));
14
15import { GET } from "./route";
16
17const ctx = (id: string) => ({ params: Promise.resolve({ id }) });
18
19describe("GET /api/posts/[id]", () => {
20 it("returns the post", async () => {
21 const res = await GET(new NextRequest("http://localhost/api/posts/1"), ctx("1"));
22 expect(res.status).toBe(200);
23 expect(await res.json()).toEqual({ id: "1", title: "Hello" });
24 });
25
26 it("returns 404 for unknown ids", async () => {
27 const res = await GET(new NextRequest("http://localhost/api/posts/9"), ctx("9"));
28 expect(res.status).toBe(404);
29 });
30});

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the Next.js set.

Open in study app