Installation & Setup
Install
Section titled “Install”npm install @authrim/sveltekitPeer dependencies: svelte ^4.0.0 || ^5.0.0, @sveltejs/kit ^2.0.0.
Step 1: Auth Configuration
Section titled “Step 1: Auth Configuration”Create src/lib/auth.ts — a singleton factory for the Authrim client:
import { createAuthrim, type AuthrimClient } from '@authrim/sveltekit';
let auth: AuthrimClient | null = null;
export async function getAuth(): Promise<AuthrimClient> { if (auth) return auth;
auth = await createAuthrim({ issuer: import.meta.env.PUBLIC_AUTHRIM_ISSUER, clientId: import.meta.env.PUBLIC_AUTHRIM_CLIENT_ID, authMode: 'server', });
return auth;}
export function clearAuth(): void { if (auth) { auth.destroy(); auth = null; }}Step 2: Server Hook
Section titled “Step 2: Server Hook”Create src/hooks.server.ts — the server-side handle hook:
import { createAuthHandle } from '@authrim/sveltekit/server';import { AUTHRIM_SESSION_SECRET } from '$env/static/private';
export const handle = createAuthHandle({ sessionSecret: AUTHRIM_SESSION_SECRET,});This reads the session cookie on every request and populates event.locals.auth.
AUTHRIM_SESSION_SECRET must be at least 32 bytes of high-entropy server-only secret material.
Step 3: TypeScript Types
Section titled “Step 3: TypeScript Types”Add to src/app.d.ts:
import type { ServerAuthContext } from '@authrim/sveltekit/server';
declare global { namespace App { interface Locals { auth?: ServerAuthContext; } interface PageData { auth: ServerAuthContext | null; } }}
export {};Step 4: Root Layout
Section titled “Step 4: Root Layout”Server layout — pass auth context from SSR:
import { createAuthLoad } from '@authrim/sveltekit/server';
export const load = createAuthLoad();Client layout — initialize AuthProvider with SSR data:
<script lang="ts"> import { onMount } from 'svelte'; import { AuthProvider } from '@authrim/sveltekit/components'; import type { AuthrimClient } from '@authrim/sveltekit';
let { data, children } = $props();
let auth: AuthrimClient | null = $state(null);
onMount(async () => { const { getAuth } = await import('$lib/auth'); auth = await getAuth(); });</script>
{#if auth} <AuthProvider {auth} initialSession={data.auth?.session ?? null} initialUser={data.auth?.user ?? null} > {@render children()} </AuthProvider>{:else} <p>Loading...</p>{/if}Step 5: Server-Mediated Session Endpoints
Section titled “Step 5: Server-Mediated Session Endpoints”Create the same-origin endpoints used by authMode: 'server'. They redeem Direct Auth artifacts on the SvelteKit server, set an HttpOnly session cookie, read the current session, and clear it on logout.
import { createDirectAuthSessionHandlers } from '@authrim/sveltekit/server';import { PUBLIC_AUTHRIM_ISSUER, PUBLIC_AUTHRIM_CLIENT_ID } from '$env/static/public';import { AUTHRIM_SESSION_SECRET } from '$env/static/private';
export const authrimHandlers = createDirectAuthSessionHandlers({ issuer: PUBLIC_AUTHRIM_ISSUER, clientId: PUBLIC_AUTHRIM_CLIENT_ID, sessionSecret: AUTHRIM_SESSION_SECRET,});import { authrimHandlers } from '$lib/server/authrim-handlers';
export const POST = authrimHandlers.exchange;import { authrimHandlers } from '$lib/server/authrim-handlers';
export const GET = authrimHandlers.session;import { authrimHandlers } from '$lib/server/authrim-handlers';
export const POST = authrimHandlers.logout;Step 6: First Page
Section titled “Step 6: First Page”Create a login page:
<script lang="ts"> import { getAuthContext } from '@authrim/sveltekit'; import { goto } from '$app/navigation';
const auth = getAuthContext(); const { isAuthenticated } = auth.stores;
let loading = $state(false); let error = $state('');
async function handlePasskeyLogin() { loading = true; error = '';
const { data, error: err } = await auth.passkey.login();
if (err) { error = err.message; loading = false; return; }
goto('/'); }</script>
{#if $isAuthenticated} <p>Already signed in. <a href="/">Go home</a></p>{:else} <button onclick={handlePasskeyLogin} disabled={loading}> {loading ? 'Signing in...' : 'Sign in with Passkey'} </button>
{#if error} <p>{error}</p> {/if}{/if}Environment Variables
Section titled “Environment Variables”| Variable | Description |
|---|---|
PUBLIC_AUTHRIM_ISSUER | Authrim server URL (e.g., https://auth.example.com) |
PUBLIC_AUTHRIM_CLIENT_ID | OAuth client ID from the Admin panel |
AUTHRIM_SESSION_SECRET | Server-only secret used to encrypt and authenticate the session cookie |
Add these to .env:
PUBLIC_AUTHRIM_ISSUER=https://auth.example.comPUBLIC_AUTHRIM_CLIENT_ID=my-appAUTHRIM_SESSION_SECRET=replace-with-at-least-32-bytes-of-random-secretProject Structure
Section titled “Project Structure”src/├── app.d.ts # Type declarations├── hooks.server.ts # Server hook (createAuthHandle)├── lib/│ ├── auth.ts # Auth client singleton│ └── server/│ └── authrim-handlers.ts└── routes/ ├── +layout.server.ts # SSR auth data ├── +layout.svelte # AuthProvider wrapper ├── +page.svelte # Home page ├── login/ │ └── +page.svelte # Login page ├── signup/ │ └── +page.svelte # Signup page ├── callback/ │ └── +page.svelte # Social login callback ├── authrim/ │ └── session/ │ ├── +server.ts │ ├── exchange/ │ │ └── +server.ts │ └── logout/ │ └── +server.ts └── account/ └── +page.svelte # Account settingsNext Steps
Section titled “Next Steps”- Server-Side Integration — Deep dive into server hooks
- Authentication — All authentication methods
- Components — Pre-built Svelte components