john smith john smith - 3 months ago 14
Node.js Question

User clicks on back button while session is still authenticated and gets redirected to login page in node.js

I have a simple web application which has a login screen and an activity page which is only accessible when the user has supplied valid credentials. Assuming the user clicks on login with valid credentials and gets re-directed to the activity page.Now the user does not click on logout, instead he/she simply clicks on the back button of the browser and goes back to the login page. This behavior is obviously non-intuitive , I would assume while the user is logged in and he/she clicks on the back button to remain on the same page and not go back to the login page.

function loginUser(req, res) {
if (req.session.auth) // if user is still authenticated
{
res.redirect('/activity');
}
res.render('login');
}


This is a simple way I use currently to always redirect the user back to the activity page, however I find this a resource wasteful method since there are unwanted redirections introduced. My question is , is this the standard and cleanest way to implement the above behavior or is there a better mechanism ? I am using passport for authentication and storing jwt tokens.

EDIT: To re-iterate the above solution works only if the browser no-cache is enabled, contrary to which the controller for the login route does not even get called since the browser has cached the page. I am looking for something more robust. I don't think it is good practice to hard-code the browser to not cache the page in a production environment.

Answer

One of the "features" of (most) modern browsers is that clicking the back button navigates you back to the state at which that page was loaded. Unless you dynamically update the login page before navigating away to the logged in state, this is the experience you'll get.

What I'd suggest instead is once authenticated on the login page, instead of immediately redirecting the user to the logged in state, update the logged in page to indicate that the user is now logged in (e.g. if you have an avatar/profile icon in the top right, change the appearance of it with .js to indicate the user is logged in).

Once the state of the login view has been changed, then navigate to the appropriate content view (using a meta redirect might be the most appropriate, but you can do it how you like).

The value of this solution as opposed to forcing a redirect (detecting a cookie with js and re-navigating) is that if the user clicked the back button, chances are they had a reason to do so. Forced forward navigation is extremely irritating!

While StackOverflow doesn't actually do what you're trying to do, here's an example of what you could do with .js to dynamically update /login before you navigate away:

enter image description here enter image description here

Comments