You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Next.js App Router with supabase.signInWithOAuth()
Client-Side
'use client';import{createClientComponentClient}from'@supabase/auth-helpers-nextjs';constgetURL=()=>{leturl=process?.env?.NEXT_PUBLIC_SITE_URL??// Set this to your site URL in production env.process?.env?.NEXT_PUBLIC_VERCEL_URL??// Automatically set by Vercel.'http://localhost:3000/';// Make sure to include https:// when not localhost.url=url.includes('http') ? url : `https://${url}`;// Make sure to including trailing /.url=url.charAt(url.length-1)==='/' ? url : `${url}/`;returnurl;};exportdefaultfunctionLoginButton(){constsupabase=createClientComponentClient();constsignIn=()=>{supabase.auth.signInWithOAuth({provider: 'google',options: {redirectTo: `${getURL()}auth/callback`,},});};return(<buttontype="button"className="rounded-md bg-btn-background px-4 py-2 no-underline hover:bg-btn-background-hover"onClick={signIn}>Login</button>);}
middleware.ts
import{createMiddlewareClient}from'@supabase/auth-helpers-nextjs';import{NextResponse}from'next/server';importtype{NextRequest}from'next/server';exportasyncfunctionmiddleware(req: NextRequest){constres=NextResponse.next();// Create a Supabase client configured to use cookiesconstsupabase=createMiddlewareClient({ req, res });// Refresh session if expired - required for Server Components// https://supabase.com/docs/guides/auth/auth-helpers/nextjs#managing-session-with-middlewareawaitsupabase.auth.getSession();returnres;}
app/auth/callback/route.ts
import{createRouteHandlerClient}from'@supabase/auth-helpers-nextjs';import{cookies}from'next/headers';import{NextResponse}from'next/server';exportasyncfunctionGET(request: Request){// The /auth/callback route is required for the server-side auth flow implemented// by the Auth Helpers package. It exchanges an auth code for the user's session.// https://supabase.com/docs/guides/auth/auth-helpers/nextjs#managing-sign-in-with-code-exchangeconstrequestUrl=newURL(request.url);constcode=requestUrl.searchParams.get('code');if(code){constsupabase=createRouteHandlerClient({ cookies });awaitsupabase.auth.exchangeCodeForSession(code);}// URL to redirect to after sign in process completesreturnNextResponse.redirect(requestUrl.origin);}
credit: https://www.reddit.com/r/Supabase/comments/15aa2bu/comment/jtku1ci/