Updated 2 October 2026
Use Own Auth from SvelteKit server routes
Use Own Auth from SvelteKit server routes
Use Own Auth inside SvelteKit server routes to implement sveltekit postgres authentication by keeping auth logic on the server, using server only environment values for secrets, and issuing HttpOnly session cookies from server handlers. The core steps are: initialize a single Own Auth instance in a server only module, sign users in with auth.signInEmailPassword or other Own Auth methods, and set a secure Set-Cookie header from your route using SvelteKit cookies.
Why server routes and server only environment variables matter
SvelteKit separates server modules from client code so that private environment values remain in server only code. Put keys, DATABASE_URL, and any Own Auth configuration in a server only module so they cannot leak to the browser. See the SvelteKit server only environment documentation for details about keeping private values inside server modules.
In practice, that means export your Own Auth instance from a file imported only by server routes and hooks. That keeps the package, database connection settings, and any Cloud API keys out of client bundles.
SvelteKit keeps private environment values inside server modules such as server routes and server hooks. (SvelteKit server only environment documentation)
Cookie handling and session cookies
When your route writes a cookie, SvelteKit adds a Set-Cookie response header and applies sensible defaults for production. For authentication, choose HttpOnly and Secure by default, set an appropriate SameSite value, and set a clear Path for your cookie. Refer to SvelteKit cookie documentation for how cookie writes add Set-Cookie headers and to MDN for cookie attributes and browser semantics.
Keeping session cookies HttpOnly prevents JavaScript access in the client and reduces token theft from XSS. Secure should be true in production so the cookie is only sent over HTTPS. SameSite can reduce cross site request exposure according to your cross origin needs.
SvelteKit cookie writes add a Set-Cookie response header and default HttpOnly and Secure protections for production use. (SvelteKit cookie documentation)
MDN documents cookie scope, expiration, Secure, HttpOnly, and SameSite behavior for browser sessions. (MDN HTTP cookies guide)
Server module: create a singleton Own Auth instance
Create a small server only module that initializes Own Auth once and exports the instance for your routes. Keep the configuration values in server only environment variables. Do not import this module from client code.
import { createOwnAuth } from 'own-auth';
// src/lib/auth.server.ts (server only module)
// Keep this module importable only by server routes and hooks
export const auth = createOwnAuth({
// configure storage with your DATABASE_URL and other options
// load secrets from server-only environment values
});
Sign in route example
This example shows a POST server route that accepts email and password, calls auth.signInEmailPassword, handles an mfa_required status, and sets a secure session cookie when signin succeeds. Narrow the returned status before reading session fields and never serialize internal Session or User records directly to clients. Only return safe client fields.
import { auth } from '$lib/auth.server';
import { defaultSessionCookieName } from 'own-auth';
// src/routes/api/auth/signin/+server.ts
export const POST = async ({ request, cookies }) => {
const body = await request.json();
const { email, password } = body;
const result = await auth.signInEmailPassword({ email, password });
// If first factor succeeded but MFA is required, return the challenge
if (result.status === 'mfa_required') {
return new Response(JSON.stringify({
status: 'mfa_required',
challenge: {
methods: result.methods,
expiresAt: result.expiresAt,
challengeToken: result.challengeToken
}
}), { status: 200 });
}
// Only read sessionToken and safe user fields after success
if (result.status !== 'success') {
return new Response(JSON.stringify({ error: 'invalid_credentials' }), { status: 401 });
}
// Set a secure, HttpOnly cookie with the session token
cookies.set(defaultSessionCookieName, result.sessionToken, {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
path: '/',
sameSite: 'lax'
});
// Return only safe user fields
return new Response(JSON.stringify({ user: { id: result.user.id, email: result.user.email } }), { status: 200 });
};
This route demonstrates three important points: narrow the method status before inspecting session or user fields, set the cookie from the server route so the browser receives a Set-Cookie header, and avoid sending internal records to the client.
Protecting server routes and reading sessions
To protect a SvelteKit server route, read the session token from the cookie and check it with Own Auth. You can use auth.getCurrentSession or auth.requireCurrentSession depending on how you structure your handlers. If you call auth.getCurrentSession, pass the session token you read from the cookie and validate the returned session. Only expose safe user fields to the client.
- Read the cookie in your server route with SvelteKit cookies.get.
- Call Own Auth to verify the token and retrieve the session.
- Abort with 401 if the session is missing or expired.
Because Own Auth stores sessions in your application database, your session checks are authoritative and fully controlled by your backend. That aligns naturally with sveltekit postgres authentication where Postgres is the application source of truth.
Operational notes and security tradeoffs
Keep all Own Auth initialization and Cloud API keys in server only modules. Use short cookie lifetimes and idle expiries appropriate for your threat model. For multi device support and revocation, rely on Own Auth sessions and revoke with auth.revokeSession or auth.revokeAllSessions from server side administrative handlers.
Next steps
Follow these steps next: install Own Auth and configure your DATABASE_URL, move initialization into a server only module, and convert client signins to POSTs to server routes that call Own Auth. Use SvelteKit hooks and endpoints to centralize session reading when appropriate.
FAQ
Where should I put Own Auth configuration and DATABASE_URL?
Keep secrets in server only modules and import the Own Auth instance from those modules into server routes or hooks. SvelteKit documents that private environment values belong in server modules.
How should I set the session cookie?
Set cookies from server routes so the response includes a Set-Cookie header. Use HttpOnly and Secure in production. SvelteKit cookie writes add Set-Cookie headers and default protections.
How do I handle MFA and status returns from sign in methods?
Check the method result status from auth.signInEmailPassword before accessing session or user fields. If the result has status mfa_required, return the challenge instead of reading session properties.