I'm using react-router-dom for routing in my reactjs app. And i want to prevent user from going back after login i.e i don't want to user go back again on login screen when he hit back button on browser after login.
-
Isn't the behavior of the Redirect component to replace the current history entry? – sn42 Apr 05 '19 at 12:42
-
You can refer this question https://stackoverflow.com/questions/25806608/how-to-detect-browser-back-button-event-cross-browser – Amol B Jamkar Apr 05 '19 at 12:42
4 Answers
Using componentDidUpdate
method of React page lifecycle, you can handled or disabled go back functionality in browser. basically componentDidUpdate
method will call automatocally when component got updated. so once your component is updated you can prevent to go back as below.
componentDidUpdate() {
window.history.pushState(null, document.title, window.location.href);
window.addEventListener('popstate', function(event) {
window.history.pushState(null, document.title, window.location.href);
});
}
This will prevent to user go back and uses the current page as a refernce for history object . so incase of user even click on back button of browser, they can not go backword in the last page.

- 3,072
- 4
- 22
- 35
You can checkout this codesandbox example may be that will help you or someone who is looking for the same.In this we can prevent the user to go back to previous page,For more detail checkout this medium article. here is small part of the code
componentDidMount() {
const { history } = this.props;
window.addEventListener("popstate", () => {
history.go(1);
});
}
for full working example click on this link.

- 8,922
- 5
- 28
- 52

- 475
- 3
- 8
Are you using redux? other wise you can add something on your render that checks if the user is already logged in it redirects him back to the page he was like:
import { Redirect } from 'react-router'
render(){
//I store my user JWT on this.props.currentUser redux state
this.props.currentUser && <Redirect to={'whatever page you want'} />
//OR you can also, if you have history, history.goBack()
So instead of forbidding going back, you forbid the user to ever going to the login page while logged in, it redirects him somewhere or back to where he was
-
Thanks for your suggestion. No, i'm not using redux yet in my app and the problem is i don't have login component in my app because i'm using a third party app for login/sign up so everything related to login handle by that app eg. Auth0 – Vishal Goel Apr 05 '19 at 12:29
-
Oh.... I see, sorry about that then... I think that's not something you should forbid in the first place, just let them make the mistake and go back – Apr 05 '19 at 12:34
window.addEventListener('popstate', function(event) {
});
use this function this will read your browser back button click event and after that whatever condition you want you can apply

- 644
- 3
- 14