Supabase Auth Helpers

authentication-libraryauthenticationJavaScriptTypeScriptReactNext.jsSvelteKitSSRcookie-authenticationsession-management

Authentication Library

Supabase Auth Helpers

Overview

Supabase Auth Helpers is a collection of helper libraries designed to integrate Supabase Authentication with various web frameworks like Next.js, React, and SvelteKit. It provides user session management, cookie-based authentication, and streamlined authentication flows for server-side rendering (SSR) environments.

Details

Supabase Auth Helpers provides a unified way to use Supabase authentication in both client-side and server-side contexts. Key features include authentication state management, automatic session token refresh, and framework-specific optimizations.

Key Components

  • createBrowserClient: Creates Supabase client for browser environments
  • createServerClient: Creates Supabase client for server environments (SSR support)
  • SessionManagerLayer: Session management layer
  • onAuthStateChange: Authentication state change monitoring

Framework-Specific Implementations

  • Next.js: Uses @supabase/ssr package for cookie-based session management
  • React: Provides UI components through @supabase/auth-ui-react
  • SvelteKit: Session management for both server-side and client-side

Security Features

  • Secure cookie-based authentication
  • Automatic JWT token refresh
  • Protection against session fixation attacks
  • CSRF attack prevention

Pros and Cons

Pros

  • Framework-Specific: Optimized implementations for each framework
  • SSR Support: Authentication support for server-side rendering
  • Easy Integration: Abstracts complex authentication logic
  • Security: Secure cookie-based authentication
  • Auto-Refresh: Automatic token refresh functionality
  • TypeScript Support: Type safety guarantees

Cons

  • Deprecated: Currently @supabase/ssr package is recommended
  • Framework Dependency: Limited to specific frameworks
  • Complexity: Initial setup can be complex
  • Version Management: Managing multiple framework-specific packages

Reference Links

Code Examples

Next.js Setup (Legacy)

// utils/supabase/client.js
import { createBrowserClient } from '@supabase/ssr'

export const createClient = () => 
  createBrowserClient(
    process.env.NEXT_PUBLIC_SUPABASE_URL,
    process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY
  )

Server-Side Client (Next.js)

// utils/supabase/server.js
import { createServerClient } from '@supabase/ssr'
import { cookies } from 'next/headers'

export const createClient = () => {
  const cookieStore = cookies()

  return createServerClient(
    process.env.NEXT_PUBLIC_SUPABASE_URL,
    process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY,
    {
      cookies: {
        get(name) {
          return cookieStore.get(name)?.value
        },
        set(name, value, options) {
          cookieStore.set({ name, value, ...options })
        },
        remove(name, options) {
          cookieStore.set({ name, value: '', ...options })
        },
      },
    }
  )
}

React Auth UI

// React with Auth UI
import { Auth } from '@supabase/auth-ui-react'
import { createClient } from '@supabase/supabase-js'

const supabase = createClient(
  process.env.REACT_APP_SUPABASE_URL,
  process.env.REACT_APP_SUPABASE_ANON_KEY
)

function AuthForm() {
  return (
    <Auth
      supabaseClient={supabase}
      appearance={{ theme: 'dark' }}
      providers={['google', 'github']}
    />
  )
}

Session Management

// Session monitoring
import { useEffect } from 'react'

useEffect(() => {
  const { data: { subscription } } = supabase.auth.onAuthStateChange(
    (event, session) => {
      if (event === 'SIGNED_IN') {
        // Login handling
        console.log('User signed in:', session.user)
      } else if (event === 'SIGNED_OUT') {
        // Logout handling
        console.log('User signed out')
      }
    }
  )

  return () => subscription.unsubscribe()
}, [])

Authentication Check

// Check authentication state
const checkAuth = async () => {
  const { data: { user } } = await supabase.auth.getUser()
  
  if (user) {
    console.log('User is authenticated:', user.email)
  } else {
    console.log('User is not authenticated')
  }
}

Logout Functionality

// Logout
const handleLogout = async () => {
  const { error } = await supabase.auth.signOut()
  if (error) {
    console.error('Error logging out:', error)
  } else {
    console.log('Successfully logged out')
  }
}