Skip to Content
DocsAuthenticationSupabase Authentication

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

  1. Go to supabase.com  and create an account
  2. Create a new project and wait for setup completion
  3. 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-here

3. How It Works in the Template

The template includes pre-configured authentication:

  • Auth Context: context/AuthContext.tsx manages authentication state
  • Client Configuration: lib/supabase.ts for client-side operations
  • Server Configuration: lib/supabase-server.ts for server-side operations
  • Middleware: middleware.ts protects 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 protection

Database 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:

  1. Email/Password: Built-in forms with validation
  2. Social Auth: Google/GitHub integration (configurable)
  3. Email Verification: Automatic email confirmation
  4. Profile Creation: Automatic database profile creation
  5. Redirect Handling: Seamless post-auth redirects

API Endpoints

The template includes these authentication APIs:

  • GET /api/auth - Check authentication status
  • GET /api/profiles - Get user profile data
  • POST /api/profiles - Update user profile
  • /auth/callback - Handle OAuth callbacks

Social Authentication

Enable OAuth Providers

  1. Go to Supabase Dashboard → Authentication → Providers
  2. Enable Google and/or GitHub
  3. Add OAuth client credentials from provider dashboards
  4. 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

  1. User visits /sign-up
  2. Fills out registration form
  3. Supabase sends verification email
  4. User clicks email confirmation link
  5. Redirected to /auth/callback
  6. Profile automatically created in database
  7. Redirected to dashboard

Sign-In Process

  1. User visits /sign-in
  2. Enters email/password or uses social login
  3. Authentication verified by Supabase
  4. Redirected to dashboard
  5. 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-in

Advanced 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)

  1. Go to Supabase Dashboard → Authentication → Settings
  2. Configure SMTP settings for custom domain
  3. Customize email templates
  4. 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
Last updated on