Next.js Discord

Discord Forum

NextResponse.redirect not working correctly

Unanswered
Ocicat posted this in #help-forum
Open in Discord
OcicatOP
Hey Guys,
I have the following code which is not functioning correctly

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) {
      // to the "next" URL if it's a relative URL prone to failure 
      //${origin}${next}
      return NextResponse.redirect(`${origin}${next}`)
    }
  }

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


I've even changed it to and it fails too.
     const callbackurl = process.env.ORIGIN_URL
      // redirect to the "next" URL if it's a relative URL prone to failure 
      //${origin}${next}
      return NextResponse.redirect(`${callbackurl}/home`)

In production it redirects to localhost


Only works when I hard code the string.


Am I doing anything wrong, How can I resolve this?
Thank you

0 Replies