Session-based Auth in Svelte

From the SvelteKit cheat sheet · Authentication · verified Nov 2026

Session-based Auth

Cookie-based authentication

javascript
// Login action (+page.server.js)
import { fail, redirect } from '@sveltejs/kit';
import { verifyUser, createSession } from '#lib/server/auth.js';

export const actions = {
  login: async ({ request, cookies }) => {
    const data = await request.formData();

    // Verify credentials
    const user = await verifyUser(data.get('email'), data.get('password'));
    if (!user) return fail(401, { incorrect: true });

    // httpOnly, secure and path '/' are the defaults
    const session = await createSession(user.id);
    cookies.set('session', session.id, {
      maxAge: 60 * 60 * 24 * 7
    });

    redirect(303, '/dashboard');
  }
};
🍪 Secure HTTP-only cookies for sessions
🔒 Server-side session validation
⚡ Automatic session extension
🛡️ Protected routes in hooks

Continue with SvelteKit

Save the full cheat sheet or work through every related task.

More Svelte tasks

Back to the full SvelteKit cheat sheet