Home > Net >  Remembering the URL a user was trying to access when redirected to Login page in Next.Js
Remembering the URL a user was trying to access when redirected to Login page in Next.Js

Time:10-05

What I'm trying to do: If a user tried to go to the URL some-basepath/events/632dbb3f6852f but was not authenticated, I want to be redirected to something like some-basepath/login?redirect=events/632dbb3f6852f & after signing in, I should be taken to the URL I was trying to access.

(Note that here I encoded slashes as / but anything else that makes sense would also work)

What I tried in my useAuth custom hook which handles authentication:

if(user-not-logged-in){
   const asPath = router.asPath();
   console.log("as path = ",asPath);

   const encodedAsPath = encodeURIComponent(asPath);
   console.log("encoded as path = ",encodedAsPath);

   router.push({
      pathname:"/login",
      query: {redirect: encodedAsPath}
   });
}

and then in the login page:

useEffect(
   () => {
      const {redirect} = router.query;
      console.log("decoded redirect in login page = ",decodeURIComponent(redirect))
   },[router.isReady,router.asPath]
);

But when I navigate to the unauthorized page & I get redirected to login page I get the following results: enter image description here

And the url of the page is: enter image description here

And I can't understand what I did wrong.

CodePudding user response:

I'd like to clarify 2 things.

1 - /api/* are server-handled requests. There might be a logic there which correctly gives a 401 response status code for unauthenticated users.

2 - as /api/* are handled in the server, you cannot run React-related features there.

If those statements above resonate with your code, I assume those 401 responses are correct and they aren't errors. That's only the way the browser shows it to you in the DevTools.

If those statements above do not resonate with your code. Please, clarify where you are implementing the code you've provided.

CodePudding user response:

You could create a react context with a var called intentionalURL or something like that, that is set to the url the user tried to visit before redirecting with a function.

  • Related