Charset negotiation
A route supports several text encodings and wants to select the first compatible option advertised by the client.
Express.js · Pipe
Checks candidate character sets against the request’s Accept-Charset header. It returns the first accepted candidate or false when none is acceptable.
Call this request method with one or more candidate character sets. Express compares them with the request's Accept-Charset header and returns the first accepted candidate, or false when no candidate matches.
req.acceptsCharsets(charset)| Name | Type | Description |
|---|---|---|
charset | String | String[] | One or more character sets to test against the request's Accept-Charset header. |
String | false
const express = require('express');
const app = express();
app.get('/', (req, res) => {
const charset = req.acceptsCharsets('utf-8', 'iso-8859-1');
if (!charset) return res.sendStatus(406);
res.type('text').send(`Selected charset: ${charset}`);
});
app.listen(3000);Run the app and send an Accept-Charset header such as utf-8, iso-8859-1;q=0.5 to see the first accepted option.
A route supports several text encodings and wants to select the first compatible option advertised by the client.
An endpoint must reject requests when none of its supported character sets is accepted.
Middleware needs to branch behavior based on whether a request accepts a particular charset.
It accepts a string or an array of strings representing candidate character sets. Express evaluates those candidates against the request's Accept-Charset header and returns the first accepted one, or false if there is no match.
Follow-up: How should a route respond when no candidate is acceptable? Treat the false result as negotiation failure and commonly return HTTP 406 Not Acceptable.
The method uses the request's Accept-Charset header to determine whether candidates are acceptable. Quality values in that header influence the negotiation, as shown by the documented example with utf-8 and iso-8859-1.
Follow-up: What header should a client send to influence this method? It should send Accept-Charset with the preferred character sets and optional quality weights.
The method can be called with multiple charset arguments, such as utf-8 followed by iso-8859-1. The returned value identifies the first accepted candidate from the supplied choices.
Follow-up: What should be avoided in new code? Avoid the deprecated singular req.acceptsCharset() alias; use the plural method instead.
req.acceptsreq.acceptsEncodingsreq.acceptsLanguagesreq.is