Route Protection
One of the key features of Svelte Guardian is the ability to protect routes based on authentication status and user roles. This guide will show you how to implement route protection in your SvelteKit application.
Basic Concepts
Route protection in Svelte Guardian works at two levels:
- Server-Side Protection: Prevents unauthorized server rendering and API access
- Client-Side Protection: Redirects unauthenticated users in the browser
Both levels work together to ensure a seamless and secure user experience.
Configuration
Route protection is configured in the security.routeProtection
section of your Svelte Guardian configuration:
Protected Routes Options
When configuring protected routes, you have several options:
Authentication Only
To protect a route for any authenticated user:
Role-Based Protection
To restrict access to users with specific roles:
You can specify multiple roles:
Custom Authorization Logic
For more complex authorization requirements, you can use a custom function:
Public Routes
Public routes are accessible to all users. However, you can configure them to redirect authenticated users elsewhere:
If no redirection is needed, use an empty object:
API Route Protection
API routes can also be protected:
When an unauthenticated request is made to a protected API route, Svelte Guardian returns:
- 401 Unauthorized for unauthenticated requests
- 403 Forbidden for authenticated users without proper permissions
Route Protection in SvelteKit
Using server-side load functions
You can implement additional protection in your page’s load function:
Creating a protected layout
For sections of your site that should all be protected, create a protected layout:
Then place your protected routes under this layout:
Client-Side Protection with Guards
Create client-side guards for additional protection in SvelteKit:
Use these guards in your pages:
Error Pages
Create custom error pages for unauthorized access:
Access Denied
You do not have permission to access this page.
Go to Homepage {#if !$page.data.session?.user} or Sign In {/if}
Best Practices
- Defense in Depth: Use both server-side and client-side protection
- Least Privilege: Give users only the access they need
- Clear Feedback: Provide meaningful error messages when access is denied
- Secure API Routes: Always protect API routes that access sensitive data
- Test All Paths: Verify that all protected routes are properly secured
Next Steps
After implementing route protection, you might want to explore: