Authentication
Complete guide to the authentication system built with Supabase, including user management, protected routes, and customization options.
Authentication
Complete guide to the authentication system built with Supabase, including user management, protected routes, and customization options.
Authentication Overview
The template uses Supabase Auth which provides:
- Email/Password authentication
- Email verification and password reset
- Session management with automatic refresh
- Server-side and client-side auth
- Protected routes with middleware
Authentication Flow
User Registration
- User fills signup form (
/auth/sign-up
) - Supabase creates account and sends verification email
- User redirected to success page (
/auth/sign-up-success
) - User clicks email link to verify account
- Account activated, user can login
User Login
- User enters credentials (
/auth/login
) - Supabase validates and creates session
- User redirected to dashboard or intended page
- Session stored in cookies for persistence
Password Reset
- User requests reset (
/auth/forgot-password
) - Supabase sends reset email
- User clicks link and sets new password (
/auth/update-password
) - User can login with new password
Authentication Pages
All auth pages are in the app/auth/
directory:
/auth/login
- Email/password login form
- "Remember me" option
- Link to signup and forgot password
- Redirects to dashboard after successful login
/auth/sign-up
- Email/password registration form
- Terms and privacy policy links
- Email verification required
- Redirects to success page
/auth/sign-up-success
- Confirmation page after registration
- Instructions to check email
- Resend verification email option
/auth/forgot-password
- Password reset request form
- Sends reset email via Supabase
- Instructions for next steps
/auth/update-password
- New password form (accessed via email link)
- Password confirmation
- Automatic login after reset
/auth/confirm
- Email verification handler
- Processes verification tokens
- Redirects to appropriate page
/auth/error
- Handles authentication errors
- User-friendly error messages
- Navigation back to login
Protected Routes
Middleware Protection
The middleware.ts
file protects routes automatically:
// Routes that require authentication
const protectedRoutes = ['/dashboard', '/billing', '/account', '/protected'];
// Routes only for unauthenticated users
const authRoutes = ['/auth/login', '/auth/sign-up'];
Protected Layout
The /protected
directory uses a special layout:
// app/protected/layout.tsx
// Ensures user is authenticated before rendering children
// Redirects to login if not authenticated
// Provides user context to child components
Manual Route Protection
For custom protection in components:
import { createClient } from '@/lib/supabase/client'
import { useEffect, useState } from 'react'
export default function ProtectedComponent() {
const [user, setUser] = useState(null)
const supabase = createClient()
useEffect(() => {
const getUser = async () => {
const { data: { user } } = await supabase.auth.getUser()
setUser(user)
}
getUser()
}, [])
if (!user) {
return <div>Please login to access this content</div>
}
return <div>Protected content for {user.email}</div>
}
User Management
Getting Current User
Client-side:
import { createClient } from '@/lib/supabase/client';
const supabase = createClient();
const {
data: { user },
} = await supabase.auth.getUser();
Server-side:
import { createClient } from '@/lib/supabase/server';
const supabase = createClient();
const {
data: { user },
} = await supabase.auth.getUser();
User Session Management
Sessions are automatically managed:
- Stored in HTTP-only cookies for security
- Auto-refresh before expiration
- Cleared on logout or expiration
- Shared across tabs in the same browser
Logout Functionality
const handleLogout = async () => {
const supabase = createClient();
await supabase.auth.signOut();
router.push('/auth/login');
};
User Profiles
Database Schema
The template includes a profiles
table:
CREATE TABLE profiles (
id UUID REFERENCES auth.users(id) PRIMARY KEY,
email TEXT,
full_name TEXT,
avatar_url TEXT,
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);
Profile Management
Users can update their profiles in /account
:
const updateProfile = async (updates) => {
const supabase = createClient();
const { data, error } = await supabase
.from('profiles')
.update(updates)
.eq('id', user.id);
};
Email Templates
Custom email templates are configured in Supabase:
Email Verification
- Sent after user registration
- Contains verification link
- Styled to match your brand
Password Reset
- Sent when user requests password reset
- Contains secure reset link
- Expires after set time
Configuration
- Go to Supabase Dashboard → Authentication → Email Templates
- Customize HTML templates
- Update links to point to your domain
- Add your branding and styling
Security Features
Row Level Security (RLS)
Database policies ensure users can only access their own data:
-- Users can only see their own profile
CREATE POLICY "Users can view own profile"
ON profiles FOR SELECT
USING (auth.uid() = id);
-- Users can only update their own profile
CREATE POLICY "Users can update own profile"
ON profiles FOR UPDATE
USING (auth.uid() = id);
Session Security
- HTTP-only cookies prevent XSS attacks
- Secure flag for HTTPS-only transmission
- SameSite protection against CSRF
- Automatic session refresh
Customization
Adding Social Providers
To add Google, GitHub, etc.:
- Configure in Supabase Dashboard → Authentication → Providers
- Add provider keys and secrets
- Update login form with social buttons
- Handle provider callbacks
Custom User Fields
Add fields to the signup process:
- Update
profiles
table schema - Modify signup form components
- Update profile creation logic
- Add validation rules
Email Customization
Customize authentication emails:
- Design HTML templates in Supabase
- Add your logo and branding
- Update redirect URLs
- Test email delivery
Common Issues
Email Not Verified
- Check spam folder
- Resend verification from success page
- Verify email settings in Supabase
Session Not Persisting
- Check cookie settings
- Verify domain configuration
- Ensure HTTPS in production
Redirect Issues
- Check middleware configuration
- Verify protected route patterns
- Update redirect URLs in Supabase
Database Permission Errors
- Check RLS policies are enabled
- Verify user permissions
- Review database policies
Next Steps
With authentication set up:
- Configure your database - Set up tables and relationships
- Set up payments - Connect Stripe for subscriptions
- Customize user experience - Update forms and flows
- Deploy securely - Configure production auth settings
Your authentication system is now ready to handle user management securely!