Mayoyo.site

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

  1. User fills signup form (/auth/sign-up)
  2. Supabase creates account and sends verification email
  3. User redirected to success page (/auth/sign-up-success)
  4. User clicks email link to verify account
  5. Account activated, user can login

User Login

  1. User enters credentials (/auth/login)
  2. Supabase validates and creates session
  3. User redirected to dashboard or intended page
  4. Session stored in cookies for persistence

Password Reset

  1. User requests reset (/auth/forgot-password)
  2. Supabase sends reset email
  3. User clicks link and sets new password (/auth/update-password)
  4. 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

  1. Go to Supabase Dashboard → Authentication → Email Templates
  2. Customize HTML templates
  3. Update links to point to your domain
  4. 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.:

  1. Configure in Supabase Dashboard → Authentication → Providers
  2. Add provider keys and secrets
  3. Update login form with social buttons
  4. Handle provider callbacks

Custom User Fields

Add fields to the signup process:

  1. Update profiles table schema
  2. Modify signup form components
  3. Update profile creation logic
  4. Add validation rules

Email Customization

Customize authentication emails:

  1. Design HTML templates in Supabase
  2. Add your logo and branding
  3. Update redirect URLs
  4. 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:

  1. Configure your database - Set up tables and relationships
  2. Set up payments - Connect Stripe for subscriptions
  3. Customize user experience - Update forms and flows
  4. Deploy securely - Configure production auth settings

Your authentication system is now ready to handle user management securely!