Server-Side Integration
Overview
The server-side module (@authrim/sveltekit/server) provides three layers:
createAuthHandle— SvelteKit handle hook that reads session cookies and populatesevent.locals.authServerSessionManager— Low-level cookie read/write API- Load helpers —
requireAuth()andcreateAuthLoad()for route protection and data passing
createAuthHandle
The primary server hook. Add it to src/hooks.server.ts:
import { createAuthHandle } from '@authrim/sveltekit/server';
export const handle = createAuthHandle();On every request, it reads the session cookie, deserializes ServerAuthContext, and sets event.locals.auth.
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; /** Callback URL paths (default: ['/auth/callback']) */ callbackPaths?: string[];}Combining with Other Hooks
Use SvelteKit’s sequence() to compose multiple hooks:
import { sequence } from '@sveltejs/kit/hooks';import { createAuthHandle } from '@authrim/sveltekit/server';
const authHandle = createAuthHandle();
const loggingHandle = async ({ event, resolve }) => { console.log(`${event.request.method} ${event.url.pathname}`); return resolve(event);};
export const handle = sequence(authHandle, loggingHandle);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
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
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
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
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
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,});API
interface ServerSessionManager { /** Read session from cookie */ get(event: RequestEvent): Promise<ServerAuthContext | null>; /** Write session to cookie */ set(event: RequestEvent, context: ServerAuthContext): void; /** Delete session cookie */ clear(event: RequestEvent): void;}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
| Function | Signature | Purpose |
|---|---|---|
getAuthFromEvent(event) | (RequestEvent) → ServerAuthContext | null | Extract auth from event |
getServerSessionManager(event) | (RequestEvent) → ServerSessionManager | Get session manager from handle |
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
| 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 |
Next Steps
- Authentication — Client-side authentication methods
- Stores & Events — Reactive state management
- Components — AuthProvider and other components