Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Nextjs: Using a non-auth related search parameter code can be very problematic! #770

Open
williamlmao opened this issue Apr 19, 2024 · 0 comments
Labels
bug Something isn't working

Comments

@williamlmao
Copy link

williamlmao commented Apr 19, 2024

This maybe isn't a complete bug, but I think it's something people should be aware of. An extra warning could be nice.

I was using code=123 as a URL search param, completely unrelated to auth. Spent a couple hours trying to debug why a certain route was clearing auth cookies completely, turns out its because the nextjs auth callback file that you find in the supabase docs uses that search param.

This results in this error: helpers.js:108 POST http://localhost:54321/auth/v1/token?grant_type=pkce 403 (Forbidden) and

This was a pretty tough one to debug. I would recommend adding a hint to the 403 PKCE forbidden error, or switching the search param here to use something more unique to supabase.

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')

  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`)
}

@williamlmao williamlmao added the bug Something isn't working label Apr 19, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

1 participant