npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@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@latest

Requirements

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:

  1. Proxies /__nextgen/* requests to the auth backend. The project secret is attached as the bearer only on the POST /sessions/exchange handoff, and never reaches the browser.
  2. Verifies the session JWT via JWKS using the Web Crypto API and writes the result to event.locals.nextgenAuth.
  3. Redirects unauthenticated requests to loginPath for 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

  1. Bearer token from Authorization header 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
  2. Tokens with an alg not in allowedAlgorithms (RS256, ES256 by default) are rejected before any JWKS fetch
  3. Tokens with a typ not in allowedTokenTypes are rejected immediately
  4. The public key is fetched from {url}/auth/keys (JWKS) via the Web Crypto API, cached for 5 minutes per kid
  5. The signature is verified before any claim checks
  6. iss must be present and must equal url
  7. exp must be present and in the future (with clockSkewMs tolerance); nbf and iat are validated when present
  8. 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).