Express req.acceptsCharsets() Method
What you’ll learn
- How
req.acceptsCharsets()matches requested character sets. - How to design safe UTF-8 defaults when charset header is missing.
- How to handle no-match charset scenarios clearly.
- How charset negotiation differs from media-type negotiation.
Syntax
javascript
req.acceptsCharsets(charset)
req.acceptsCharsets(charset1, charset2, ...)
req.acceptsCharsets([charsets])1
Basic charset negotiation
javascript
app.get('/message', function (req, res) {
var charset = req.acceptsCharsets('utf-8', 'iso-8859-1');
if (!charset) return res.status(406).send('Not Acceptable');
res.set('Content-Type', 'text/plain; charset=' + charset);
res.send('Hello');
});2
UTF-8 fallback strategy
javascript
app.get('/notes', function (req, res) {
var charset = req.acceptsCharsets('utf-8') || 'utf-8';
res.type('text/plain; charset=' + charset);
res.send('Notes response');
});❓ FAQ
It checks the Accept-Charset request header and returns the best matching charset from the values you provide.
It returns false so you can decide how to handle unsupported charset negotiation.
Not always. Many clients omit it, so your server should still apply sensible defaults like utf-8.
Yes. Pass an array or multiple arguments, such as req.acceptsCharsets('utf-8', 'iso-8859-1').
Most modern APIs default to utf-8, but acceptsCharsets is useful when strict compatibility is required.
Did you know?
req.acceptsCharsets() helps choose response character encoding by checking the client's Accept-Charset header.
4 people found this page helpful
