Private Page(s)
Once user is authenticated, you can build private routes like a user dashboard, account, etc.
Here’s an example of a simple user dashboard showing private user data in the page:
---
import { getSession } from '@/lib/auth'
const session = getSession(Astro.request)
if (session) {
// If need to do something on the server side say fetch data for the user
// This is the right block to do it
} else {
// In case the user is not logged in
// Redirect them for example
return Astro.redirect('/')
}
---
<html>
<head> </head>
<body>
The user that's logged name is {session.user.name}
</body>
</html>
Here’s a simple example of protecting a route in SvelteKit.
Create a +page.server.ts
in/along the directory that you want to protect:
// File: src/routes/something/+page.server.ts
import { error } from '@sveltejs/kit'
import type { RequestEvent } from './$types'
import { getSession } from '@/lib/utils/auth'
export async function load(event: RequestEvent) {
const session = getSession(event.request)
if (!session) {
// In case the user is not logged in
// Send 403
throw error(403, { message: 'Unauthorized' })
}
// If need to do something on the server side say fetch data for the user
// This is the right block to do it
return session
}