Supabase Authentication
Supabase provides comprehensive authentication with database integration, row-level security, and multiple provider support. This module is already integrated in the template.
Overview
Supabase Auth offers email authentication, social logins, and seamless database integration with automatic user profile management.
Key Features:
- Email/password authentication
- Social login providers (Google, GitHub)
- Row Level Security integration
- User profile management
- Real-time authentication state
- Database triggers for user creation
Getting Started
1. Set Up Supabase Project
- Go to supabase.com and create an account
- Create a new project and wait for setup completion
- Go to Settings → API to get your credentials:
- Project URL
- Anon/Public Key
- Service Role Key (for server operations)
2. Add Environment Variables
Add these to your .env.local file:
NEXT_PUBLIC_SUPABASE_URL=https://your-project-ref.supabase.co
NEXT_PUBLIC_SUPABASE_ANON_KEY=your-anon-key-here
SUPABASE_SERVICE_ROLE_KEY=your-service-role-key-here3. How It Works in the Template
The template includes pre-configured authentication:
- Auth Context:
context/AuthContext.tsxmanages authentication state - Client Configuration:
lib/supabase.tsfor client-side operations - Server Configuration:
lib/supabase-server.tsfor server-side operations - Middleware:
middleware.tsprotects routes and handles auth callbacks - Database Integration: Automatic profile creation via database triggers
4. Template Structure
app/
├── auth/callback/ # OAuth callback handler
├── sign-in/ # Sign-in page with Supabase forms
├── sign-up/ # Sign-up page with Supabase forms
├── dashboard/ # Protected dashboard page
context/
├── AuthContext.tsx # Authentication state management
lib/
├── supabase.ts # Client-side Supabase config
├── supabase-server.ts # Server-side Supabase config
├── supabase-service.ts # Service role client
supabase/
├── migrations/ # Database schema migrations
middleware.ts # Auth middleware and route protectionDatabase Integration
Automatic Profile Creation
The template automatically creates user profiles:
- Database Trigger: Creates profile record when user signs up
- Row Level Security: Protects user data with RLS policies
- Profile Table: Stores additional user information
- Type Safety: Generated TypeScript types for database operations
User Profile Schema
-- profiles table (already set up in template)
CREATE TABLE public.profiles (
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
user_id UUID REFERENCES auth.users(id) ON DELETE CASCADE UNIQUE,
name TEXT,
created_at TIMESTAMP WITH TIME ZONE DEFAULT now()
);Row Level Security
The template includes secure data access:
-- Users can only access their own data
CREATE POLICY "Users can read own profile"
ON public.profiles FOR SELECT
USING (auth.uid() = user_id);Authentication Features
Accessing User Data
The template provides authentication context:
// In any component
import { useAuthContext } from '@/context/AuthContext'
const { user, loading } = useAuthContext()
// User data includes:
// user.id, user.email, user.user_metadata, etc.Server-Side Access
// In API routes (already implemented in template)
import { createServerClient } from '@/lib/supabase-server'
const supabase = createServerClient()
const { data: { user }, error } = await supabase.auth.getUser()
if (!user) {
return Response.json({ error: 'Unauthorized' }, { status: 401 })
}Sign-In/Sign-Up Flow
The template handles authentication with custom forms:
- Email/Password: Built-in forms with validation
- Social Auth: Google/GitHub integration (configurable)
- Email Verification: Automatic email confirmation
- Profile Creation: Automatic database profile creation
- Redirect Handling: Seamless post-auth redirects
API Endpoints
The template includes these authentication APIs:
GET /api/auth- Check authentication statusGET /api/profiles- Get user profile dataPOST /api/profiles- Update user profile/auth/callback- Handle OAuth callbacks
Social Authentication
Enable OAuth Providers
- Go to Supabase Dashboard → Authentication → Providers
- Enable Google and/or GitHub
- Add OAuth client credentials from provider dashboards
- Set callback URL:
https://your-project-ref.supabase.co/auth/v1/callback
OAuth Integration
The template supports social login buttons:
// Social login (implemented in template)
const handleGoogleLogin = async () => {
const { error } = await supabase.auth.signInWithOAuth({
provider: 'google',
options: { redirectTo: `${window.location.origin}/auth/callback` }
})
}Authentication Flow
Sign-Up Process
- User visits
/sign-up - Fills out registration form
- Supabase sends verification email
- User clicks email confirmation link
- Redirected to
/auth/callback - Profile automatically created in database
- Redirected to dashboard
Sign-In Process
- User visits
/sign-in - Enters email/password or uses social login
- Authentication verified by Supabase
- Redirected to dashboard
- User profile loaded from database
Session Management
- Automatic Refresh: Sessions refreshed automatically
- Persistent Login: Sessions persist across browser restarts
- Secure Cookies: HTTPOnly cookies for server-side auth
- Real-time Updates: Authentication state updates in real-time
Database Operations
Profile Management
// Get user profile (implemented in template)
import { getUserProfile } from '@/lib/supabase/profile'
const profile = await getUserProfile()
// Update profile
import { updateUserProfile } from '@/lib/supabase/profile'
await updateUserProfile({ name: 'New Name' })Type-Safe Queries
// Using generated types (available in template)
import { Database } from '@/types/supabase'
type Profile = Database['public']['Tables']['profiles']['Row']
const { data: profiles } = await supabase
.from('profiles')
.select('*')
.returns<Profile[]>()Middleware Configuration
The template includes authentication middleware:
// middleware.ts protects routes
const protectedPaths = ['/dashboard']
const authPaths = ['/sign-in', '/sign-up']
// Automatic redirects based on auth state
// Authenticated users: redirect from auth pages to dashboard
// Unauthenticated users: redirect from protected pages to sign-inAdvanced Features
Row Level Security Policies
The template includes comprehensive RLS policies:
- Profile Access: Users can only read/write their own profiles
- Subscription Data: Users can only access their own subscription data
- Service Role Access: Admin operations use service role key
Real-Time Subscriptions
// Listen to auth state changes (implemented in template)
useEffect(() => {
const { data: { subscription } } = supabase.auth.onAuthStateChange(
(event, session) => {
// Handle auth state changes
setUser(session?.user ?? null)
}
)
return () => subscription.unsubscribe()
}, [])Email Configuration
Custom SMTP (Optional)
- Go to Supabase Dashboard → Authentication → Settings
- Configure SMTP settings for custom domain
- Customize email templates
- Update sender email and branding
Troubleshooting
Authentication not working:
- Check Supabase URL and keys in
.env.local - Verify project is not paused (free tier limitation)
- Ensure RLS policies allow data access
OAuth providers not working:
- Verify provider is enabled in Supabase dashboard
- Check OAuth client credentials are correct
- Ensure callback URLs match exactly
Profile creation failing:
- Check database trigger is properly set up
- Verify RLS policies allow profile creation
- Look at Supabase dashboard logs for errors
Session issues:
- Clear browser cookies and local storage
- Check middleware configuration
- Verify auth callback handling
Database connection issues:
- Check environment variables are set correctly
- Ensure database migrations have been applied
- Verify network connectivity to Supabase
Type errors:
- Regenerate database types:
supabase gen types typescript - Check TypeScript configuration
- Update Supabase client version