SvelteKit
This guide shows how to integrate gau
with SvelteKit, using Drizzle (SQLite) and GitHub as examples.
-
Follow the basic setup
Section titled “Follow the basic setup”Complete the Getting Started guide for installation, environment variables, and the auth configuration with the database setup.
-
Set up API Route
Section titled “Set up API Route”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) -
Add Server Hook
Section titled “Add Server Hook”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 }
ornull
.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 {} -
Set up the Client
Section titled “Set up the Client”To use
gau
on the client-side, you’ll need to wrap your application in anAuthProvider
and use theuseAuth
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} -
File Structure
Section titled “File Structure”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
-
Next Steps
Section titled “Next Steps”- Explore other OAuth Providers.
- See Deployment for production tips.
- Learn about how
gau
works.