Search code examples
javascriptreactjsreact-router-dom

Redirection URL not being shown in the browser


I'm trying to do a 3rd party authentication. I have a login page where user clicks on the login button and user is redirected to the 3rd party authorization page where on successful login user is redirected to a page of our choice, for e.g. In my case I have set it to http://localhost/redirection and then the request token is appended to it, that I would like to read. But now what happens is when user is redirected to something like http://localhost/redirection?request_token=asdfasfdas, it wouldn't work because user is not authenticated and automatically redirected to login page and I don't want to keep the redirection page directly accessible or any other endpoints. I just want to know what is an ideal way of doing this in react. I have my routes defined like this:

return (
  <Routes>
    <Route path="/" element={loggedIn ? <Home /> : <Navigate to="/login" />} />
    <Route path="/login" element={<Login />} />
    <Route path="/redirection" element={<Redirection />} />
  </Routes>
);

This is preventing the redirected url to be shown in the browser and automatically redirects the user to login page. I need the request token from the redirected url and also want to prevent direct access to the endpoints. Is there a way to solve this issue?


Solution

  • It appears like you are using React Router version 5.
    If that's the case you need to make the following changes, because currently every path matches "/" by default.
    Adding exact keyword, will make sure that match is exact.

    return (
      <Routes>
        <Route path="/" exact element={loggedIn ? <Home /> : <Navigate to="/login" />} />
        <Route path="/login" element={<Login />} />
        <Route path="/redirection" element={<Redirection />} />
        <Route path="*"><Redirect to="/" /></Route>
      </Routes>
    );