Is it possible to redirect the user to login.html from backend using node.js (v18.16.0) and express.js (v4.18.2)?

This is my current code.

const userList = require('./routes/userList');

app.use(session({
    secret: crypto.randomBytes(32).toString('hex'),
    resave: false,
    saveUninitialized: false,
}));

app.use((req, res, next) => {
    if (!req.session.isLoggedIn)                 
        return res.redirect('https://mysite/login/login.html')
    else         
        next();
})

app.use('/userList', userList);

What I want now is that if I try to reach a webpage and I’m not logged in (e.g. userList.html), node.js must redirects me to the form login.

userList.html on load makes an ajax post request (with jQuery v3.7.1) to the same node.js server to the endpoint /userList

What I would expect is that object req.session.isLoggedIn is undefined and so it would redirect to https://mysite/login/login.html

Here what actually happens.

requests done when I load userList.html

login.html is the first request done (excluding json configs files) and the response is its html code.

endpoint /userList is on status 304 and still pending

Finally, the webpage does not redirect to login.html but it remains https://mysite/users/userList.html

What am I doing wrong? Why do I see login.html in requests and it does not redirect to?

Thank you.

I tried to use the function res.sendFile() instead of res.redirect() but it does not change anything.

New contributor

Riccardo is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.