42

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?

Sebastian
  • 1,710
  • 2
  • 16
  • 28
TIMEX
  • 259,804
  • 351
  • 777
  • 1,080

7 Answers7

84

You probably want to use app.use with your own middleware:

app.use(function(req, res, next) {
    res.header('X-XSS-Protection', 0);
    next();
});
Francesc Rosas
  • 5,915
  • 2
  • 30
  • 16
78
// global controller
app.get('/*',function(req,res,next){
    res.header('X-XSS-Protection' , 0 );
    next(); // http://expressjs.com/guide.html#passing-route control
});

Just make sure this is the first controller you add, order is significant.

BGerrissen
  • 21,250
  • 3
  • 39
  • 40
15

For express 4.x, the idiomatic way is as follows:

Implementation

// no mount path; executed for every request.
app.use(function (req, res, next) {
  res.set('X-XSS-Protection', 0);
  next();
});

Test

describe('Response Headers', function () {
  it('responds with header X-XSS-Protection: 0', function (done) {
    hippie(app)
    .get('/any/route/you/can/think/of')
    .expectHeader('X-XSS-Protection', 0)
    .end(done);
  });
});

Dev Dependencies (for tests to work)

% npm install --save-dev mocha hippie

Relevant Documentation

Wil Moore III
  • 6,968
  • 3
  • 36
  • 49
7

you could create your own middleware method like so:

addToHeader = function (req, res, next) {
  console.log("add to header called ... " + req.url);
  res.header('X-XSS-Protection', '0');
  next();
}

and then change your routes to sth like this:

app.get('/', addToHeader, function(req,res){
  var stuff = { 'title': 'blah' };
  res.render('mytemplate',stuff);
});

should work.

Philipp Kyeck
  • 18,402
  • 15
  • 86
  • 123
4

Use a middleware...

app.use(function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*")
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept")
  next()
})

But make sure you use it before your API method. Like this:

const app = express()

// middleware
app.use(function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*")
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept")
  next()
})

// api
app.get('/user', (req, res, next) => {
  service.doSomething
    .then(data => res.send(data))
    .catch(next)
})

app.use(handleError)

Took me a while to figure it out. I didn't see it mentioned anywhere so adding this to complement previous answers.

Evandro Pomatti
  • 13,341
  • 16
  • 97
  • 165
  • can you plz look into this: https://stackoverflow.com/questions/69409586/how-to-make-a-get-call-to-api-github-with-express-server – Tanzeel Oct 01 '21 at 17:03
3

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:

//...
var router = express.Router();

// middleware for all routes
router.use(function(req, res, next) {
  // inject default headers
  res.header('cache-control', 'private, max-age=0');
  res.header('expires', new Date(Date.now()).toUTCString());
  next();
});

// all routes below will now inherit 
// the middleware's default headers
router.get('/users', function(req, res){
   // I will return the user list, with default headers
   // ...
});
1

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:

const router = require('express').Router();
router.use('/test.json', (req, res) => res.json({ test: 'hi' });
router.use('/test.html', (req, res) => res.render('test'));

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.

app.use(jsonRouter);
app.use(htmlRouter);

...which allows you to do as some of the other answers suggest, and add generic middleware for setting the headers.

  • I think this answer was the answer we both were looking for: https://stackoverflow.com/a/48448925/6814172 – Emilio Jan 25 '18 at 19:07