react redirect after login
How to router redirect after login ( React )
Introduction
Login flow is the key to managing websites. To make sure, many users are logged in with their credentials registered in your website, most websites allow only to reveal their content until the user is logged in. This means redirecting the user back to the login page if they are not logged in or have logged out of the session.
Today, in this comprehensive post, we will inspect in detail how to use React routers to regulate the flow of login/logout through redirecting the pages.
First thing first, I have used express-js rest API for react in this demonstration.
What is a REST web service?
A REST(Representational State Transfer) API proactively manages operability between the client request and the constraints set up then returns the appropriate HTTP response with the desired functionality.
The most pleasing thing about REST web services is that it is light weighted, embeddable, and consumable with other services.
Restful API services handle your intended application and promptly carry out the extensive operations of the client in a secure and stateless manner. Just how the name states, a transfer of a representation of a
state in a stateless manner.
Let’s get started!
In this code, note that two paths have been created.
The requisition “/login” discharges a function that listens to the requests incoming from the user through the post method. For the sake of the purpose, I have assumed the username and password.
The if condition checks the request for login, only to be fulfilled by the established criteria of that the req.body.username and req.body.password exists, and the provided username and password match the correct username and password.
If that’s the case then a token is being generated. This token is granted to the user that has requested to login.
How to redirect page after login using react-router-dom?
Good evening! I am having some trouble trying to redirect the user correctly. If the user is not logged in, then the website redirects the user directly to the login page. After the user is logged in, they are redirected to a page. However, whenever the tries to directly access a page using any link, it’s always redirected to the same page after the login.
Problem
App.js is actually redirecting the user to «/dashboard/» which is always redirecting the user to «/dashboard/quotes», no matter if the user access a different link as you can see on the code above. The login component is redirecting the user correctly whenever they are logged in or not. However, if the user that is already logged in tries to access directly a link (Ex: «/dashboard/something/id») they are always redirected to «/dashboard/quotes» no matter what.
I am using component in index.js file which does not allow direct link access (according to this answer) After changing it to HashRouter, it seems to have fixed the problem (Despite the # in the URL). But according to the documentation, it says that we should only use this to support legacy browsers, so I am not sure if it’s a correct answer.
I am not sure how I can solve this trouble. Can someone please help me out? I really appreciate the help and time!
Solution
Turns out I was doing the routing wrong. Redirecting was working correctly at a certain point but when using Switch as it was, it did not change correctly. Here is my solution:
Automatic redirect after login with react-router
I wanted to build a Facebook login into my react/react-router/flux application. I have a listener registered on the login event and would like to redirect the user to ‘/dashboard’ if they are logged in. How can I do that? location.push didn’t work very well, except after reloading the page completely.
8 Answers 8
Now we can use the component in React Router v4.
Rendering a will navigate to a new location. The new location will override the current location in the history stack, like server-side redirects.
The Router instance returned from Router.create can be passed around (or, if inside a React component, you can get it from the context object), and contains methods like transitionTo that you can use to transition to a new route.
Even though the question is already answered, I think it’s relevant to post the solution that worked for me, since it wasn’t covered in any of the solutions given here.
First, I’m using the router context on my LoginForm component
After that, I can access the router object inside my LoginForm component
PS: working on React-router version 2.6.0
Navigating Outside of Components
create your app with Router like this
Somewhere like a Redux middleware or Flux action:
I am using React-16.2.0 & React-router-4.2.0
And I get solution by this code this.props.history.push(«/»);
My working code:
I was also try by return But unlucky, this not working for me.
React router v5 using hooks
These steps are for authorisation redirect. But can be used for login/logout redirection also.
The accepts to prop as a string or an object. We can utilise the object to pass the redirection path after login/logout using hooks easily.
Get the pathname of url from where the is called using useLocation()
const
In the to prop of pass in the following object:
Redirect after login React.js
i’ve been trying since days to redirect my user after login to the home creating a callback function in my App.js and sending it as props to the login class component throught a loginregisterpage class component, but this doesn’t work, can someone have a look on it and tell me what i;m missing out? Thank you my code look like this
LoginRegisterPage class component
LoginPage class component
3 Answers 3
If you’re using React Router you can use the Redirect component:
But if you’re not inside a render function (i.e. you’re in a submit callback) or you want to rewrite browser history, use the useHistory hook (note: hooks work only in function components, not class components)
Define your handleSucess function in LoginRegisterPage instead of passing it as a prop and this should work.
Issue
App is defined outside the Router component so it has no history prop function to call to do any navigation.
Solution
Have the LoginRegisterPage component navigate upon successful authentication. It will need to access the history object of the nearest Router context. Normally this is achieved by consuming passed route props from the Route component.
Move LoginRegisterPage to be rendered by the component prop of the Route so it receives the route props and thus the history object as a prop.
Decorate your LoginRegisterPage with the withRouter Higher Order Component so the route props are injected as props.
If you need the handleSuccess callback to manage some auth state in App then I think it best to let App manage the authentication state and the LoginPage to still handle navigation. In this case, go with the second solution above so it receives both the handleSuccess callback and the history object.
Redirect page upon login using react-router-v5 and redux-toolkit
I’m using react-router-dom v5.2.
When I try to perform authentication without any async function (ie. comparing username and password to hardcoded values in react), everything works perfectly.
But when I do perform authentication using express and mongo, the redirection upon login stops working. If I login again, then the redirection happens. Protected routes still work (redirect to login page if the user is not logged in).
Here’s a small demo of the problem where I use do auth with express + mongo ie. async redux. This is not working as intended. https://youtu.be/Zxm5GOYymZQ
Here’s the link of the app where I use hardcoded username and password (both «test») to do auth. No async here. This works as intended. Username and password are both «test». https://poke-zoo.herokuapp.com/
Am I using react-router with redux-toolkit incorrectly?
3 Answers 3
Your code does not define redirection logic after login. You can do it in two way.
1st : You can define another redirection wrapper for authentication if you want your routes to redirect in case of authentication.
2nd : Another approach can be imperatively handling with history.push() or history.replace() :
Why didn’t your code work? Take a look at the code below :
What it does? It checks your browser path and check if it matches with given Route rule from top to down. If Route path matches then it renders the component if not it continues through down visiting each one of Route until it matches your 404.
So back to your case; when you login, you were not leaving «/» path. Because there is no logic implemented to leave the «/» path. So it again match with landing page even though it is authenticated. It matches with route path (Landing page) and stays there. It does not continue and try your logic on ProtectedRoute.
The current accepted answer fixes your issues, but does not properly identify the reason that you were having trouble. So I want to explain it for you (and anyone else reading this).
Problem: Redirecting Too Soon
So if you redirect to «/home» before the value of authState.isUserLoggedIn has been updated then you will end up getting redirected back to «/» instead of being able to view the Home component.
That’s why you are having these issues with asynchronous authentication:
When I try to perform authentication without any async function (ie. comparing username and password to hardcoded values in react), everything works perfectly.
But when I do perform authentication using express and mongo, the redirection upon login stops working.
Solution: Wait Before Redirecting
You need to wait for the authState to update before redirecting to a protected route.
There’s a lot of ways to do this, but in general we want to use selectors to listen for changes being posted to the redux state. Here’s one approach which uses the ModalLogin to conditionally render a Redirect component. I would also recommend including some sort of selector for login errors in case the dispatch finishes resolving but the login was unsuccessful. You would want to show an error message to the user in the modal.