Skip to content

How to redirect to previous page using react after authentication?

I want to redirect the user back to the page they were before using react after they authenticate. The problem is that they might have errored out while logging in so their previous page might be the login. I want to redirect them back to the page they tried to access. How do I do that using react?

Answer

You can use query parameters to redirect them back to the previous page. Suppose user is at /create-post but not authenticated. So you will redirect user to login page with a query param like this /login?q=create-post and after that you can use that param to redirect them back to previous page.