Skip to content

Instantly share code, notes, and snippets.

@edoves
Last active November 15, 2024 05:21
Show Gist options
  • Save edoves/4331346eba96491270a26e5f660c9ce9 to your computer and use it in GitHub Desktop.
Save edoves/4331346eba96491270a26e5f660c9ce9 to your computer and use it in GitHub Desktop.
src/utils/supabase/middleware.ts

Supabase Middleware public and private route

import { createServerClient } from '@supabase/ssr';
import { NextResponse, type NextRequest } from 'next/server';

export async function updateSession(request: NextRequest) {
  try {
    let supabaseResponse = NextResponse.next({
      request,
    });

    const supabase = createServerClient(
      process.env.NEXT_PUBLIC_SUPABASE_URL!,
      process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
      {
        cookies: {
          getAll() {
            return request.cookies.getAll();
          },
          setAll(cookiesToSet) {
            cookiesToSet.forEach(({ name, value, options }) =>
              request.cookies.set(name, value)
            );
            supabaseResponse = NextResponse.next({
              request,
            });
            cookiesToSet.forEach(({ name, value, options }) =>
              supabaseResponse.cookies.set(name, value, options)
            );
          },
        },
      }
    );

    // automatically invoked token refresh in supabase.
    const user = await supabase.auth.getUser();

    const protectedRoutes = ['/home', '/profile', '/analytics', '/wallet'];

    // Redirect unauthenticated users trying to access protected routes to "/signin"
    if (protectedRoutes.includes(request.nextUrl.pathname) && user.error) {
      return NextResponse.redirect(new URL('/signin', request.url));
    }

    const publicRoutes = ['/', '/signin', '/signup'];

    // Redirect authenticated users from public routes to "/home"
    if (publicRoutes.includes(request.nextUrl.pathname) && !user.error) {
      return NextResponse.redirect(new URL('/home', request.url));
    }

    return supabaseResponse;
  } catch (error) {
    return NextResponse.next({
      request: {
        headers: request.headers,
      },
    });
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment