Skip to Content
ZarexDocs

SvelteKit

Protect a SvelteKit application with the @zarex/sveltekit server hook.

Installation

npm install @zarex/sveltekit
.env
ZAREX_KEY=zarex_test_...

Declare the key

SvelteKit 3 only passes declared environment variables to your code. Declare the key once:

src/env.ts
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

src/hooks.server.ts
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:

src/hooks.server.ts
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

src/hooks.server.ts
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:

src/routes/+page.server.ts
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.

On this page