48

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?

znat
  • 13,144
  • 17
  • 71
  • 106

1 Answers1

77

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.

jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • 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. – Miguel Mesquita Alfaiate Sep 06 '18 at 13:41
  • 1
    @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). – jfriend00 Sep 06 '18 at 20:23
  • I wsa looking for a "beforeSend" event or something similar. I have found a solution for this already, someone answered my question: https://stackoverflow.com/questions/52201380/add-header-to-all-responses-after-processing-but-before-sending-to-client – Miguel Mesquita Alfaiate Sep 07 '18 at 07:33