Express req.accepts() Method

Beginner
⏱️ 8 min read
📚 Updated: May 2026
🎯 4 Code Examples

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.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

4 people found this page helpful