Home

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

_39
import { createServerClient, type CookieOptions } from '@supabase/ssr'
_39
import { cookies } from 'next/headers'
_39
import { NextResponse } from 'next/server'
_39
_39
export async function GET(request: Request) {
_39
const { searchParams } = new URL(request.url)
_39
const code = searchParams.get('code')
_39
const next = searchParams.get('next') ?? '/'
_39
_39
if (code) {
_39
const cookieStore = cookies()
_39
_39
const supabase = createServerClient(
_39
process.env.NEXT_PUBLIC_SUPABASE_URL!,
_39
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
_39
{
_39
cookies: {
_39
get(name: string) {
_39
return cookieStore.get(name)?.value
_39
},
_39
set(name: string, value: string, options: CookieOptions) {
_39
cookieStore.set({ name, value, ...options })
_39
},
_39
remove(name: string, options: CookieOptions) {
_39
cookieStore.delete({ name, ...options })
_39
},
_39
},
_39
}
_39
)
_39
_39
const { error } = await supabase.auth.exchangeCodeForSession(code)
_39
if (!error) {
_39
return NextResponse.redirect(next)
_39
}
_39
}
_39
_39
// return the user to an error page with instructions
_39
return NextResponse.redirect('/auth/auth-code-error')
_39
}

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


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