Content-encoding negotiation
Offer compressed responses only when the client advertises a compatible encoding.
Express.js · Pipe
Negotiates a response content encoding using the request’s Accept-Encoding header. It returns the first accepted candidate or false when none is accepted.
Use this request method to negotiate a response content encoding against the client’s Accept-Encoding header. Pass one or more candidate encodings; the method returns the first accepted candidate or false when no candidate matches.
req.acceptsEncodings(encoding)| Name | Type | Description |
|---|---|---|
encoding | String | String[] | One or more encodings to test against the request’s Accept-Encoding header. |
String | false. Returns the first accepted encoding of the specified encodings, or false if none of them is accepted.
const express = require('express');
const app = express();
app.get('/', (req, res) => {
const encoding = req.acceptsEncodings('br', 'gzip');
if (encoding === false) {
return res.status(406).send('No supported content encoding');
}
res.set('Content-Encoding', encoding).send('compressed response');
});
app.listen(3000);The handler chooses the first supported encoding accepted by the request and rejects the request when neither candidate is acceptable.
Offer compressed responses only when the client advertises a compatible encoding.
Choose among multiple compression formats in a preferred order.
Reject requests that cannot receive any supported response encoding.
It compares the supplied encoding candidates with the request’s Accept-Encoding header and returns the first accepted encoding. If no candidate is acceptable, it returns false.
Follow-up: How would you respond when the result is false? Return an appropriate HTTP error, commonly 406 Not Acceptable, rather than applying an unsupported encoding.
The argument may be a single string or an array of strings. The candidates represent the encodings being tested against the request header.
Follow-up: Why might an array be useful? It lets the application provide a reusable candidate list instead of spelling out multiple arguments at each call site.
The method bases negotiation on the request’s Accept-Encoding header. For example, with gzip and deflate advertised, testing gzip before deflate returns gzip.
Follow-up: What should the application do after selecting an encoding? It should encode the response accordingly and set the matching Content-Encoding response header.
req.acceptsreq.acceptsCharsetsreq.acceptsLanguagesreq.getres.set