How to Negotiate Content with Accept Headers
Implement proactive content negotiation: parse Accept headers, honor quality values, choose a representation, and answer 406 only when truly nothing matches.
On this page
Introduction
A single URL can serve several representations: JSON and XML of the same resource, HTML and JSON of the same page, English and French of the same document. Proactive content negotiation is how the server chooses which one to send based on what the client says it prefers. The mechanism is elegant in principle and full of small traps in practice: quality values that order preferences, wildcards that match broadly, and the question of when the server should refuse a request because it cannot produce anything acceptable.
This tutorial implements content negotiation for an HTTP API in Node.js. It covers the grammar of the Accept header, how to parse quality values, how to match media ranges against available representations, the correct use of the 406 status, and the Vary header that keeps caches honest. The examples negotiate between JSON and XML, but the same code extends to language and encoding.
Parse the Accept header grammar
The Accept header is a comma-separated list of media ranges, each optionally followed by parameters. The most important parameter is q, a quality value between zero and one that expresses relative preference. An entry with no q has an implicit value of one. A q of zero means the client explicitly does not want that type. Entries can be concrete such as application/json, or wildcard such as text/* or /.
Order in the header is not the preference order; the q value is. A client that sends text/html;q=0.8, application/json;q=0.9 prefers JSON even though HTML appears first. Ignoring q and taking the first entry is a common bug. Parse every entry, record its q, then rank candidates by descending q with a deterministic tie-break such as header order.
function parseAccept(header) {
if (!header) return [{ type: '*/*', q: 1, order: 0 }];
return header.split(',').map((part, order) => {
const [rawType, ...params] = part.trim().split(';');
let q = 1;
for (const p of params) {
const [k, v] = p.trim().split('=');
if (k === 'q') q = Math.max(0, Math.min(1, Number(v) || 0));
}
return { type: rawType.trim().toLowerCase(), q, order };
}).sort((a, b) => b.q - a.q || a.order - b.order);
}
Match ranges against available types
With the client’s ranked preferences in hand, walk them in order and pick the first that matches something you can produce. Matching follows specificity: an exact type matches only the same type, type/* matches any subtype of that type, and / matches anything. When two client ranges have the same quality, the more specific one should win, because it expresses a narrower intent. Build a small matcher that scores a candidate against a media range and returns the best match.
Define the set of representations once, then negotiate over it. Hard-coding the decision inside a handler makes the policy invisible and untestable. A negotiation function that takes the header and the available types and returns the chosen type is easy to unit test across the whole matrix.
function negotiate(header, available) {
const prefs = parseAccept(header);
for (const pref of prefs) {
if (pref.q <= 0) continue;
const [type, sub] = pref.type.split('/');
for (const candidate of available) {
const [ct, cs] = candidate.split('/');
if ((type === '*' || type === ct) && (sub === '*' || sub === cs)) {
return candidate;
}
}
}
return null; // nothing acceptable
}
Choose a representation and respond
When a match exists, serialize the resource in that representation and set Content-Type to the chosen type. Set Vary: Accept so caches key on the header; without it, a JSON response cached for one client can be served to another that asked for XML. If the choice depends on other request headers such as Accept-Language or Accept-Encoding, add those to Vary as well, remembering that each added dimension lowers the achievable cache hit rate.
If no representation matches and the client explicitly sent an Accept header, return 406 Not Acceptable. The body of a 406 can include a list of available types so a developer can correct the request. This distinction matters: return 406 only when the client constrained the response and you truly cannot satisfy it, not when the header was simply absent.
import { createServer } from 'node:http';
const AVAILABLE = ['application/json', 'application/xml'];
const renderers = {
'application/json': (d) => JSON.stringify(d),
'application/xml': (d) => '<root>' + JSON.stringify(d) + '</root>',
};
function handle(req, res) {
const hasAccept = typeof req.headers.accept === 'string';
const chosen = negotiate(req.headers.accept, AVAILABLE);
if (!chosen && hasAccept) {
res.writeHead(406, { 'content-type': 'text/plain', vary: 'Accept' });
res.end('Available: ' + AVAILABLE.join(', '));
return;
}
const type = chosen ?? AVAILABLE[0];
const body = renderers[type]({ ok: true });
res.writeHead(200, { 'content-type': type, vary: 'Accept' });
res.end(body);
}
createServer(handle).listen(3000);
Extend to language and encoding
The same grammar governs Accept-Language and Accept-Encoding, and the same negotiation function handles them given the right matchers. Language matching supports wildcards and quality values over language tags such as en, en-US, or *. Encoding negotiation usually has a fixed preference order on the server side, because the server knows which encodings it produces efficiently. Combine the decisions into one negotiation pass so a single request can select format, language, and encoding consistently.
Do not overload negotiation with authentication. The status code for an unauthenticated request is 401, not 406, even if the client also asked for an unacceptable type. Evaluate authorization first, so a caller never learns about content support without first proving identity.
Test the negotiation matrix
Negotiation has many branches and few of them are exercised in normal tests. Build a table that covers: exact match, type wildcard, full wildcard, two entries where the second has a higher q, all entries with q=0, a missing Accept header, and an Accept header with no match in the available set. Assert the chosen type and the status code for each row. Include a case that asserts Vary: Accept is present, because its absence is a silent caching bug.
curl -s -o /dev/null -w '%{content_type}\n' -H 'Accept: application/xml' http://localhost:3000/resource
curl -s -o /dev/null -w '%{http_code}\n' -H 'Accept: text/csv' http://localhost:3000/resource
# expect application/xml then 406
Common pitfalls
Ignoring quality values, taking the first entry instead of the highest q, returning 406 when the header was absent, omitting Vary, and forgetting that q=0 is a refusal are the recurring mistakes. Each has a direct fix in the parser or the response path, and all of them are caught by the negotiation table test if it covers the zero-quality and no-match rows.
Conclusion
Content negotiation is a small parser plus a predictable selection rule. Rank client preferences by quality value, match media ranges with correct wildcard handling, set Vary for every header that influenced the choice, and reserve 406 for the case where the client constrained the response and nothing acceptable exists. Self-check by running the negotiation table and confirming both the selected type and the Vary header; a passing table means the policy is deterministic and cache-safe.
Centralize the negotiation logic so format, language, and encoding share one tested decision path rather than three ad hoc branches.
Sources: MDN: Content negotiation, RFC 9110: Proactive negotiation, MDN: Accept header.
FAQ
- When should I return 406 Not Acceptable?
- Only when the client sent an Accept header and no available representation matches any of its media ranges. If the Accept header is absent or unparsable, send a sensible default representation instead of 406.
- Why do I need Vary: Accept?
- Different clients can receive different representations from the same URL based on their Accept header. Vary tells shared caches that the Accept header is part of the cache key, preventing one client's format from being served to another.
Report a problem with this articleOpens a pre-filled issue on GitHub.