Supabase Authentication: Complete Guide to User Management

User authentication is the foundation of most modern applications, and Supabase provides a comprehensive authentication system built on the open-source GoTrue server that handles user signup, login, password recovery, email verification, session management, and OAuth integration out of the box. This complete guide covers all authentication methods including email/password, magic links, OAuth providers (Google, GitHub, Facebook, etc.), phone authentication, and anonymous users, along with session management, user metadata, password reset flows, and security best practices. Unlike building authentication from scratch—which requires handling password hashing, JWT tokens, email verification, rate limiting, and security vulnerabilities—Supabase provides enterprise-grade authentication in minutes while maintaining full control and customization. Before proceeding, ensure you've completed Supabase setup and understand the JavaScript client basics.
Authentication Methods
| Method | Description | Best For | Setup Complexity |
|---|---|---|---|
| Email/Password | Traditional credentials | All applications | Easy |
| Magic Links | Passwordless email login | Better UX, no passwords | Easy |
| OAuth (Social) | Google, GitHub, Facebook, etc. | Faster signup, trusted auth | Medium |
| Phone/SMS | OTP via SMS | Mobile apps, high security | Medium (requires provider) |
| Anonymous | Temporary users | Try before signup | Easy |
Email and Password Authentication
import { supabase } from './supabaseClient'
// Sign up new user
async function signUp(email, password) {
const { data, error } = await supabase.auth.signUp({
email: email,
password: password,
options: {
emailRedirectTo: 'https://yourapp.com/welcome',
data: {
full_name: 'John Doe',
age: 25
}
}
})
if (error) {
console.error('Signup error:', error.message)
return { success: false, error }
}
console.log('User created:', data.user)
return { success: true, user: data.user }
}
// Sign in existing user
async function signIn(email, password) {
const { data, error } = await supabase.auth.signInWithPassword({
email: email,
password: password
})
if (error) {
console.error('Login error:', error.message)
return { success: false, error }
}
console.log('Logged in:', data.user)
return { success: true, user: data.user, session: data.session }
}
// Sign out
async function signOut() {
const { error } = await supabase.auth.signOut()
if (error) console.error('Signout error:', error.message)
}Email/password is the most common authentication method. Supabase handles password hashing with bcrypt, email verification, and secure session management automatically. By default, users must verify their email before accessing the app. Learn detailed email authentication implementation including React components.
Magic Link Authentication
// Send magic link to user's email
async function sendMagicLink(email) {
const { data, error } = await supabase.auth.signInWithOtp({
email: email,
options: {
emailRedirectTo: 'https://yourapp.com/dashboard'
}
})
if (error) {
console.error('Magic link error:', error.message)
return { success: false, error }
}
console.log('Magic link sent to:', email)
return { success: true }
}
// User clicks link in email → automatically logged in
// No additional code needed - Supabase handles the callbackMagic links provide passwordless authentication improving user experience and security—users receive a one-time login link via email. This eliminates password management, reduces support requests for forgotten passwords, and improves conversion rates. Explore comprehensive magic link implementation.
OAuth Social Login
// Sign in with Google
async function signInWithGoogle() {
const { data, error } = await supabase.auth.signInWithOAuth({
provider: 'google',
options: {
redirectTo: 'https://yourapp.com/auth/callback',
scopes: 'email profile'
}
})
if (error) console.error('OAuth error:', error.message)
}
// Sign in with GitHub
async function signInWithGitHub() {
const { data, error } = await supabase.auth.signInWithOAuth({
provider: 'github'
})
}
// Available providers:
// - Google
// - GitHub
// - Facebook
// - Twitter
// - Discord
// - GitLab
// - Bitbucket
// - Azure
// - LinkedIn
// - Slack
// - Spotify
// - Twitch
// - Apple
// - 20+ more!OAuth enables users to sign in with existing accounts from Google, GitHub, Facebook, and 20+ providers. This reduces friction, increases trust, and provides verified email addresses. Each provider requires configuration in the Supabase dashboard with client IDs and secrets. Learn detailed OAuth setup for Google and GitHub.
Session Management
// Get current user
const { data: { user } } = await supabase.auth.getUser()
if (user) {
console.log('Current user:', user.email)
} else {
console.log('No user logged in')
}
// Get current session
const { data: { session } } = await supabase.auth.getSession()
if (session) {
console.log('Access token:', session.access_token)
console.log('Expires at:', session.expires_at)
}
// Listen to auth state changes
supabase.auth.onAuthStateChange((event, session) => {
switch(event) {
case 'SIGNED_IN':
console.log('User signed in:', session.user)
break
case 'SIGNED_OUT':
console.log('User signed out')
break
case 'TOKEN_REFRESHED':
console.log('Token refreshed')
break
case 'USER_UPDATED':
console.log('User updated')
break
}
})
// Refresh session manually (usually automatic)
const { data, error } = await supabase.auth.refreshSession()Supabase manages sessions automatically using JWT tokens stored in localStorage. Sessions refresh automatically before expiration, and the onAuthStateChange listener enables reactive UI updates when authentication state changes—perfect for updating navigation, displaying user info, or redirecting users.
Password Reset Flow
// Send password reset email
async function resetPassword(email) {
const { data, error } = await supabase.auth.resetPasswordForEmail(
email,
{
redirectTo: 'https://yourapp.com/reset-password'
}
)
if (error) {
console.error('Reset error:', error.message)
return { success: false, error }
}
console.log('Reset email sent to:', email)
return { success: true }
}
// Update password (on reset page after clicking email link)
async function updatePassword(newPassword) {
const { data, error } = await supabase.auth.updateUser({
password: newPassword
})
if (error) {
console.error('Update error:', error.message)
return { success: false, error }
}
console.log('Password updated successfully')
return { success: true }
}User Metadata
// Add metadata during signup
const { data, error } = await supabase.auth.signUp({
email: '[email protected]',
password: 'password123',
options: {
data: {
full_name: 'John Doe',
avatar_url: 'https://example.com/avatar.jpg',
subscription_plan: 'pro'
}
}
})
// Update user metadata
const { data, error } = await supabase.auth.updateUser({
data: {
full_name: 'Jane Smith',
preferences: {
theme: 'dark',
notifications: true
}
}
})
// Access user metadata
const { data: { user } } = await supabase.auth.getUser()
console.log('Full name:', user.user_metadata.full_name)
console.log('Avatar:', user.user_metadata.avatar_url)User metadata stores custom user information like names, avatars, preferences, and settings. This data lives in the auth.users table and is accessible via the JWT token. For relational data like posts or orders, create separate tables with foreign keys to auth.users.id instead of storing in metadata.
Security Best Practices
- Enable Email Verification: Require users to verify email addresses before account activation
- Implement Row Level Security: Protect user data with RLS policies ensuring users only access their own data
- Use Strong Password Policies: Configure minimum password length (8+ characters) in dashboard settings
- Never Expose Service Role Key: Use anon key in client apps; service role key only in secure servers
- Implement Rate Limiting: Supabase includes automatic rate limiting; monitor for abuse
- Handle Sessions Securely: Use HTTPS only, set secure cookie flags, and implement proper logout
Next Steps
- Build Login Components: Create React forms with email/password authentication
- Add Magic Links: Implement passwordless auth with magic link guide
- Configure OAuth: Set up Google and GitHub login for social authentication
- Secure Your Data: Implement Row Level Security policies for user data protection
- Build Complete App: Integrate auth with Next.js application
Conclusion
Supabase authentication provides enterprise-grade user management without the complexity of building from scratch—handling password security, session management, email verification, and OAuth integration through simple APIs. Whether implementing traditional email/password, modern passwordless magic links, or OAuth social login, Supabase offers flexible authentication methods suitable for any application. The automatic session management, JWT token handling, and built-in security features eliminate common authentication vulnerabilities while maintaining developer control and customization. Always remember that authentication is just the first step—combine it with Row Level Security policies to ensure complete data protection at the database level. With authentication mastered, you're equipped to build secure applications with proper user management, personalized experiences, and protected data. Continue your learning with detailed auth implementations and security best practices.
$ share --platform
$ cat /comments/ (0)
$ cat /comments/
// No comments found. Be the first!


