Skip to content

Protected Routes

Protecting routes ensures that only authenticated users can access them.

gau supports both client-side guards for better UX and server-side checks for security.

You should use both.

Client-side guards keep the session reactive and prevent flickers when navigating within your app.

Wrap the page in the <Protected> component.

src/routes/dashboard/+page.svelte
<script lang='ts'>
import Protected from '@rttnd/gau/client/svelte/Protected.svelte'
import { useAuth } from '$lib/auth'
const auth = useAuth()
</script>
<Protected redirectTo='/'>
<h1>Dashboard</h1>
<p>Welcome, {auth.session?.user?.name}!</p>
</Protected>

<Protected> props:

  • redirectTo (optional): where to send unauthenticated visitors. Defaults to '/'.
  • fallback (optional): a Svelte snippet rendered while loading or when blocked.
<Protected redirectTo='/login' fallback={() => <div>Loading...</div>}>
<!-- page content -->
</Protected>

Check session on the server to avoid rendering protected pages at all when the user is not signed in.

Example:

src/routes/dashboard/+page.server.ts
import type { PageServerLoad } from './$types'
import { redirect } from '@sveltejs/kit'
export const load: PageServerLoad = async ({ locals }) => {
const session = await locals.getSession()
if (!session?.user)
throw redirect(302, '/login')
return { session }
}