Skip to content

Commit e1aba95

Browse files
dsbly1bjohansebas
andauthored
docs: add API option examples for Express 4 and 5 (#2385)
Co-authored-by: Sebastian Beltran <bjohansebas@gmail.com>
1 parent 573dfed commit e1aba95

4 files changed

Lines changed: 194 additions & 0 deletions

File tree

‎src/content/api/4x/api/express/index.mdx‎

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,10 +47,26 @@ const app: Express = express();
4747
The `reviver` option is passed directly to `JSON.parse` as the second argument. You can
4848
find more information on this argument [in the MDN documentation about
4949
JSON.parse](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#the_reviver_parameter).
50+
51+
```js
52+
app.use(express.json({
53+
reviver: (key, value) => key === 'createdAt' ? new Date(value) : value,
54+
}));
55+
// Body: {"createdAt":"2026-01-01T00:00:00Z"}
56+
// req.body.createdAt is a Date.
57+
```
58+
5059
</Param>
5160
<Param name="strict" type="Boolean" default="true">
5261
Enables or disables only accepting arrays and objects; when disabled will accept anything
5362
`JSON.parse` accepts.
63+
64+
```js
65+
app.use(express.json({ strict: false }));
66+
// Body: 42 -> req.body is the number 42.
67+
// With strict: true (the default), this body is rejected with status 400.
68+
```
69+
5470
</Param>
5571
<Param name="type" type="String | String[] | Function" default='"application/json"'>
5672
This is used to determine what media type the middleware will parse. This option can be a
@@ -64,6 +80,16 @@ const app: Express = express();
6480
This option, if supplied, is called as `verify(req, res, buf, encoding)`, where `buf` is a
6581
`Buffer` of the raw request body and `encoding` is the encoding of the request. The
6682
parsing can be aborted by throwing an error.
83+
84+
```js
85+
app.use(express.json({
86+
verify: (req, res, buf) => {
87+
req.rawBody = buf;
88+
},
89+
}));
90+
// req.rawBody contains the original Buffer, before JSON parsing.
91+
```
92+
6793
</Param>
6894
</Fragment>
6995
</Param>
@@ -241,15 +267,43 @@ app.post('/upload', (req: Request, res: Response) => {
241267
<Fragment slot="attributes">
242268
<Param name="caseSensitive" type="Boolean" default="false">
243269
Enable case sensitivity. Disabled by default, treating `/Foo` and `/foo` as the same.
270+
271+
```js
272+
// caseSensitive: treat "/Foo" and "/foo" as different routes
273+
const router = express.Router({ caseSensitive: true });
274+
router.get('/Foo', (req, res) => res.send('Matched /Foo exactly'));
275+
```
276+
244277
</Param>
245278
<Param name="mergeParams" type="Boolean" default="false" since="v4.5.0+">
246279
Preserve the `req.params` values from the parent router. If the parent and the child have
247280
conflicting param names, the child's value take precedence.
281+
282+
```js
283+
// mergeParams: access parent route params in child router
284+
const parent = express.Router();
285+
const child = express.Router({ mergeParams: true });
286+
287+
parent.use('/user/:userId', child);
288+
child.get('/comments', (req, res) => {
289+
// req.params.userId is available because mergeParams: true
290+
res.send(`Comments for user ${req.params.userId}`);
291+
});
292+
```
293+
248294
</Param>
249295
<Param name="strict" type="Boolean" default="false">
250296
Enable strict routing. Disabled by default, `/foo` and `/foo/` are treated the same by the
251297
router.
298+
299+
```js
300+
// strict: treat "/foo" and "/foo/" as different routes
301+
const strictRouter = express.Router({ strict: true });
302+
strictRouter.get('/foo/', (req, res) => res.send('Matched /foo/ with trailing slash'));
303+
```
304+
252305
</Param>
306+
253307
</Fragment>
254308
</Signature>
255309

@@ -296,12 +350,32 @@ For more information, see [Router](/api/router/).
296350
<Param name="fallthrough" type="Boolean" default="true">
297351
Let client errors fall-through as unhandled requests, otherwise forward a client error.
298352
See [fallthrough](#fallthrough) below.
353+
354+
```js
355+
app.use('/assets', express.static('public', { fallthrough: true }));
356+
app.use('/assets', (req, res) => {
357+
res.status(404).send('Asset not found');
358+
});
359+
// Missing files reach the fallback above.
360+
// With fallthrough: false, they reach error-handling middleware instead.
361+
```
362+
299363
</Param>
300364
<Param name="immutable" type="Boolean" default="false">
301365
Enable or disable the `immutable` directive in the `Cache-Control` response header. If
302366
enabled, the `maxAge` option should also be specified to enable caching. The `immutable`
303367
directive will prevent supported clients from making conditional requests during the life
304368
of the `maxAge` option to check if the file has changed.
369+
370+
```js
371+
// Use filenames that change whenever the file contents change.
372+
app.use('/assets', express.static('public', {
373+
maxAge: '1y',
374+
immutable: true,
375+
}));
376+
// Cache-Control: public, max-age=31536000, immutable
377+
```
378+
305379
</Param>
306380
<Param name="index" type="String | Boolean" default='"index.html"'>
307381
Sends the specified directory index file. Set to `false` to disable directory indexing.
@@ -572,6 +646,18 @@ app.post('/', (req: Request, res: Response) => {
572646
rich objects and arrays to be encoded into the URL-encoded format, allowing for a
573647
JSON-like experience with URL-encoded. For more information, please [see the qs
574648
library](https://www.npmjs.com/package/qs#readme).
649+
650+
```js
651+
// Form body: user[name]=Tobi
652+
app.post('/simple', express.urlencoded({ extended: false }), (req, res) => {
653+
res.json(req.body); // => { 'user[name]': 'Tobi' }
654+
});
655+
656+
app.post('/extended', express.urlencoded({ extended: true }), (req, res) => {
657+
res.json(req.body); // => { user: { name: 'Tobi' } }
658+
});
659+
```
660+
575661
</Param>
576662
<Param name="inflate" type="Boolean" default="true">
577663
Enables or disables handling deflated (compressed) bodies; when disabled, deflated bodies

‎src/content/api/4x/api/request/index.mdx‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -983,6 +983,17 @@ Body-parsing middleware must be loaded for `req.param()` to work predictably. Re
983983
<Param name="combine" type="Boolean" default="false">
984984
Specify if overlapping and adjacent ranges should be combined. When `true`, ranges are
985985
combined and returned as if they were specified that way in the header.
986+
987+
```js
988+
// Range: bytes=0-99,50-149
989+
const separate = req.range(1000, { combine: false });
990+
console.log(separate[0]); // => { start: 0, end: 99 }
991+
console.log(separate[1]); // => { start: 50, end: 149 }
992+
993+
const combined = req.range(1000, { combine: true });
994+
console.log(combined[0]); // => { start: 0, end: 149 }
995+
```
996+
986997
</Param>
987998
</Fragment>
988999
</Param>

‎src/content/api/5x/api/express/index.mdx‎

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,10 +55,26 @@ The Express object has the following methods that can be used to create middlewa
5555
The `reviver` option is passed directly to `JSON.parse` as the second argument. You can
5656
find more information on this argument [in the MDN documentation about
5757
JSON.parse](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#the_reviver_parameter).
58+
59+
```js
60+
app.use(express.json({
61+
reviver: (key, value) => key === 'createdAt' ? new Date(value) : value,
62+
}));
63+
// Body: {"createdAt":"2026-01-01T00:00:00Z"}
64+
// req.body.createdAt is a Date.
65+
```
66+
5867
</Param>
5968
<Param name="strict" type="Boolean" default="true">
6069
Enables or disables only accepting arrays and objects; when disabled will accept anything
6170
`JSON.parse` accepts.
71+
72+
```js
73+
app.use(express.json({ strict: false }));
74+
// Body: 42 -> req.body is the number 42.
75+
// With strict: true (the default), this body is rejected with status 400.
76+
```
77+
6278
</Param>
6379
<Param name="type" type="String | String[] | Function" default='"application/json"'>
6480
This is used to determine what media type the middleware will parse. This option can be a
@@ -72,6 +88,16 @@ The Express object has the following methods that can be used to create middlewa
7288
This option, if supplied, is called as `verify(req, res, buf, encoding)`, where `buf` is a
7389
`Buffer` of the raw request body and `encoding` is the encoding of the request. The
7490
parsing can be aborted by throwing an error.
91+
92+
```js
93+
app.use(express.json({
94+
verify: (req, res, buf) => {
95+
req.rawBody = buf;
96+
},
97+
}));
98+
// req.rawBody contains the original Buffer, before JSON parsing.
99+
```
100+
75101
</Param>
76102
</Fragment>
77103
</Param>
@@ -249,15 +275,43 @@ app.post('/upload', (req: Request, res: Response) => {
249275
<Fragment slot="attributes">
250276
<Param name="caseSensitive" type="Boolean" default="false">
251277
Enable case sensitivity. Disabled by default, treating `/Foo` and `/foo` as the same.
278+
279+
```js
280+
// caseSensitive: treat "/Foo" and "/foo" as different routes
281+
const router = express.Router({ caseSensitive: true });
282+
router.get('/Foo', (req, res) => res.send('Matched /Foo exactly'));
283+
```
284+
252285
</Param>
253286
<Param name="mergeParams" type="Boolean" default="false">
254287
Preserve the `req.params` values from the parent router. If the parent and the child have
255288
conflicting param names, the child's value take precedence.
289+
290+
```js
291+
// mergeParams: access parent route params in child router
292+
const parent = express.Router();
293+
const child = express.Router({ mergeParams: true });
294+
295+
parent.use('/user/:userId', child);
296+
child.get('/comments', (req, res) => {
297+
// req.params.userId is available because mergeParams: true
298+
res.send(`Comments for user ${req.params.userId}`);
299+
});
300+
```
301+
256302
</Param>
257303
<Param name="strict" type="Boolean" default="false">
258304
Enable strict routing. Disabled by default, `/foo` and `/foo/` are treated the same by the
259305
router.
306+
307+
```js
308+
// strict: treat "/foo" and "/foo/" as different routes
309+
const strictRouter = express.Router({ strict: true });
310+
strictRouter.get('/foo/', (req, res) => res.send('Matched /foo/ with trailing slash'));
311+
```
312+
260313
</Param>
314+
261315
</Fragment>
262316
</Signature>
263317

@@ -304,12 +358,32 @@ For more information, see [Router](/api/router/).
304358
<Param name="fallthrough" type="Boolean" default="true">
305359
Let client errors fall-through as unhandled requests, otherwise forward a client error.
306360
See [fallthrough](#fallthrough) below.
361+
362+
```js
363+
app.use('/assets', express.static('public', { fallthrough: true }));
364+
app.use('/assets', (req, res) => {
365+
res.status(404).send('Asset not found');
366+
});
367+
// Missing files reach the fallback above.
368+
// With fallthrough: false, they reach error-handling middleware instead.
369+
```
370+
307371
</Param>
308372
<Param name="immutable" type="Boolean" default="false">
309373
Enable or disable the `immutable` directive in the `Cache-Control` response header. If
310374
enabled, the `maxAge` option should also be specified to enable caching. The `immutable`
311375
directive will prevent supported clients from making conditional requests during the life
312376
of the `maxAge` option to check if the file has changed.
377+
378+
```js
379+
// Use filenames that change whenever the file contents change.
380+
app.use('/assets', express.static('public', {
381+
maxAge: '1y',
382+
immutable: true,
383+
}));
384+
// Cache-Control: public, max-age=31536000, immutable
385+
```
386+
313387
</Param>
314388
<Param name="index" type="String | Boolean" default='"index.html"'>
315389
Sends the specified directory index file. Set to `false` to disable directory indexing.
@@ -579,6 +653,18 @@ app.post('/', (req: Request, res: Response) => {
579653
rich objects and arrays to be encoded into the URL-encoded format, allowing for a
580654
JSON-like experience with URL-encoded. For more information, please [see the qs
581655
library](https://www.npmjs.com/package/qs#readme).
656+
657+
```js
658+
// Form body: user[name]=Tobi
659+
app.post('/simple', express.urlencoded({ extended: false }), (req, res) => {
660+
res.json(req.body); // => { 'user[name]': 'Tobi' }
661+
});
662+
663+
app.post('/extended', express.urlencoded({ extended: true }), (req, res) => {
664+
res.json(req.body); // => { user: { name: 'Tobi' } }
665+
});
666+
```
667+
582668
</Param>
583669
<Param name="inflate" type="Boolean" default="true">
584670
Enables or disables handling deflated (compressed) bodies; when disabled, deflated bodies

‎src/content/api/5x/api/request/index.mdx‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -897,6 +897,17 @@ For more information, or if you have issues or concerns, see [type-is](https://g
897897
<Param name="combine" type="Boolean" default="false">
898898
Specify if overlapping and adjacent ranges should be combined. When `true`, ranges are
899899
combined and returned as if they were specified that way in the header.
900+
901+
```js
902+
// Range: bytes=0-99,50-149
903+
const separate = req.range(1000, { combine: false });
904+
console.log(separate[0]); // => { start: 0, end: 99 }
905+
console.log(separate[1]); // => { start: 50, end: 149 }
906+
907+
const combined = req.range(1000, { combine: true });
908+
console.log(combined[0]); // => { start: 0, end: 149 }
909+
```
910+
900911
</Param>
901912
</Fragment>
902913
</Param>

0 commit comments

Comments
 (0)