SvelteKit
Protect a SvelteKit application with the @zarex/sveltekit server hook.
Installation
npm install @zarex/sveltekitZAREX_KEY=zarex_test_...Declare the key
SvelteKit 3 only passes declared environment variables to your code. Declare the key once:
import { defineEnvVars } from "@sveltejs/kit/env";
export const variables = defineEnvVars({
ZAREX_KEY: {},
});The key becomes required, is read when the server starts and is never sent to the browser. Import it from $app/env/private.
SvelteKit 2
No src/env.ts: import the key with import { ZAREX_KEY } from "$env/static/private";. Don't use process.env.ZAREX_KEY: in development, it doesn't contain the values of your .env file.
Protect the application
import { ZAREX_KEY } from "$app/env/private";
import { zarexHandle, shield, rateLimit } from "@zarex/sveltekit";
export const handle = zarexHandle({
key: ZAREX_KEY,
rules: [shield(), rateLimit({ max: 100, window: "1m" })],
});With other hooks, combine them with sequence:
import { sequence } from "@sveltejs/kit/hooks";
import { ZAREX_KEY } from "$app/env/private";
import { zarexHandle, shield } from "@zarex/sveltekit";
export const handle = sequence(
zarexHandle({ key: ZAREX_KEY, rules: [shield()] }),
myOtherHandle
);A denied request automatically receives 403, or 429 with retry-after.
The visitor's IP address
Zarex uses event.getClientAddress(), provided by your deployment adapter. With adapter-node behind a proxy, set the ADDRESS_HEADER and XFF_DEPTH variables; with other adapters, see their documentation.
Identifiers and form data
export const handle = zarexHandle({
key: ZAREX_KEY,
rules: [rateLimit({ max: 100, window: "1m", characteristics: ["userId"] })],
call: (event) => ({ characteristics: { userId: event.locals.user?.id } }),
});call can also provide email, phone, text and tokensRequested. Identifiers are hashed (SHA-256) before being sent.
Read the decision
The decision is available in locals.zarex:
export function load({ locals }) {
console.log(locals.zarex?.verdict); // "ALLOW" | "DENY"
}Customize the denial
zarexHandle({
key: ZAREX_KEY,
rules: [shield()],
onDeny: (event, decision) =>
new Response("Request denied", { status: 403 }),
});onDeny must always return a Response: that is what is sent to the visitor. 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).
Security headers and responses
secureHeaders: true and responseGuard: true apply automatically to every response, with no other setting.