Next.js
Protect a Next.js application with @zarex/next, in a route handler or for every route.
@zarex/next works in route handlers and in the file that intercepts every request (proxy.ts from Next.js 16, middleware.ts before). It only uses the standard Request and Response objects.
Installation
npm install @zarex/nextAdd your key to .env.local (without the NEXT_PUBLIC_ prefix):
ZAREX_KEY=zarex_test_...Protect a route handler
import { withZarex, shield, rateLimit } from "@zarex/next";
export const GET = withZarex(
{
key: process.env.ZAREX_KEY!,
ipSource: "vercel",
rules: [shield(), rateLimit({ max: 100, window: "1m" })],
},
async () => Response.json({ products: [] })
);A denied request automatically receives 403, or 429 with Retry-After, without your handler being called.
Protect every route
import { NextResponse } from "next/server";
import { zarexNext, shield, rateLimit } from "@zarex/next";
const guard = zarexNext({
key: process.env.ZAREX_KEY!,
ipSource: "vercel",
rules: [shield(), rateLimit({ max: 100, window: "1m" })],
});
export async function proxy(request: Request) {
return (await guard(request)) ?? guard.finalize(NextResponse.next(), request);
}guard(request) returns the denial response, or null if the request can continue.
Don't forget finalize
If you enable secureHeaders or responseGuard, also call guard.finalize(...) on the allowed response, as above: otherwise these protections never apply to allowed traffic. With withZarex, it is automatic.
The visitor's IP address
Next.js never exposes the connection address: Zarex reads it from a header written by your host or your proxy.
| Hosting | ipSource |
|---|---|
| Vercel | Nothing to do (detected automatically), or "vercel". |
| Fly.io | Nothing to do (detected automatically), or "fly". |
| Cloudflare Workers or Pages | Nothing to do (detected automatically), or "cloudflare-workers". |
| VPS or Docker behind nginx or Caddy | { header: "x-real-ip" }, the header written by your proxy. |
| Cloudflare in front of your server | { header: "cf-connecting-ip" } |
Anywhere else, without ipSource, the application refuses to start rather than guess.
No { proxies } or "cloudflare" with Next.js
These settings need the connection address, which Next.js does not provide: requests would go through unchecked. With { header }, the proxy must overwrite the header, and the application must only be reachable through it. nginx and Caddy configuration: see The visitor's IP address.
Running locally
next dev passes your local address in x-forwarded-for, and nothing else.
- With
ipSource: "vercel": requests are checked. The console shows warnings (VERCELnot set, fallback header, private address): they are expected locally, nothing to fix. - With
ipSource: { header: "x-real-ip" }:next devdoesn't provide this header, so requests go through unchecked (a warning says so). Test by adding it yourself:
curl -H "X-Real-IP: 41.0.0.1" "http://localhost:3000/api/products?id=1%27%20OR%20%271%27=%271"Form data
withZarex reads the request before your handler: to validate an email, a phone number or text typed into a form, use createZarex instead and call protect yourself, with the data you have already read.
"use server";
import { headers } from "next/headers";
import { createZarex, emailValidation, rateLimit } from "@zarex/next";
const zarex = createZarex({
key: process.env.ZAREX_KEY!,
ipSource: "vercel",
rules: [rateLimit({ max: 5, window: "10m" }), emailValidation()],
});
export async function signup(email: string) {
const h = await headers();
const decision = await zarex.protect(
{ method: "POST", path: "/signup", headers: h },
{ email }
);
if (decision.denied) return { ok: false };
// … create the account
return { ok: true };
}Customize the denial
withZarex(
{
key: process.env.ZAREX_KEY!,
rules: [shield()],
onDeny: (request, decision) =>
Response.json({ error: "Request denied", id: decision.id }, { status: 403 }),
},
handler
);onDeny receives the full decision and must always return a Response: that is what is sent to the visitor instead of your handler. If it returns nothing (a forgotten return, for example), the SDK sends the default denial response and reports it in your logs: the request stays blocked (since version 0.1.4). onDegraded(request, decision) is called when Zarex could not decide and the request was let through.