Keploy logo
Next.js logo

Keploy as a Next.js testing framework

Keploy tests Next.js APIs by recording real requests through the running server and every database or outbound call a route handler makes, then replaying both as assertions. Route handlers, middleware, and server actions all execute over a real socket.

Generate Next.js tests free
keploy record -c "npm run start"
18.4K+VS Code1.2M+300M+mocks created

What Keploy gives a Next.js team

App Router and Pages Router alike

Keploy runs the production server. Route handlers, API routes, server actions, and middleware all record the same way because capture is at the socket rather than inside the Next runtime.

  • Next.js 13 and above
  • App Router and Pages Router
  • Route handlers and server actions
  • Node runtime, not Edge
The problem

Why Next.js integration tests slow teams down

The friction is rarely the assertions. It is everything around them — spinning up dependencies, keeping mocks honest, and repairing tests after every refactor.

Three ways to do it

Testing Next.js: by hand, with Jest + next-test-api-route-handler, or with Keploy

Mocking the database module makes a route pass regardless of whether its query is right. Keploy records the running server, so the real query executes and its rows replay.

Select any row for the full comparison, with code.

Same coverage, three costs

What you write for Next.js vs what Keploy records

All three produce the same assertion. Only the third still passes after the next refactor without anyone editing it.

By hand2–4 hours
route.test.ts
hand-written
// Hand-written: the db module is mocked, so the query is never run.
import { POST } from '../app/orders/[id]/confirm/route';
 
jest.mock('@/lib/db', () => ({
db: {
order: {
// Returns rows whatever the query asked for.
findUnique: async () => ({ id: 'ord_1', amountMinor: 4200 }),
update: async (args) => args.data,
},
},
}));
 
it('confirms an authorized order', async () => {
const req = new Request('http://localhost/orders/ord_1/confirm', {
method: 'POST',
body: JSON.stringify({ paymentToken: 'tok_123' }),
});
 
const res = await POST(req, { params: { id: 'ord_1' } });
 
expect(res.status).toBe(200);
});

The Prisma mock answers regardless of the query, so a wrong where clause or a missing include passes here and returns nothing in production.

Jest + next-test-api-route-handler1–2 hours
route.harness.test.ts
tool-assisted
// A route-handler harness plus a mocked fetch.
import { testApiHandler } from 'next-test-api-route-handler';
import * as appHandler from '../app/orders/[id]/confirm/route';
 
it('confirms an authorized order', async () => {
global.fetch = jest.fn(async () =>
new Response(JSON.stringify({ status: 'AUTHORIZED' }), { status: 200 }),
) as unknown as typeof fetch;
 
await testApiHandler({
appHandler,
params: { id: 'ord_1' },
test: async ({ fetch }) => {
const res = await fetch({
method: 'POST',
body: JSON.stringify({ paymentToken: 'tok_123' }),
});
expect(res.status).toBe(200);
},
});
});

Closer to a real request, and global fetch is replaced wholesale — so every upstream in the handler now returns the same canned body.

With Keploy~5 minutes
test-1.yaml
auto-generated
# Recorded with: keploy record -c 'npm run start'
# Nobody wrote this file. Keploy captured it from a real request.
version: api.keploy.io/v1beta1
kind: Http
name: test-1
spec:
req:
method: POST
url: /orders/ord_1/confirm
body: '{"paymentToken":"tok_123"}'
resp:
status_code: 200
body:
id: "ord_1"
state: "CONFIRMED"
amountMinor: 4200
noise:
- body.confirmedAt
mocks:
- kind: Postgres
operation: "SELECT \"id\", \"amount_minor\", \"state\" FROM \"orders\" WHERE \"id\" = $1 LIMIT $2"
- kind: Http
url: https://api.payments.example.com/v1/payment_intents/tok_123/confirm

The recorded case ran through the real server, so middleware, cookies(), and the actual Prisma query all executed on the way to this response.

Times are estimates for authoring one endpoint’s coverage from scratch, not measurements.

Keploy vs the alternatives

Next.js testing tools, compared

The options a team on Node.js actually reaches for, and where each one genuinely wins. Select a row for the full comparison.

Best in classStrongPartialNot covered

Assessments reflect each tool’s documented behaviour, not benchmark measurements.

How it works

Record your Next.js app once, replay it forever

Keploy sits below your Next.js process at the network layer. It watches the calls your app already makes, then serves them back on replay so tests run with no dependencies attached.

Keploy records a GET call to /api/v1/orders/{id} on a Next.js service and captures the dependency calls it makes.

Next.js logo
Your Next.js app
GET/api/v1/orders/{id}200
RecordingKeploy proxyeBPF · userspace
+3 more Next.js dependencies
An example shape of a captured call. Your own endpoints and dependencies come from your real traffic, so nothing here has to be written by hand.
Mock coverage

What Keploy mocks for Next.js, with zero config

7 of the 7 dependencies a typical Next.js service talks to are stubbed from the recording itself — no mock classes, no fixture files, no containers in CI.

Quick start

Your first Next.js test suite in under five minutes

Every command below runs against your existing Next.js service. Nothing in your source tree changes.

  1. 1Install the Keploy CLI

    A single binary. It needs a Linux kernel with eBPF support, or Docker on macOS and Windows — and it adds nothing to your project's dependencies.

    curl -sSL https://keploy.io/install.sh | bash
  2. 2Record your service

    Pass the command you already use to start the app. Keploy runs it and watches every socket it opens.

    keploy record -c "npm run start"
  3. 3Exercise the paths you care about

    Drive the running server. Every request becomes a test case with its database and HTTP calls captured alongside.

    npm run build
    curl -X POST localhost:3000/orders/ord_1/confirm -H 'Content-Type: application/json' -d '{"paymentToken":"tok_123"}'
  4. 4Replay in CI

    Replay serves the recorded dependency responses, so the job needs no service containers and no Docker daemon.

    keploy test -c "npm run start" --delay 12

Ready to try it on your own Next.js service?

Ecosystem

Works with the rest of your Next.js stack

Keploy records at the network layer, so framework and driver choices inside your Next.js app do not change how it captures traffic.

FAQ

Next.js testing with Keploy: common questions

Join our GlobalCommunity

Connect with developers worldwide. Follow updates, ask questions, share feedback, and ship faster with other Keploy builders.

1.2M+Installs
18.4K+GitHub
100K+Devs
300M+Mocks
1K+Contributors
#1OSS Trending
4.9★★★★★from 500+ reviews onG2GartnerVS CodeChrome
★★★★★

Best report of integration and API tests I've seen — which we don't get from RestAssured.

G2
★★★★★

Future of microservices testing. I don't write tests now!

G2 · 5/5
★★★★★

An amazing product that simplifies the automation.

Gartner · 4.0
XGitHubSlackYouTubeLinkedIn
Built by developers, for developers.Let's build the future, together.