Express res.format() Method
What you’ll learn
- How to serve different formats from one route.
- How
Acceptheader negotiation works in Express. - How to provide JSON, HTML, and plain text responses cleanly.
- How to handle unmatched formats safely with fallback logic.
Syntax
javascript
res.format({
'text/plain': function () {},
'text/html': function () {},
'application/json': function () {},
default: function () {}
})1
Return HTML, JSON, or text from one endpoint
javascript
app.get('/profile', function (req, res) {
var user = { id: 1, name: 'Mari' };
res.format({
'text/plain': function () { res.send('User: ' + user.name); },
'text/html': function () { res.send('<h1>' + user.name + '</h1>'); },
'application/json': function () { res.json(user); }
});
});2
Provide default fallback response
javascript
app.get('/stats', function (req, res) {
res.format({
'application/json': function () { res.json({ ok: true }); },
default: function () { res.type('text').send('ok=true'); }
});
});3
Handle unsupported formats explicitly
javascript
app.get('/data', function (req, res) {
res.format({
'application/json': function () { res.json({ items: [1, 2, 3] }); },
default: function () { res.status(406).send('Not Acceptable'); }
});
});⚠️ Common pitfalls
- Do not write multiple responses across format handlers; only one handler should execute.
- Always include a
defaulthandler to control unmatched Accept cases. - Keep payload shapes consistent across formats to avoid client confusion.
❓ FAQ
It selects a response handler based on the request Accept header and available content types.
Express can return 406 Not Acceptable unless a default handler is provided.
Yes, res.format() is designed for this exact use case.
Usually no. Helpers like res.json() and res.send() set it appropriately.
Yes, it improves robustness and avoids unexpected 406 responses.
Did you know?
res.format() checks the request Accept header and chooses the best matching response formatter.
4 people found this page helpful
