0

I am working on nextjs & nextauth projects, with a custom sign-in page. Below are the configurations

Package.json

"next": "^12.0.8"
"next-auth": "^4.2.1"

[..nextauth].js

pages:{
  signIn:'/auth/signin'
},
callbacks: {
    async redirect({ url, baseUrl }) {
      console.log('redirect : '+url+' : '+baseUrl);
      if (url.startsWith(baseUrl)) return url
      // Allows relative callback URLs
      else if (url.startsWith("/")) return new URL(url, baseUrl).toString()
      return baseUrl;
    }
  }

I have a middleware in my profile folder, this is done to secure the files inside this folder. Which should be visible only when user signin.

Folder Structure :

enter image description here

_middleware.js

export { default } from "next-auth/middleware"

Issue : When i try to open the files inside profile folder, it shows the signin screen(working as expected) after successfully signing in the page doesn't redirect to callback url, it still stays on the signin page.

Yilmaz
  • 35,338
  • 10
  • 157
  • 202
Gourav Bhardwaj
  • 75
  • 2
  • 10

1 Answers1

0

Since you have this

pages:{
  signIn:'/auth/signin'
},

if you are on the "Cart" page and you are redirected to signin from "Cart" page, this "Cart" page will be on the query as callback=urlfromRedirected. So you have to catch it, after sign in you have to route it to callback. And when redirecting starts, redirect callback will intervene. catch the callbackUrl in getServerSideProps

export async function getServerSideProps(context) {
  const { req, query } = context;
  const session = await getSession({ req });
  const { callbackUrl } = query;
  if (session) {
    return {
      redirect: {
        destination: callbackUrl,
      },
    };
  }
  
  return {
    props: {
      callbackUrl,
    },
  };
}

If there is not session, we pass the callbackUrl to the component and in signInHandler you run this

 return Router.push(callbackUrl || "/");
Yilmaz
  • 35,338
  • 10
  • 157
  • 202