Next.js Discord

Discord Forum

Getting invalid url after successful login redirect in next auth

Birman posted this in #help-forum
Open in Discord
I am trying to get redirected to the value of callbackUrl in the URL search param after a successful login. When I include the baseUrl i.e. return baseUrl + url in my redirect function, I am able to get redirected with no problem. But when I use only the urli.e. return url, I get an error that reads
Unhandled Runtime Error
TypeError: Failed to construct 'URL': Invalid URL

My next auth redirect function looks like this
export const authOptions: NextAuthOptions = {
  providers: [
      async authorize(credentials, _req) {...}
  callbacks: {
    async redirect({ url, baseUrl }) {
      if (url.startsWith('/')) {
        // return url; // <--- This returns http://localhost:3000/login?callbackUrl=%2Fdashboard 
        return `${baseUrl}${url}`; // <-- This returns http://localhost:3000/login?callbackUrl=http%3A%2F%2F127.0.0.1%3A3000%2Fdashboard

      return '/dashboard';

Can anyone help me why this is happening?

Note: Why do I want to exclude the baseUrl in the callback url? Because I am trying to share my local server remotely through ssh tunneling/port forwarding so that other remote users can test it out.
Thanks for reading.

0 Replies