App Router Auth Callback

This is the route.ts for /app/auth/callback/route.ts This uses the modern SSR package from Supabase.
mail@pastecode.io avatar
unknown
typescript
8 months ago
1.4 kB
16
Indexable
Never
import { type CookieOptions, createServerClient } from "@supabase/ssr";
import { cookies } from "next/headers";
import { NextResponse } from "next/server";
import { baseUrl } from "@/app/utils/BaseURL";

export async function GET(request: Request) {
  const { searchParams } = new URL(request.url);
  console.log("searchParams", searchParams);
  const code = searchParams.get("code");

  const next = searchParams.get("next") ?? `${baseUrl}/dashboard`;
  console.log(`WE RECEIVED CODE: ${code} and are now redirecting to ${next}`);

  if (code) {
    const cookieStore = cookies();

    const supabase = createServerClient(
      process.env.NEXT_PUBLIC_SUPABASE_URL!,
      process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
      {
        cookies: {
          get(name: string) {
            return cookieStore.get(name)?.value;
          },
          set(name: string, value: string, options: CookieOptions) {
            cookieStore.set({ name, value, ...options });
          },
          remove(name: string, options: CookieOptions) {
            cookieStore.delete({ name, ...options });
          },
        },
      }
    );

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

  // return the user to an error page with instructions
  return NextResponse.error();
}
Leave a Comment