Express req.accepts() Method
What you’ll learn
- How
req.accepts()performs response format negotiation. - How to handle HTML vs JSON responses from one endpoint.
- How to detect unsupported formats and return proper status codes.
- How to avoid common Accept-header logic mistakes.
Syntax
javascript
req.accepts(types)
req.accepts(type1, type2, ...)1
Basic accepts check
javascript
app.get('/report', function (req, res) {
if (req.accepts('html')) return res.send('<h1>Report</h1>');
if (req.accepts('json')) return res.json({ title: 'Report' });
res.status(406).send('Not Acceptable');
});2
Selecting best match
javascript
app.get('/data', function (req, res) {
var type = req.accepts(['json', 'html', 'text']);
if (!type) return res.status(406).send('Not Acceptable');
res.type(type).send('Response in ' + type);
});❓ FAQ
It checks the request Accept header and returns the best match from formats you provide.
You can pass MIME types, extensions, or arrays like 'json', 'html', or ['html', 'json'].
It returns false, and you can respond with 406 Not Acceptable or a fallback format.
Yes. It helps serve JSON, HTML, or other representations based on client preference.
req.get('Accept') returns raw header text, while req.accepts() performs parsed matching logic.
Did you know?
req.accepts() helps choose the best response format based on the client's Accept header.
4 people found this page helpful
