Production Authentication & SSR Architecture

Production Authentication & SSR Architecture in Supabase: Modern authentication requires supporting multiple identity providers, passwordless flows, and secure…

Modern authentication requires supporting multiple identity providers, passwordless flows, and secure session persistence across client components, Server Components, and Edge Middleware.


Authentication Strategies Supported

  1. Email & Password: Traditional registration with secure hashing (Argon2 / bcrypt) handled internally by GoTrue.
  2. Passwordless Magic Links: Password-free authentication via email verification tokens.
  3. SMS OTP: One-Time Passcodes delivered via Twilio, MessageBird, or Vonage.
  4. Third-Party OAuth: Google, GitHub, Apple, Discord, Azure, etc., using PKCE (Proof Key for Code Exchange).
  5. SAML 2.0 / Enterprise SSO: Single Sign-On integration for corporate identity providers (Okta, Azure AD).

Implementing PKCE OAuth in Web Applications

PKCE is the recommended security standard for single-page applications and mobile apps to mitigate authorization code interception attacks:

import { supabase } from '@/lib/supabase';

// Trigger OAuth sign-in flow
async function signInWithGoogle() {
  const { data, error } = await supabase.auth.signInWithOAuth({
    provider: 'google',
    options: {
      redirectTo: `${window.location.origin}/auth/callback`,
      queryParams: {
        access_type: 'offline',
        prompt: 'consent',
      },
    },
  });
  if (error) console.error('OAuth initiation failed:', error.message);
}

Server-Side Rendering (SSR) with @supabase/ssr

In modern frameworks like Next.js App Router, auth tokens cannot be stored in localStorage because the server cannot access browser storage during SSR. The modern standard is using HTTP-only cookies managed via @supabase/ssr:

npm install @supabase/ssr

1. Server Component / Route Handler Client

import { createServerClient } from '@supabase/ssr';
import { cookies } from 'next/headers';

export async function createClient() {
  const cookieStore = await cookies();

  return createServerClient(
    process.env.NEXT_PUBLIC_SUPABASE_URL!,
    process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
    {
      cookies: {
        getAll() {
          return cookieStore.getAll();
        },
        setAll(cookiesToSet) {
          try {
            cookiesToSet.forEach(({ name, value, options }) =>
              cookieStore.set(name, value, options)
            );
          } catch {
            // The `setAll` method was called from a Server Component.
            // This can be ignored if you have middleware refreshing user sessions.
          }
        },
      },
    }
  );
}

2. Auth Callback Route Handler (/auth/callback/route.ts)

import { NextResponse } from 'next/server';
import { createClient } from '@/utils/supabase/server';

export async function GET(request: Request) {
  const { searchParams, origin } = new URL(request.url);
  const code = searchParams.get('code');
  const next = searchParams.get('next') ?? '/dashboard';

  if (code) {
    const supabase = await createClient();
    const { error } = await supabase.auth.exchangeCodeForSession(code);
    if (!error) {
      return NextResponse.redirect(`${origin}${next}`);
    }
  }

  // Return the user to an error page with instructions
  return NextResponse.redirect(`${origin}/auth/auth-code-error`);
}

Exercises

  1. Implement an email magic-link sign-in form with client-side loading and rate-limiting feedback.
  2. Build an auth guard middleware protecting all /dashboard/* routes in Next.js.
  3. Compare supabase.auth.getSession() vs supabase.auth.getUser() in terms of cryptographic verification on the server.