Express.js - How to set a header to all responses

34,334

Just use a middleware statement that executes for all routes:

// a middleware with no mount path; gets executed for every request to the app
app.use(function(req, res, next) {
  res.setHeader('charset', 'utf-8')
  next();
});

And, make sure this is registered before any routes that you want it to apply to:

app.use(...);
app.get('/index.html', ...);

Express middleware documentation here.

Share:
34,334
znat
Author by

znat

Updated on July 29, 2022

Comments

  • znat
    znat almost 2 years

    I am using Express for web services and I need the responses to be encoded in utf-8.

    I know I can do the following to each response:

    response.setHeader('charset', 'utf-8');
    

    Is there a clean way to set a header or a charset for all responses sent by the express application?

  • Miguel Mesquita Alfaiate
    Miguel Mesquita Alfaiate over 5 years
    What if you want to do this after the controller has generated the response? In case the header you are adding depends on the response body? something like a string length or hash of the body? I have tried this but the body of the response is always empty, as it seems to be executed before.
  • jfriend00
    jfriend00 over 5 years
    @BlunT - You can't do that. Headers are sent before the body is sent. Express caches the header values and sends them as soon as you start writing the body. So, as soon as you've started to send the body, you can no longer add or modify headers. If you need a hash in a header, then you have to pre-flight what you're going to send calculate the hash and set that header before you start writing the body. Or, select a format for the body data that allows you to specify properties as part of the body and located at the end of the body (not in headers which always precede the body).
  • Miguel Mesquita Alfaiate
    Miguel Mesquita Alfaiate over 5 years
    I wsa looking for a "beforeSend" event or something similar. I have found a solution for this already, someone answered my question: stackoverflow.com/questions/52201380/…