mirror of
https://github.com/LukeHagar/Sveltey.git
synced 2025-12-06 04:21:38 +00:00
5.6 KiB
5.6 KiB
SvelteKit Supabase Authentication Setup
This project uses Supabase for authentication with full server-side rendering (SSR) support through SvelteKit hooks.
Features
- ✅ Email/Password authentication
- ✅ GitHub OAuth integration
- ✅ Server-side authentication with
hooks.server.ts - ✅ Protected routes with automatic redirects
- ✅ Session management across client and server
- ✅ TypeScript support with proper types
Setup Instructions
1. Environment Variables
Create a .env.local file in your project root:
PUBLIC_SUPABASE_URL=your_supabase_project_url
PUBLIC_SUPABASE_ANON_KEY=your_supabase_anon_key
Get these values from your Supabase project dashboard under Settings > API.
2. Supabase Configuration
Enable GitHub OAuth Provider
- Go to your Supabase project dashboard
- Navigate to Authentication > Providers
- Enable the GitHub provider
- Add your GitHub OAuth credentials:
- Client ID: From your GitHub OAuth app
- Client Secret: From your GitHub OAuth app
GitHub OAuth App Setup
- Go to GitHub Settings > Developer settings > OAuth Apps
- Click "New OAuth App"
- Fill in the details:
- Application name: Your app name
- Homepage URL:
http://localhost:5173(for development) - Authorization callback URL:
https://your-project-ref.supabase.co/auth/v1/callback
- Note the Client ID and Client Secret for Supabase configuration
3. Supabase Authentication Settings
In your Supabase project settings:
- Go to Authentication > Settings
- Add your site URLs:
- Site URL:
http://localhost:5173(development) /https://yourdomain.com(production) - Redirect URLs: Add both your local and production URLs
- Site URL:
Architecture Overview
Server-Side Authentication (hooks.server.ts)
The authentication is handled through SvelteKit hooks:
// src/hooks.server.ts
export const handle: Handle = sequence(supabase, authGuard);
Features:
supabasehook: Creates server-side Supabase client with cookie managementauthGuardhook: Protects routes and handles redirects- Session validation: Validates JWTs on every request
- Cookie management: Automatic token refresh and cookie handling
Protected Routes
Routes are automatically protected based on path patterns:
/dashboard/*: Requires authentication, redirects to/auth/loginif not authenticated/auth/*: Redirects authenticated users to/dashboard
Client-Side Integration (+layout.svelte)
The root layout handles client-side authentication state:
// Syncs server-side session with client-side
$effect(() => {
session = data.session;
});
// Handles auth state changes
supabase.auth.onAuthStateChange((event, newSession) => {
if (newSession?.expires_at !== session?.expires_at) {
invalidateAll();
}
});
File Structure
src/
├── hooks.server.ts # Server-side authentication hooks
├── app.d.ts # TypeScript definitions for Supabase
├── lib/
│ ├── index.ts # Exports (toaster)
│ └── supabaseClient.ts # Browser Supabase client
├── routes/
│ ├── +layout.svelte # Root layout with auth state
│ ├── +layout.server.ts # Server layout with session data
│ ├── auth/
│ │ ├── login/+page.svelte # Login page with GitHub OAuth
│ │ ├── signup/+page.svelte # Signup page with GitHub OAuth
│ │ └── logout/+page.server.ts # Logout action
│ └── dashboard/
│ ├── +layout.server.ts # Dashboard layout (protected)
│ └── +page.svelte # Dashboard page
Usage Examples
Login Page Features
- Email/password authentication
- GitHub OAuth login
- Form validation and error handling
- Loading states
- Automatic redirect after login
Signup Page Features
- Email/password registration
- GitHub OAuth signup
- Email confirmation handling
- Error handling with toast notifications
Dashboard Protection
The dashboard is automatically protected and will:
- Redirect unauthenticated users to login
- Display user information for authenticated users
- Handle session expiration gracefully
TypeScript Support
Full TypeScript support with proper types:
// app.d.ts
interface Locals {
supabase: SupabaseClient;
safeGetSession(): Promise<{ session: Session | null; user: User | null }>;
session: Session | null;
user: User | null;
}
Development
- Start your development server:
npm run dev
- Test authentication:
- Visit
/auth/signupto create an account - Try GitHub OAuth login
- Visit
/dashboardto see protected content - Test logout functionality
- Visit
Security Features
- JWT validation: Server-side validation of authentication tokens
- Automatic refresh: Tokens are refreshed automatically
- Secure cookies: HTTP-only cookies for session management
- Route protection: Server-side route guards
- CSRF protection: Built into Supabase auth flow
Troubleshooting
Common Issues
- "Cannot redirect during render": Usually caused by trying to redirect in a
loadfunction without throwing the redirect - OAuth callback errors: Check your GitHub OAuth app callback URL matches Supabase settings
- Session not persisting: Ensure cookies are configured correctly in
hooks.server.ts
Debug Tips
- Check browser Network tab for auth requests
- Verify Supabase project settings match your configuration
- Test OAuth flow in incognito mode to avoid cached sessions