javascript
51 lines · 9 steps
Content negotiation with res.format in Express
One Express route serves JSON, HTML, or CSV from the same data by matching the client's Accept header.
Explained by
highlit
1const express = require('express');
2const router = express.Router();
3
4router.get('/articles/:slug', async (req, res, next) => {
5 try {
6 const article = await Article.findBySlug(req.params.slug);
7
8 if (!article) {
9 return res.format({
10 'application/json': () => res.status(404).json({ error: 'Article not found' }),
11 'text/html': () => res.status(404).render('errors/404', { slug: req.params.slug }),
12 default: () => res.status(406).send('Not Acceptable')
13 });
14 }
15
16 const related = await article.relatedArticles({ limit: 5 });
17
18 res.format({
19 'application/json': () => {
20 res.json({
21 data: article.toJSON(),
22 related: related.map((a) => a.toSummary())
23 });
24 },
25
26 'text/html': () => {
27 res.render('articles/show', {
28 article,
29 related,
30 title: article.title
31 });
32 },
33
34 'text/csv': () => {
35 res.attachment(`${article.slug}.csv`);
36 res.send(article.toCsvRow());
37 },
38
39 default: () => {
40 res.status(406).json({
41 error: 'Not Acceptable',
42 supported: ['application/json', 'text/html', 'text/csv']
43 });
44 }
45 });
46 } catch (err) {
47 next(err);
48 }
49});
50
51module.exports = router;
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1res.format lets one handler serve multiple representations by branching on the Accept header instead of duplicating routes.
- 2Always supply a default branch so unsupported Accept headers return a clean 406 rather than falling through silently.
- 3Wrapping async handler logic in try/catch and forwarding to next(err) routes failures into Express's error middleware.
Related explainers
ruby
class Order class InvalidTransition < StandardError; end TRANSITIONS = {
A state machine for order transitions in Ruby
state-machine
data-driven
error-handling
Intermediate
8 steps
python
from flask import Blueprint, jsonify, request, abort v1 = Blueprint("users_v1", __name__) v2 = Blueprint("users_v2", __name__)
Versioning a Flask API with Blueprints
api versioning
blueprints
rest
Intermediate
7 steps
javascript
const express = require('express'); const router = express.Router(); const { pool } = require('../db'); const redis = require('../redis');
Building a health check endpoint in Express
health-check
timeouts
promise-race
Intermediate
9 steps
rust
use std::cmp::Ordering; use std::str::FromStr; #[derive(Debug, Clone, PartialEq, Eq)]
Parsing and ordering semantic versions in Rust
parsing
trait-implementation
ordering
Intermediate
8 steps
javascript
'use client'; import { useEffect } from 'react'; import * as Sentry from '@sentry/nextjs';
How a Next.js error boundary recovers
error-boundary
error-handling
observability
Intermediate
8 steps
ruby
class Registration < ApplicationRecord belongs_to :event validates :email, presence: true, format: { with: URI::MailTo::EMAIL_REGEXP }
Validating registrations in Rails
validations
i18n
error-handling
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/content-negotiation-with-res-format-in-express-explained-javascript-7d09/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.