@svelte-dev/auth

A simple and easy-to-use Svelte identity management library

Logo

Features

  • Full Server-Side Authentication
  • Complete TypeScript Support
  • Strategy-based Authentication
  • Easily handle success and failure
  • Implement custom strategies
  • Supports persistent sessions

Overview

Svelte Auth is a complete open-source authentication solution for Svelte applications.

Heavily inspired by Passport.js and Remix-Auth, but completely rewrote it from scratch to work on top of the Web Fetch API. Svelte Auth can be dropped in to any Svelte-based application with minimal setup.

As with Passport.js, it uses the strategy pattern to support the different authentication flows. Each strategy is published individually as a separate npm package.

Demo

Github Login

Installation

To use it, install it from npm (yarn or bun):

npm install @svelte-dev/auth @svelte-dev/session

Usage

Here’s an simple Example:

// hooks.server.ts
import { env } from '$env/dynamic/private';
import { sequence } from '@sveltejs/kit/hooks';
import { handleAuth } from '@svelte-dev/auth';
import { OAuth2Strategy } from '@svelte-dev/auth-oauth2';
 
const oauthStrategy = new OAuth2Strategy(
  {
    clientID: env.SSO_ID,
    clientSecret: env.SSO_SECRET,
    callbackURL: env.SSO_CALLBACK_URL || 'http://localhost:8788/auth/oauth2/callback'
  },
  async ({ profile }) => {
    // Get the user data from your DB or API using the tokens and profile
    return profile;
  }
);
 
export const handle = handleAuth({
  // Auth Options
  autoRouting: true,
  strategies: [oauthStrategy],
  sessionKey: 'user',
  sessionErrorKey: 'auth:error',
  sessionStrategyKey: 'strategy',
  successRedirect: '/',
  failureRedirect: '/',
  // Session Storage Options
  adapter: {
    name: 'cookie',
    options: {
      chunk: true
    }
  },
  session: {
    secrets: ['s3cr3t']
  },
  cookie: {
    secure: !!env.SSO_CALLBACK_URL,
    sameSite: 'lax',
    path: '/',
    httpOnly: !!env.SSO_CALLBACK_URL
  }
});

That’s it.

Advanced Usage

Custom Handle

If you did not set authRouting. You need to add a login handler src/routes/auth/[provider]/+server.ts:

import { redirect, type RequestEvent } from '@sveltejs/kit';
 
export const GET = async (event: RequestEvent) => {
  const { request } = event;
  const provider = event.params.provider ?? 'github';
  return await event.locals.auth.authenticate(event, provider, {
    successRedirect: '/dashboard',
    failureRedirect: '/error'
  });
};

Then, add a callback handler src/routes/auth/[provider]/callback/+server.ts.ts:

// same as before...
import type { RequestEvent } from '@sveltejs/kit';
 
export const GET = async (event: RequestEvent) => {
  const provider = event.params.provider ?? 'github';
 
  return await event.locals.auth.authenticate(event, provider, {
    successRedirect: '/dashboard',
    failureRedirect: '/error'
  });
};

Typescript

Modify app.d.ts, here is an example:

// See https://kit.svelte.dev/docs/types#app
// for information about these interfaces
declare global {
  namespace App {
    // interface Error {}
    interface Locals {
      auth: Auth;
      session: SessionStorage<{ user: any }>;
      user:
        | {
            invalid?: boolean;
            [key: string]: unknown;
          }
        | unknown;
    }
    // interface PageData {}
    interface Platform {
      env: {
        SSO_ID: string;
        SSO_SECRET: string;
      };
      context: {
        waitUntil(promise: Promise<unknown>): void;
      };
      caches: CacheStorage & { default: Cache };
    }
  }
}
 
export {};

Strategies

PackageMetaChangelog
@svelte-dev/auth-oauth2npm npm npmChangelog
@svelte-dev/auth-githubnpm npm npmChangelog
@svelte-dev/auth-alipaynpm npm npmChangelog
@svelte-dev/auth-afdiannpm npm npmChangelog
@svelte-dev/auth-ssonpm npm npmChangelog

Welcome to share your strategies here.

API Spec

Owner: Willin Wang

Donation ways:

License

Apache-2.0