Skip to content

Server-Side Integration

Overview

The server-side module (@authrim/sveltekit/server) provides three layers:

  1. createAuthHandle — SvelteKit handle hook that reads session cookies and populates event.locals.auth
  2. ServerSessionManager — Low-level cookie read/write API
  3. Load helpersrequireAuth() and createAuthLoad() 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:

src/routes/dashboard/+page.server.ts
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 URL
export const load = requireAuth({
loginUrl: '/auth/signin',
redirectParam: 'returnTo',
});

Combining with Custom Data

src/routes/dashboard/+page.server.ts
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:

src/routes/+layout.server.ts
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

src/routes/api/profile/+server.ts
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

FunctionSignaturePurpose
getAuthFromEvent(event)(RequestEvent) → ServerAuthContext | nullExtract auth from event
getServerSessionManager(event)(RequestEvent) → ServerSessionManagerGet session manager from handle
isAuthenticated(locals)({ auth? }) → booleanCheck if authenticated
getUser(locals)({ auth? }) → User | nullGet user from locals
getSession(locals)({ auth? }) → Session | nullGet 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 };
};
OptionDefaultDescription
cookieName'authrim_session'Cookie name
sameSite'lax'SameSite attribute
securetrue (production)HTTPS only
path'/'Cookie path
maxAge604800 (7 days)TTL in seconds
httpOnlytrueNot accessible via JavaScript

Next Steps