Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Express.JS: Attach cookie to statically served content

I use Express.JS to serve static content:

express.use(express.static('./../'));

When index.html is served, I would like to send a cookie alongside the response indicating if the user is signed in or not. Normally one should use res.cookie() but I cannot see how to use it for statically served content.

like image 886
Randomblue Avatar asked Dec 27 '22 11:12

Randomblue


1 Answers

Not sure why you need to do this, but you can place your own middleware before the static module.

The following quick hack should work:

function attach_cookie(url, cookie, value) {
  return function(req, res, next) {
    if (req.url == url) {
      res.cookie(cookie, value);
    }
    next();
  }
}

app.configure(function(){
  app.use(attach_cookie('/index.html', 'mycookie', 'value'));
  app.use(express.static(path.join(__dirname, 'public')));
});

The above inserts another function in the chain of middleware express uses before the static middleware. The new layer attaches the cookie to the response if the URL matches the specific one you are looking for -- and passes the response further down the chain.

like image 121
nimrodm Avatar answered Dec 29 '22 01:12

nimrodm