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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With