Skip to content

SvelteKit

This guide shows how to integrate gau with SvelteKit, using Drizzle (SQLite or PostgreSQL) and GitHub as examples.


  1. Complete the Getting Started guide.

    Complete the Drizzle guide:

    1. Set up your schema in src/lib/server/db/schema.ts
    2. Set up your database in src/lib/server/db/index.ts

  2. Create a catch-all route for auth endpoints on the server.

    src/routes/api/auth/[...gau]/+server.ts
    import { SvelteKitAuth } from '@rttnd/gau/sveltekit'
    import { auth } from '$lib/server/auth'
    export const { GET, POST, OPTIONS } = SvelteKitAuth(auth)
  3. Add the SvelteKitAuth handle to make sessions available in event.locals.

    src/hooks.server.ts
    import { SvelteKitAuth } from '@rttnd/gau/sveltekit'
    import { auth } from '$lib/server/auth'
    export const { handle } = SvelteKitAuth(auth)

    Now, in server routes, you can access event.locals.getSession() which returns { user, session, accounts, providers }.

    For full type-safety, update your src/app.d.ts:

    src/app.d.ts
    import type { GauSession } from '@rttnd/gau'
    declare global {
    namespace App {
    interface Locals {
    getSession: () => Promise<GauSession>
    }
    }
    }
    export {}
  4. To use gau on the client-side, you’ll need to wrap your application in an AuthProvider and use the useAuth hook to access session data.

    First, wrap your root layout in the AuthProvider. This makes the auth state available to all your components.

    src/routes/+layout.svelte
    <script lang="ts">
    import AuthProvider from '@rttnd/gau/client/svelte/AuthProvider.svelte'
    const { children } = $props()
    </script>
    <AuthProvider>
    {@render children()}
    </AuthProvider>

    Next, to get full TypeScript support for your provider IDs, create a typed useAuth hook. This is a great practice as you only have to type it once.

    src/lib/auth.ts
    import type { Auth } from '$lib/server/auth'
    import { useAuth as useAuthCore } from '@rttnd/gau/client/svelte'
    export const useAuth = () => useAuthCore<Auth>()

    Now you can use your custom useAuth hook in any component to access the session and authentication methods.

    src/routes/+page.svelte
    <script>
    import { useAuth } from '$lib/auth'
    const auth = useAuth()
    </script>
    {#if auth.session?.user}
    <p>Welcome, {auth.session.user.name}!</p>
    <button onclick={() => auth.signOut()}>Sign Out</button>
    {:else}
    <button onclick={() => auth.signIn('github')}>Sign in with GitHub</button>
    {/if}
    • Directorysrc
      • Directorylib
        • Directoryserver
          • auth.ts
        • auth.ts
      • Directoryroutes
        • Directoryapi
          • Directoryauth
            • Directory[…gau]
              • +server.ts
        • +layout.svelte
        • +page.svelte
      • app.d.ts
      • hooks.server.ts
    • package.json
    • svelte.config.js