Is this an API you're building or a Web interface?
if an API, I wouldn't use redirects
function sessionValidation(req, res, next) {
if (req.originalUrl === '/api/login') {
next()
} else {
const sessionId = req.cookies['session_id'];
if (sessionId) {
next()
} else {
res.json({error:'Access Denied',reason:'NO_TOKEN_PRESENT'})
}
}
}
if a web interface
function sessionValidation(req, res, next) {
if (req.originalUrl === '/api/login') {
next()
} else {
const sessionId = req.cookies['session_id'];
if (sessionId) {
next()
} else {
res.redirect('/api/login');
}
}
}
Without knowing your setup fully - its a little hard to understand what is the right answer.
Also be carful about redirects and HTTP Methods - I think the redirect needs to handle the original method - else you may get 404 for the redirect target, I'm not entirely sure