When it comes to implementing the protected route in Nuxt, I have found that using middleware is the best approach. In my implementation, I utilized the cookie-universal-nuxt module.
Everything was running smoothly until I encountered a bug. When a user's session expires and they try to access a protected route, they are correctly redirected to the login page. However, if the user then clicks the back button on their browser, the protected page reappears even though the session has already expired.
I tried setting cookies and utilizing localStorage:
const expireAt = Helpers.getJwtData().exp * 1000
window.localStorage.setItem('tokenExpire',expireAt);
this.$cookies.set('tokenExpire', expireAt, { path: '/'})
middleware/autheticate.js
export default function (context) {
const expiry = context.$cookies?.get('tokenExpire');
const isLoggedIn = +expiry > new Date().getTime
if (!isLoggedIn) {
Helpers.logout();
context.redirect(`/login?redirect_path=${context.route.path}`);
}
}