Skip to content

SvelteKit

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


  1. Complete the Getting Started guide for installation, environment variables, and the auth configuration with the database setup.

  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 } = 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 } or null.

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

    src/app.d.ts
    import type { Session, User } from '@rttnd/gau'
    declare global {
    namespace App {
    interface Locals {
    getSession: () => Promise<{ user: User, session: Session } | null>
    }
    }
    }
    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. See the Client-side Usage guide for more details.

    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 { clientEnv } from '$lib/env/client'
    import AuthProvider from '@rttnd/gau/client/svelte/AuthProvider.svelte'
    const { children } = $props()
    </script>
    <AuthProvider baseUrl={clientEnv.PUBLIC_API_URL}>
    {@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 { useAuth as useGauAuth } from '@rttnd/gau/client/svelte'
    import type { Auth as ServerAuth } from '$lib/server/auth'
    export const useAuth = () => useGauAuth<ServerAuth>()

    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}
    • Directoryroutes
      • Directoryapi
        • Directoryauth
          • Directory[…gau]
            • +server.ts
      • +layout.svelte
      • +page.svelte
    • hooks.server.ts
    • Directorylib
      • Directoryserver
        • auth.ts
      • auth.ts
    • app.d.ts
    • package.json
    • svelte.config.js