Im building an application including react router and I am trying to Logout out in app. I'm using history.push('/') to redirect to home page but by clicking on back arrow I'm again logged in app and redirected to previous screen. Is there any way to protect this.
I usually solve this by defining public and protected routes. Public routes are the ones which should be available to all users (login, register etc). Protected routes are the ones which only authenticate users can access.
For instance, lets say that we are storing current user's authentication key in our state. If we have /login public and /home protected routes, and a logout button, we can simply define the following logic:
const Router = props => {
const [key, setKey] = useState("Auth Key")
const publicRoutes = [<Route path="/login" component={Login} />]
const protectedRoutes = [<Route path="/home" component={Home} />]
return (
<Switch>
{key === null ? publicRoutes : protectedRoutes}
<button onClick={() => setKey(null)>Log out</button>}
</Switch>
)
}
This way, you will only allow authenticated users to access your protected routes. You need to find a better way of authenticating your users though, because in this case, if the client just changes his state from null to pretty much anything else, he will have full access to your protected routes. You will probably need to use some sort of JWT authentication key in order to verify user identity.