I have many of these "controllers":
app.get('/',function(req,res){
var stuff = { 'title': 'blah' };
res.render('mytemplate',stuff);
});
Notice res.render? I want to add this header to every response header I make:
X-XSS-Protection: 0
How can I add that response header automatically?
you could create your own middleware method like so:
and then change your routes to sth like this:
should work.
Just make sure this is the first controller you add, order is significant.
I find that another good place to inject default headers is during the Routing Middleware. This way, all routes controlled by the router instance will receive the headers.
For example:
For express 4.x, the idiomatic way is as follows:
Implementation
Test
Dev Dependencies (for tests to work)
Relevant Documentation
I'd like to point out that none of these answer actually answer the question; the question is specifically relating to render responses; e.g. for an app like:
It's not clear how to add headers (e.g. CSP headers, which can be very verbose) only to your HTML responses. Express doesn't have a hook to specifically do that. The only option at the moment is to organize your code so you don't have to, e.g.
...which allows you to do as some of the other answers suggest, and add generic middleware for setting the headers.
You probably want to use app.use with your own middleware: