Auth

OAuth with PKCE flow for SSR

Learn how to configure OAuth authentication in your server-side rendering (SSR) application to work with the PKCE flow.

Setting up SSR client#

Check out our guide for creating a client to learn how to install the necessary packages, declare environment variables, and create a Supabase client configured for SSR in your framework.

Create API endpoint for handling the code exchange#

In order to use OAuth we will need to setup a endpoint for the code exchange, to exchange an auth code for the user's session, which is set as a cookie for future requests made to Supabase.

Create a new file at app/auth/callback/route.ts and populate with the following:

app/auth/callback/route.ts
import { cookies } from 'next/headers'
import { NextResponse } from 'next/server'
import { type CookieOptions, createServerClient } from '@supabase/ssr'

export async function GET(request: Request) {
const { searchParams, origin } = new URL(request.url)
const code = searchParams.get('code')
// if "next" is in param, use it as the redirect URL
const next = searchParams.get('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(`${origin}${next}`)
}
}

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

Let's point our .signInWithOAuth method's redirect to the callback route we create above:

await supabase.auth.signInWithOAuth({
provider,
options: {
redirectTo: `http://example.com/auth/callback`,
},
})

We only collect analytics essential to ensuring smooth operation of our services.

Learn more