Fastify
Protect a Fastify application (or NestJS on Fastify) with the @zarex/fastify hook.
Installation
npm install @zarex/fastifyZAREX_KEY=zarex_test_...Node.js doesn't load this file by itself: start the application with node --env-file=.env server.ts (Node 24 runs TypeScript directly when your package.json contains "type": "module"), or use the dotenv package.
Protect the application
import Fastify from "fastify";
import { zarexFastify, shield, rateLimit } from "@zarex/fastify";
const app = Fastify();
app.addHook(
"onRequest",
zarexFastify({
key: process.env.ZAREX_KEY!,
rules: [shield(), rateLimit({ max: 100, window: "1m" })],
})
);
app.get("/", async () => ({ ok: true }));
app.listen({ port: 3000 });A denied request automatically receives 403, or 429 with retry-after.
With NestJS
import type { FastifyInstance } from "fastify";
(app.getHttpAdapter().getInstance() as FastifyInstance).addHook(
"onRequest",
zarexFastify({ key: process.env.ZAREX_KEY!, rules: [shield()] })
);The visitor's IP address
Zarex uses request.ip, computed by Fastify according to your server's trustProxy option. Behind a proxy, set it to match your actual infrastructure: otherwise all your visitors seem to come from the same address.
Inspect request bodies
Pick the right hook
In onRequest, Fastify has not read the body yet: it cannot be inspected (it is by default since 0.2.0). Register the hook as preHandler.
app.addHook(
"preHandler",
zarexFastify({ key: process.env.ZAREX_KEY!, rules: [shield()] })
);Identifiers and form data
app.addHook(
"preHandler",
zarexFastify({
key: process.env.ZAREX_KEY!,
rules: [rateLimit({ max: 100, window: "1m", characteristics: ["userId"] })],
call: (req) => ({ characteristics: { userId: req.user?.id } }),
})
);call can also provide email, phone, text and tokensRequested. Identifiers are hashed (SHA-256) before being sent.
Read the decision
app.get("/", async (req) => {
console.log(req.zarex?.verdict); // "ALLOW" | "DENY"
return { ok: true };
});Customize the denial
zarexFastify({
key: process.env.ZAREX_KEY!,
rules: [shield()],
onDeny: (req, reply, decision) => {
reply.code(403).send({ error: "Request denied", id: decision.id });
},
});Security headers and responses
secureHeaders: true adds security headers to every response. To watch your application's responses, Fastify needs a second hook:
import { zarexFastifyOnSend } from "@zarex/fastify";
app.addHook("onSend", zarexFastifyOnSend({ responseGuard: true }));