Server-Side Integration
Overview
Section titled “Overview”The server-side module (@authrim/sveltekit/server) provides four layers:
createAuthHandle— SvelteKit handle hook that reads session cookies and populatesevent.locals.authcreateDirectAuthSessionHandlers— Same-origin handlers that redeem Direct Auth artifacts and set HttpOnly session cookiesServerSessionManager— Low-level cookie read/write API- Load helpers —
requireAuth()andcreateAuthLoad()for route protection and data passing
createAuthHandle
Section titled “createAuthHandle”The primary server hook. Add it to src/hooks.server.ts:
import { createAuthHandle } from '@authrim/sveltekit/server';import { AUTHRIM_SESSION_SECRET } from '$env/static/private';
export const handle = createAuthHandle({ sessionSecret: AUTHRIM_SESSION_SECRET,});On every request, it reads the session cookie, deserializes ServerAuthContext, and sets event.locals.auth.
sessionSecret is required to read encrypted session cookies. Use at least 32 bytes of high-entropy server-only secret material.
Options
Section titled “Options”interface AuthHandleOptions { /** Cookie name (default: 'authrim_session') */ cookieName?: string; /** SameSite attribute (default: 'lax') */ sameSite?: 'strict' | 'lax' | 'none'; /** Secure flag (default: true in production) */ secure?: boolean; /** Cookie path (default: '/') */ path?: string; /** Max age in seconds (default: 604800 = 7 days) */ maxAge?: number; /** HttpOnly flag (default: true) */ httpOnly?: boolean; /** Secret for encrypted/signed session cookies */ sessionSecret?: string | Uint8Array | CryptoKey; /** Callback URL paths (default: ['/auth/callback']) */ callbackPaths?: string[];}Direct Auth Session Handlers
Section titled “Direct Auth Session Handlers”For the default authMode: 'server' client profile, create same-origin endpoints that exchange Direct Auth artifacts for an HttpOnly app session:
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,});| Handler | Method | Default Route | Purpose |
|---|---|---|---|
exchange | POST | /authrim/session/exchange | Redeem a Direct Auth artifact and set the session cookie |
session | GET | /authrim/session | Return the current cookie-backed session |
logout | POST | /authrim/session/logout | Clear the session cookie |
Combining with Other Hooks
Section titled “Combining with Other Hooks”Use SvelteKit’s sequence() to compose multiple hooks:
import { sequence } from '@sveltejs/kit/hooks';import { createAuthHandle } from '@authrim/sveltekit/server';import { AUTHRIM_SESSION_SECRET } from '$env/static/private';
const authHandle = createAuthHandle({ sessionSecret: AUTHRIM_SESSION_SECRET,});
const loggingHandle = async ({ event, resolve }) => { console.log(`${event.request.method} ${event.url.pathname}`); return resolve(event);};
export const handle = sequence(authHandle, loggingHandle);ServerAuthContext
Section titled “ServerAuthContext”The data structure set on event.locals.auth:
interface ServerAuthContext { session: Session; user: User;}Session and User are the same types from @authrim/core.
Load Helpers
Section titled “Load Helpers”requireAuth — Protected Routes
Section titled “requireAuth — Protected Routes”Redirects unauthenticated users to a login page:
import { requireAuth } from '@authrim/sveltekit/server';
export const load = requireAuth();The user is redirected to /login?redirectTo=/dashboard if not authenticated.
Options
Section titled “Options”interface AuthLoadOptions { /** Login page URL (default: '/login') */ loginUrl?: string; /** Query parameter for return path (default: 'redirectTo') */ redirectParam?: string;}// Custom login URLexport const load = requireAuth({ loginUrl: '/auth/signin', redirectParam: 'returnTo',});Combining with Custom Data
Section titled “Combining with Custom Data”import { requireAuth } from '@authrim/sveltekit/server';
export const load = async (event) => { // requireAuth() first — redirects if not authenticated const { auth } = await requireAuth()(event);
// Additional data loading const dashboardData = await fetchDashboard(auth.user.id);
return { auth, dashboard: dashboardData, };};createAuthLoad — Optional Auth Data
Section titled “createAuthLoad — Optional Auth Data”Passes auth data without requiring authentication:
import { createAuthLoad } from '@authrim/sveltekit/server';
export const load = createAuthLoad();// Returns { auth: ServerAuthContext | null }Use this in the root layout to make auth data available to all pages.
ServerSessionManager
Section titled “ServerSessionManager”For direct cookie operations (advanced use):
import { createServerSessionManager, type ServerSessionManager,} from '@authrim/sveltekit/server';
const sessionManager = createServerSessionManager({ cookieName: 'authrim_session', sameSite: 'lax', secure: true, httpOnly: true, maxAge: 604800, sessionSecret: process.env.AUTHRIM_SESSION_SECRET,});interface ServerSessionManager { /** Read session from cookie */ get(event: RequestEvent): Promise<ServerAuthContext | null>; /** Write session to cookie */ set(event: RequestEvent, context: ServerAuthContext): Promise<void>; /** Delete session cookie */ clear(event: RequestEvent): void;}Usage in API Routes
Section titled “Usage in API Routes”import { getAuthFromEvent,} from '@authrim/sveltekit/server';import { json, error } from '@sveltejs/kit';
export async function GET({ locals }) { const auth = locals.auth; if (!auth) throw error(401, 'Not authenticated');
return json({ user: auth.user });}Utility Functions
Section titled “Utility Functions”| Function | Signature | Purpose |
|---|---|---|
getAuthFromEvent(event) | (RequestEvent) → ServerAuthContext | null | Extract auth from event |
getServerSessionManager(options?) | (ServerSessionManagerOptions?) → ServerSessionManager | Create a session manager with the provided cookie options |
isAuthenticated(locals) | ({ auth? }) → boolean | Check if authenticated |
getUser(locals) | ({ auth? }) → User | null | Get user from locals |
getSession(locals) | ({ auth? }) → Session | null | Get session from locals |
import { isAuthenticated, getUser } from '@authrim/sveltekit/server';
export const load = async ({ locals }) => { if (isAuthenticated(locals)) { const user = getUser(locals); return { user }; } return { user: null };};Cookie Configuration Reference
Section titled “Cookie Configuration Reference”| Option | Default | Description |
|---|---|---|
cookieName | 'authrim_session' | Cookie name |
sameSite | 'lax' | SameSite attribute |
secure | true (production) | HTTPS only |
path | '/' | Cookie path |
maxAge | 604800 (7 days) | TTL in seconds |
httpOnly | true | Not accessible via JavaScript |
sessionSecret | — | Required to encrypt and authenticate session cookies |
Next Steps
Section titled “Next Steps”- Authentication — Client-side authentication methods
- Stores & Events — Reactive state management
- Components — AuthProvider and other components