Node.js / Express - How do I set response character encoding?

You will probably want to explicitly add a charset to the end of your content-type string if you find it's not being set already by Express:

 res.set({ 'content-type': 'application/json; charset=utf-8' });

The charset is not always set automagically and does need to be set to work correctly everywhere (i.e. with all browsers and all ajax libraries) or you can run into encoding bugs.

In Express 4.x specifically I've found that depending on the object you trying to return, it normally automatically returns with content-type: application/json; charset=utf-8 when you call res.json(someObject), however not always.

When calling res.json() on some objects it can return content-type: application/json (i.e. without the charset encoding!). I'm not actually sure what triggers this, other than it's something about the specific object being returned.

I've only noticed it because of automated tests which explicitly checked the headers and found it was missing the charset declaration on some responses (even though the content-type was still application/json).


This worked for me

res.writeHead(200, {'Content-Type': 'text/html; charset=utf-8'});

Having similar issues I'm collecting Swedish characters from a database and outputting them as JSON object, node doesn't really care if json must be UTF-8 or not when the chars from the database isn't in UTF-8.. So assuming "you don't need to set anything" is false. Depending on what charsets you are working with.


Use res.charset: http://expressjs.com/api.html#res.charset

res.charset = 'value';
res.send('some html');
// => Content-Type: text/html; charset=value

However, JSON is UTF-8 by default so you don't need to set anything.