Skip to content

Middleware

gau provides composable middleware helpers for framework integrations. Use what you need.

The base middleware attaches two methods to your request context:

  • getSession() - Returns client-safe session data.
  • getServerSession() - Returns the full session including OAuth tokens.

SvelteKitAuth returns a handle hook that sets up locals.getSession():

hooks.server.ts
export { handle } from './routes/api/auth/[...gau]/+server'

Now you can use locals.getSession() in load functions, endpoints, and remote functions.

Use getSession() for data that will be serialized to the browser:

src/api/session.ts
const session = await locals.getSession()
return { session }

Use getServerSession() only on the server, like when you need OAuth tokens:

src/api/github.ts
const { accounts } = await locals.getServerSession()
const githubAccount = accounts?.find(a => a.provider === 'github')
if (githubAccount?.accessToken) {
const res = await fetch('https://api.github.com/user/repos', {
headers: { Authorization: `Bearer ${githubAccount.accessToken}` }
})
}

SvelteKit is lazy by default.

The Refresh middleware adds automatic session refresh:

  • Reads the token from Cookie first, then Authorization: Bearer
  • Refreshes if past the threshold, or every request
  • Responds appropriately:
    • Cookie: Set-Cookie header
    • Bearer: X-Refreshed-Token header (for Tauri/mobile)
hooks.server.ts
import { sequence } from '@sveltejs/kit/hooks'
import { handle as authHandle } from './routes/api/auth/[...gau]/+server'
import { createRefreshHandle } from '@rttnd/gau/sveltekit'
import { auth } from '$lib/server/auth'
export const handle = sequence(
authHandle,
createRefreshHandle(auth, { threshold: 0.5 }),
)

Options:

  • threshold - Only refresh if past this fraction of TTL (0-1). Example: 0.5 = refresh after 50% of session lifetime.
  • ttl - Override the TTL for the new token.

If your app uses bearer tokens instead of cookies, the server middleware sends refreshed tokens via the X-Refreshed-Token header. Use the fetch method from useAuth() to handle this automatically.

See the Integrations page for details.