npm-express

Description
Fast, unopinionated, minimalist web framework for Node.js
Author
tessl
Last updated

How to use

npx @tessl/cli registry install tessl/npm-express@5.1.0

middleware.md docs/

1
# Built-in Middleware
2
3
Express includes several built-in middleware functions for common web application needs including body parsing and static file serving.
4
5
## Capabilities
6
7
### JSON Body Parser
8
9
Parse JSON request bodies and populate `req.body`.
10
11
```javascript { .api }
12
/**
13
* Parse JSON request bodies
14
* @param {object} options - Parser configuration options (optional)
15
* @returns {Function} Middleware function
16
*/
17
express.json(options?: object): Function;
18
```
19
20
**JSON Parser Options:**
21
22
```javascript { .api }
23
interface JsonOptions {
24
/**
25
* Controls maximum request body size (default: '100kb')
26
*/
27
limit?: string | number;
28
29
/**
30
* JSON reviver function passed to JSON.parse()
31
*/
32
reviver?: Function;
33
34
/**
35
* Enable strict mode - only parse arrays and objects (default: true)
36
*/
37
strict?: boolean;
38
39
/**
40
* Content-Type verification function or false to skip
41
*/
42
type?: string | string[] | Function | false;
43
44
/**
45
* Custom error verification function
46
*/
47
verify?: Function;
48
}
49
```
50
51
**Usage Examples:**
52
53
```javascript
54
const express = require('express');
55
const app = express();
56
57
// Basic JSON parsing
58
app.use(express.json());
59
60
// JSON parsing with options
61
app.use(express.json({
62
limit: '10mb', // Allow larger payloads
63
type: 'application/json', // Only parse application/json
64
strict: true // Only parse objects and arrays
65
}));
66
67
// Custom content type
68
app.use(express.json({
69
type: 'application/vnd.api+json' // Parse custom JSON content type
70
}));
71
72
// With verification
73
app.use(express.json({
74
verify: (req, res, buf, encoding) => {
75
// Verify request signature, log raw body, etc.
76
req.rawBody = buf;
77
}
78
}));
79
80
// Route using parsed JSON
81
app.post('/api/users', (req, res) => {
82
console.log(req.body); // Parsed JSON object
83
res.json({ received: req.body });
84
});
85
```
86
87
### URL-Encoded Body Parser
88
89
Parse URL-encoded request bodies (form data) and populate `req.body`.
90
91
```javascript { .api }
92
/**
93
* Parse URL-encoded request bodies
94
* @param {object} options - Parser configuration options (optional)
95
* @returns {Function} Middleware function
96
*/
97
express.urlencoded(options?: object): Function;
98
```
99
100
**URL-Encoded Parser Options:**
101
102
```javascript { .api }
103
interface UrlencodedOptions {
104
/**
105
* Parse extended syntax with rich objects (default: true)
106
*/
107
extended?: boolean;
108
109
/**
110
* Controls maximum request body size (default: '100kb')
111
*/
112
limit?: string | number;
113
114
/**
115
* Maximum number of parameters (default: 1000)
116
*/
117
parameterLimit?: number;
118
119
/**
120
* Content-Type verification function or false to skip
121
*/
122
type?: string | string[] | Function | false;
123
124
/**
125
* Custom error verification function
126
*/
127
verify?: Function;
128
}
129
```
130
131
**Usage Examples:**
132
133
```javascript
134
// Basic URL-encoded parsing
135
app.use(express.urlencoded({ extended: true }));
136
137
// Simple parsing (querystring library)
138
app.use(express.urlencoded({ extended: false }));
139
140
// URL-encoded parsing with options
141
app.use(express.urlencoded({
142
extended: true,
143
limit: '10mb',
144
parameterLimit: 2000
145
}));
146
147
// Handle form submissions
148
app.post('/contact', (req, res) => {
149
console.log(req.body); // { name: 'John', email: 'john@example.com', message: '...' }
150
res.send('Form received');
151
});
152
```
153
154
### Raw Body Parser
155
156
Parse raw request bodies into Buffer and populate `req.body`.
157
158
```javascript { .api }
159
/**
160
* Parse raw request bodies into Buffer
161
* @param {object} options - Parser configuration options (optional)
162
* @returns {Function} Middleware function
163
*/
164
express.raw(options?: object): Function;
165
```
166
167
**Raw Parser Options:**
168
169
```javascript { .api }
170
interface RawOptions {
171
/**
172
* Controls maximum request body size (default: '100kb')
173
*/
174
limit?: string | number;
175
176
/**
177
* Content-Type verification function or false to skip
178
*/
179
type?: string | string[] | Function | false;
180
181
/**
182
* Custom error verification function
183
*/
184
verify?: Function;
185
}
186
```
187
188
**Usage Examples:**
189
190
```javascript
191
// Parse all requests as raw buffers
192
app.use(express.raw());
193
194
// Parse specific content types as raw
195
app.use(express.raw({
196
type: 'application/octet-stream',
197
limit: '5mb'
198
}));
199
200
// Handle binary uploads
201
app.post('/upload', (req, res) => {
202
console.log(req.body); // Buffer containing raw data
203
console.log('Received', req.body.length, 'bytes');
204
res.send('Binary data received');
205
});
206
```
207
208
### Text Body Parser
209
210
Parse text request bodies into string and populate `req.body`.
211
212
```javascript { .api }
213
/**
214
* Parse text request bodies into string
215
* @param {object} options - Parser configuration options (optional)
216
* @returns {Function} Middleware function
217
*/
218
express.text(options?: object): Function;
219
```
220
221
**Text Parser Options:**
222
223
```javascript { .api }
224
interface TextOptions {
225
/**
226
* Controls maximum request body size (default: '100kb')
227
*/
228
limit?: string | number;
229
230
/**
231
* Content-Type verification function or false to skip (default: 'text/plain')
232
*/
233
type?: string | string[] | Function | false;
234
235
/**
236
* Custom error verification function
237
*/
238
verify?: Function;
239
240
/**
241
* Default charset when not specified (default: 'utf-8')
242
*/
243
defaultCharset?: string;
244
}
245
```
246
247
**Usage Examples:**
248
249
```javascript
250
// Parse text/plain requests
251
app.use(express.text());
252
253
// Parse custom text types
254
app.use(express.text({
255
type: 'text/csv',
256
limit: '2mb'
257
}));
258
259
// Handle text uploads
260
app.post('/data', (req, res) => {
261
console.log(req.body); // String containing text data
262
console.log('Text length:', req.body.length);
263
res.send('Text data received');
264
});
265
```
266
267
### Static File Serving
268
269
Serve static files from specified directory.
270
271
```javascript { .api }
272
/**
273
* Serve static files from specified directory
274
* @param {string} root - Root directory for static files
275
* @param {object} options - Static serving options (optional)
276
* @returns {Function} Middleware function
277
*/
278
express.static(root: string, options?: object): Function;
279
```
280
281
**Static Options:**
282
283
```javascript { .api }
284
interface StaticOptions {
285
/**
286
* Enable dotfiles serving ('allow', 'deny', 'ignore') (default: 'ignore')
287
*/
288
dotfiles?: string;
289
290
/**
291
* Set ETag generation (true, false, 'weak', 'strong') (default: true)
292
*/
293
etag?: boolean | string;
294
295
/**
296
* Set file extension fallbacks
297
*/
298
extensions?: string[];
299
300
/**
301
* Fallback file when file not found
302
*/
303
fallthrough?: boolean;
304
305
/**
306
* Enable immutable directive in Cache-Control (default: false)
307
*/
308
immutable?: boolean;
309
310
/**
311
* Directory index files (default: ['index.html'])
312
*/
313
index?: string[] | false;
314
315
/**
316
* Enable lastModified header (default: true)
317
*/
318
lastModified?: boolean;
319
320
/**
321
* Set max-age for Cache-Control (default: 0)
322
*/
323
maxAge?: number | string;
324
325
/**
326
* Enable redirect for trailing slash (default: true)
327
*/
328
redirect?: boolean;
329
330
/**
331
* Function to set custom headers
332
*/
333
setHeaders?: Function;
334
}
335
```
336
337
**Usage Examples:**
338
339
```javascript
340
// Basic static file serving
341
app.use(express.static('public'));
342
343
// Serve from specific path
344
app.use('/static', express.static('public'));
345
346
// Static serving with options
347
app.use(express.static('public', {
348
dotfiles: 'ignore', // Ignore dotfiles
349
etag: false, // Disable ETag generation
350
extensions: ['html', 'htm'], // Try these extensions
351
index: ['index.html'], // Index files
352
maxAge: '1d', // Cache for 1 day
353
redirect: false, // Don't redirect /foo to /foo/
354
setHeaders: (res, path, stat) => {
355
res.set('X-Timestamp', Date.now());
356
}
357
}));
358
359
// Multiple static directories
360
app.use(express.static('public'));
361
app.use(express.static('uploads'));
362
app.use(express.static('assets'));
363
364
// Virtual path prefix
365
app.use('/css', express.static('public/stylesheets'));
366
app.use('/js', express.static('public/javascripts'));
367
app.use('/images', express.static('public/images'));
368
```
369
370
### Middleware Combination Patterns
371
372
Common patterns for combining built-in middleware.
373
374
**Usage Examples:**
375
376
```javascript
377
const express = require('express');
378
const app = express();
379
380
// Standard web application middleware stack
381
app.use(express.json()); // Parse JSON bodies
382
app.use(express.urlencoded({ extended: true })); // Parse form data
383
app.use(express.static('public')); // Serve static files
384
385
// API server middleware stack
386
app.use(express.json({ limit: '10mb' })); // Large JSON payloads
387
app.use(express.raw({
388
type: 'application/octet-stream',
389
limit: '50mb'
390
})); // Binary uploads
391
392
// Content-type specific parsing
393
app.use('/api/json', express.json());
394
app.use('/api/form', express.urlencoded({ extended: true }));
395
app.use('/api/upload', express.raw({ limit: '100mb' }));
396
app.use('/api/text', express.text());
397
398
// Conditional middleware based on content type
399
app.use((req, res, next) => {
400
if (req.is('application/json')) {
401
express.json()(req, res, next);
402
} else if (req.is('application/x-www-form-urlencoded')) {
403
express.urlencoded({ extended: true })(req, res, next);
404
} else {
405
next();
406
}
407
});
408
```
409
410
### Error Handling with Built-in Middleware
411
412
Handle errors that occur during body parsing.
413
414
**Usage Examples:**
415
416
```javascript
417
// JSON parsing with error handling
418
app.use(express.json());
419
420
// Error handler for body parsing errors
421
app.use((err, req, res, next) => {
422
if (err instanceof SyntaxError && err.status === 400 && 'body' in err) {
423
console.error('Bad JSON:', err.message);
424
return res.status(400).json({ error: 'Invalid JSON' });
425
}
426
next(err);
427
});
428
429
// Size limit error handling
430
app.use((err, req, res, next) => {
431
if (err.type === 'entity.too.large') {
432
return res.status(413).json({
433
error: 'Request entity too large',
434
limit: err.limit
435
});
436
}
437
next(err);
438
});
439
440
// Comprehensive error handling for all body parser middleware
441
app.use((err, req, res, next) => {
442
// Handle different types of body parser errors
443
if (err.type === 'entity.parse.failed') {
444
return res.status(400).json({
445
error: 'Invalid request body format',
446
details: err.message
447
});
448
}
449
450
if (err.type === 'entity.verify.failed') {
451
return res.status(400).json({
452
error: 'Request body verification failed',
453
details: err.message
454
});
455
}
456
457
if (err.type === 'request.aborted') {
458
return res.status(400).json({
459
error: 'Request aborted',
460
details: 'Client closed connection'
461
});
462
}
463
464
if (err.type === 'request.timeout') {
465
return res.status(408).json({
466
error: 'Request timeout',
467
details: 'Request body read timeout'
468
});
469
}
470
471
if (err.type === 'charset.unsupported') {
472
return res.status(415).json({
473
error: 'Unsupported charset',
474
charset: err.charset
475
});
476
}
477
478
if (err.type === 'encoding.unsupported') {
479
return res.status(415).json({
480
error: 'Unsupported encoding',
481
encoding: err.encoding
482
});
483
}
484
485
// Pass other errors to the next error handler
486
next(err);
487
});
488
```
489
490
### Body Parser Error Types
491
492
Common error types thrown by Express built-in middleware:
493
494
```javascript { .api }
495
interface BodyParserError extends Error {
496
type: 'entity.too.large' | // Request body size exceeded limit
497
'entity.parse.failed' | // JSON/form parsing failed
498
'entity.verify.failed' | // Custom verify function failed
499
'request.aborted' | // Client aborted request
500
'request.timeout' | // Request timeout
501
'charset.unsupported' | // Unsupported character set
502
'encoding.unsupported' | // Unsupported content encoding
503
'parameters.too.many' | // Too many parameters (urlencoded)
504
'stream.encoding.set'; // Stream encoding already set
505
506
status: number; // HTTP status code
507
statusCode: number; // Alias for status
508
expose: boolean; // Whether error should be exposed to client
509
length?: number; // Content length that caused error
510
limit?: number; // Size limit that was exceeded
511
charset?: string; // Unsupported charset
512
encoding?: string; // Unsupported encoding
513
}
514
```
515
516
### Custom Body Parser Configuration
517
518
Advanced configuration for specific use cases.
519
520
**Usage Examples:**
521
522
```javascript
523
// Custom JSON parser for API versioning
524
app.use('/api/v1', express.json());
525
app.use('/api/v2', express.json({
526
reviver: (key, value) => {
527
// Transform v2 data format
528
if (key === 'date' && typeof value === 'string') {
529
return new Date(value);
530
}
531
return value;
532
}
533
}));
534
535
// Different limits for different endpoints
536
app.use('/api/upload', express.json({ limit: '50mb' }));
537
app.use('/api/data', express.json({ limit: '1mb' }));
538
539
// Content type specific handling
540
app.use(express.json({
541
type: ['application/json', 'application/vnd.api+json']
542
}));
543
544
app.use(express.text({
545
type: ['text/plain', 'text/csv', 'application/csv']
546
}));
547
```