I am trying to restrict all pages if the user is not authenticated.
The strange thing is that my middleware is being called twice when I call the login page.
THe following are my code
app.use((req, res, next) => {
if (req.session.user) {
res.session.user = req.session.user;
}
if (req.isAuthenticated() || req.path === '/' || req.path === '/login'){
console.log('inside next');
next()
}else{
console.log('inside redirect');
res.redirect('/')
}
});
app.get('/', (req, res) => {
console.log('inside /')
res.render('./login', {
css: ['login.css'],
js: ['login.js']
})
});
When I go to localhost:8000/
which is my root page, it prints out following in the console
inside next
inside /
inside redirect
inside next
inside /
As you can see after get('/')
is called, the middleware is called once again to redirect the page. Why is this? If I remove the middleware, /
gets called only once.