@zitadel/sdk-sveltekit
v0.7.0
Published
SvelteKit handle hook and helpers for Zitadel
Readme
@zitadel/sdk-sveltekit
SvelteKit handle hook and helpers for Zitadel.
Installation
pnpm add @zitadel/sdk-sveltekit@latestRequirements
Peer dependencies: @sveltejs/kit ^3.0.0 and svelte ^5.0.0.
TypeScript ≥ 5.0, the floor shared by every SDK; see the compatibility notes.
Setup
1. Server hook
Declare the three server-only settings in src/env.ts, so SvelteKit 3 serves
them from $app/env/private: from .env.local in dev, and from the platform's
environment in production. A missing one fails each request with an error naming it, and SvelteKit never
bundles them for the browser. An app that already has src/env.ts adds the
three entries to its own defineEnvVars call:
import { defineEnvVars } from '@sveltejs/kit/env';
export const variables = defineEnvVars({
ZITADEL_URL: {},
ZITADEL_PROJECT_SECRET: {},
ZITADEL_PROJECT_ID: {},
});Then create (or extend) src/hooks.server.ts:
import { ZITADEL_PROJECT_ID, ZITADEL_PROJECT_SECRET, ZITADEL_URL } from '$app/env/private';
import { createNextgenHandle } from '@zitadel/sdk-sveltekit/server';
export const handle = createNextgenHandle({
url: ZITADEL_URL,
projectSecret: ZITADEL_PROJECT_SECRET,
projectId: ZITADEL_PROJECT_ID,
protectedRoutes: ['/admin', '/dashboard*'],
loginPath: '/login',
});Left out, url, projectSecret and projectId default to the same names on
process.env, which SvelteKit never fills from .env files.
The hook runs on every request and does three things in one pass:
- Proxies
/__nextgen/*requests to the auth backend. The project secret is attached as the bearer only on thePOST /sessions/exchangehandoff, and never reaches the browser. - Verifies the session JWT via JWKS using the Web Crypto API and writes the
result to
event.locals.nextgenAuth. - Redirects unauthenticated requests to
loginPathfor protected routes, with the requested path and query string in?next=, where<zitadel-login>returns after sign-in.
Compose it with your existing hooks via sequence():
import { sequence } from '@sveltejs/kit/hooks';
import { createNextgenHandle } from '@zitadel/sdk-sveltekit/server';
export const handle = sequence(createNextgenHandle({ /* … */ }), myOtherHandle);2. Type the auth locals
@zitadel/sdk-sveltekit/server augments App.Locals with nextgenAuth
automatically. Make sure your src/app.d.ts keeps the App namespace:
declare global {
namespace App {
// nextgenAuth is merged in by @zitadel/sdk-sveltekit
interface Locals {}
}
}
export {};3. Reading auth in a load function or endpoint
import { getAuth } from '@zitadel/sdk-sveltekit/server';
import { redirect } from '@sveltejs/kit';
export const load = (event) => {
const auth = getAuth(event);
if (!auth.isAuthenticated) throw redirect(302, '/login');
// Forward only client-safe fields to the page — never the raw token.
return { identifier: auth.session.identifier };
};protectedRoutes guards full page loads (a direct visit or a reload): the hook
redirects before anything renders. Client-side navigation, such as following a
link to /profile, does not request the page from the server, so the hook does
not run. There the ZitadelSession card is the guard: when it finds no session
it navigates to its postSignOutUrl, so a signed-out visitor still ends at
/login.
To keep a page from rendering at all without a session, guard it on the server
with a load like the one above in its +page.server.ts. SvelteKit fetches that
load's data from the server on client-side navigation too, so the redirect runs
before the page renders either way:
// src/routes/profile/+page.server.ts
import { redirect } from '@sveltejs/kit';
import { getAuth } from '@zitadel/sdk-sveltekit/server';
import type { PageServerLoad } from './$types';
export const load: PageServerLoad = (event) => {
if (!getAuth(event).isAuthenticated) throw redirect(303, '/login');
};A universal +page.ts load does not work for this: it runs in the browser on
client-side navigation, where the hook's locals are not available.
4. Render the login widget
Install the Svelte component library and render its ZitadelLogin component.
@zitadel/sdk-sveltekit is server-only; the widget comes from @zitadel/sdk-svelte:
pnpm add @zitadel/sdk-svelte@latest<script lang="ts">
import { onMount } from 'svelte';
import { ZitadelLogin, configureZitadel } from '@zitadel/sdk-svelte';
const project = configureZitadel({ projectId: 'demo', proxyPath: '/__nextgen' });
let mounted = $state(false);
onMount(() => {
mounted = true;
});
</script>
{#if mounted}
<ZitadelLogin {project} purpose="login" postSignInUrl="/admin" />
{/if}The widget mounts on the client only: its config is set as element properties,
which server-rendered markup cannot carry, so it is created in the browser with
its config in place. onMount never runs during SSR, unlike the deprecated
$app/environment check, which warns on every dev render.
To read the project id from the environment, use Vite's
import.meta.env.VITE_ZITADEL_PROJECT_ID, which SvelteKit exposes to the
browser (zitadel setup seeds it in .env.local).
ZitadelSession renders the signed-in "signed in as" card with a sign-out
button, and ZitadelLogout a sign-out control on its own. Mount them the same
way:
{#if mounted}
<ZitadelSession {project} postSignOutUrl="/login" />
{/if}The widgets' events surface as optional callbacks: onFlowStep, onFlowInput,
onFlowComplete, onFlowRedirect and onFlowError on ZitadelLogin, and
onSignout on ZitadelLogout and ZitadelSession. Pass
locales={businessLocales} (exported from @zitadel/sdk-svelte) to show
work-email copy for a business audience.
Middleware options
| Option | Type | Default | Description |
| ------------------- | -------------------- | -------------------- | ---------------------------------------------------------------------------------------------- |
| url | string | ZITADEL_URL env | Full URL of the Zitadel auth backend. A trailing slash is ignored. |
| projectSecret | string | ZITADEL_PROJECT_SECRET env | Project secret, sent as the bearer on the handoff exchange only (server-only) |
| projectId | string | ZITADEL_PROJECT_ID, else VITE_ZITADEL_PROJECT_ID env | The project this app signs its users in to. A session of any other project on the server reads as signed out and keeps its cookie; with no project, no session counts |
| proxyPath | string | "/__nextgen" | Path prefix proxied to the auth backend |
| protectedRoutes | string[] | [] | Paths requiring a valid session. Trailing * matches sub-paths |
| ignoredRoutes | string[] | [] | Paths skipped entirely — no JWT check. Trailing * matches sub-paths |
| loginPath | string | "/login" | Where to redirect unauthenticated users |
| allowedAlgorithms | string[] | ["RS256", "ES256"] | JWT alg values to accept. Other algorithms are rejected before JWKS is fetched |
| allowedTokenTypes | string[] | ["JWT", "at+JWT"] | Accepted typ header values (case-insensitive). Set to [] to disable this check |
| clockSkewMs | number | 5000 | Clock skew tolerance in ms for exp, nbf, iat |
| jwksTimeoutMs | number | 5000 | Timeout in ms for JWKS endpoint requests |
| proxyTimeoutMs | number | 5000 | Timeout in ms for upstream proxy requests |
| audience | string \| string[] | not validated | Expected aud claim value(s). When omitted, audience is not checked |
How JWT verification works
- Bearer token from
Authorizationheader is checked first; the app's session cookie,__Host-zitadel_session_<projectId>(zitadel_session_<projectId>over plain http to a loopback host), is the fallback - Tokens with an
algnot inallowedAlgorithms(RS256,ES256by default) are rejected before any JWKS fetch - Tokens with a
typnot inallowedTokenTypesare rejected immediately - The public key is fetched from
{url}/auth/keys(JWKS) via the Web Crypto API, cached for 5 minutes perkid - The signature is verified before any claim checks
issmust be present and must equalurlexpmust be present and in the future (withclockSkewMstolerance);nbfandiatare validated when present- Opaque (non-JWT) tokens fall back to validation via
GET /sessions/me
Testing
To test an app that uses this SDK end to end, against a real local Zitadel server, use @zitadel/testing (guide).
