0

I'm making a website that uses cookies to give the user an id. I want this id to get set when my user visits any page on my website. I don't want to program this in to each page individually. I'm using Express.

  • Why not use a reverse-proxy feature for it? nginx for example can attach headers. – LEQADA Mar 12 '20 at 15:34
  • Does this answer your question? [Express.js - How to set a header to all responses](https://stackoverflow.com/questions/31661449/express-js-how-to-set-a-header-to-all-responses) – LEQADA Mar 12 '20 at 15:38

2 Answers2

0

You can use an express application-level middleware to could set a cookie in every request in case the user don't have it, like:

app.use(function (req, res, next) {
  // by using cookie-parser
  if (!req.cookies.myCookie) {
    res.cookie('myCookie', .....);
  }

  next()
})
giankotarola
  • 765
  • 7
  • 13
0

Just add this middleware to the code:

app.use(function (req, res, next){
  if(!req.cookies.id){
    res.cookie("id", (Math.random().toString(36).slice(2)), {secure: true, expires: new Date(Date.now() + 1800000)});
  };
  next();
});