- Spec files
npm-express
Describes: pkg:npm/express@5.1.x
- Description
- Fast, unopinionated, minimalist web framework for Node.js
- Author
- tessl
- Last updated
middleware.md docs/
1# Built-in Middleware23Express includes several built-in middleware functions for common web application needs including body parsing and static file serving.45## Capabilities67### JSON Body Parser89Parse JSON request bodies and populate `req.body`.1011```javascript { .api }12/**13* Parse JSON request bodies14* @param {object} options - Parser configuration options (optional)15* @returns {Function} Middleware function16*/17express.json(options?: object): Function;18```1920**JSON Parser Options:**2122```javascript { .api }23interface JsonOptions {24/**25* Controls maximum request body size (default: '100kb')26*/27limit?: string | number;2829/**30* JSON reviver function passed to JSON.parse()31*/32reviver?: Function;3334/**35* Enable strict mode - only parse arrays and objects (default: true)36*/37strict?: boolean;3839/**40* Content-Type verification function or false to skip41*/42type?: string | string[] | Function | false;4344/**45* Custom error verification function46*/47verify?: Function;48}49```5051**Usage Examples:**5253```javascript54const express = require('express');55const app = express();5657// Basic JSON parsing58app.use(express.json());5960// JSON parsing with options61app.use(express.json({62limit: '10mb', // Allow larger payloads63type: 'application/json', // Only parse application/json64strict: true // Only parse objects and arrays65}));6667// Custom content type68app.use(express.json({69type: 'application/vnd.api+json' // Parse custom JSON content type70}));7172// With verification73app.use(express.json({74verify: (req, res, buf, encoding) => {75// Verify request signature, log raw body, etc.76req.rawBody = buf;77}78}));7980// Route using parsed JSON81app.post('/api/users', (req, res) => {82console.log(req.body); // Parsed JSON object83res.json({ received: req.body });84});85```8687### URL-Encoded Body Parser8889Parse URL-encoded request bodies (form data) and populate `req.body`.9091```javascript { .api }92/**93* Parse URL-encoded request bodies94* @param {object} options - Parser configuration options (optional)95* @returns {Function} Middleware function96*/97express.urlencoded(options?: object): Function;98```99100**URL-Encoded Parser Options:**101102```javascript { .api }103interface UrlencodedOptions {104/**105* Parse extended syntax with rich objects (default: true)106*/107extended?: boolean;108109/**110* Controls maximum request body size (default: '100kb')111*/112limit?: string | number;113114/**115* Maximum number of parameters (default: 1000)116*/117parameterLimit?: number;118119/**120* Content-Type verification function or false to skip121*/122type?: string | string[] | Function | false;123124/**125* Custom error verification function126*/127verify?: Function;128}129```130131**Usage Examples:**132133```javascript134// Basic URL-encoded parsing135app.use(express.urlencoded({ extended: true }));136137// Simple parsing (querystring library)138app.use(express.urlencoded({ extended: false }));139140// URL-encoded parsing with options141app.use(express.urlencoded({142extended: true,143limit: '10mb',144parameterLimit: 2000145}));146147// Handle form submissions148app.post('/contact', (req, res) => {149console.log(req.body); // { name: 'John', email: 'john@example.com', message: '...' }150res.send('Form received');151});152```153154### Raw Body Parser155156Parse raw request bodies into Buffer and populate `req.body`.157158```javascript { .api }159/**160* Parse raw request bodies into Buffer161* @param {object} options - Parser configuration options (optional)162* @returns {Function} Middleware function163*/164express.raw(options?: object): Function;165```166167**Raw Parser Options:**168169```javascript { .api }170interface RawOptions {171/**172* Controls maximum request body size (default: '100kb')173*/174limit?: string | number;175176/**177* Content-Type verification function or false to skip178*/179type?: string | string[] | Function | false;180181/**182* Custom error verification function183*/184verify?: Function;185}186```187188**Usage Examples:**189190```javascript191// Parse all requests as raw buffers192app.use(express.raw());193194// Parse specific content types as raw195app.use(express.raw({196type: 'application/octet-stream',197limit: '5mb'198}));199200// Handle binary uploads201app.post('/upload', (req, res) => {202console.log(req.body); // Buffer containing raw data203console.log('Received', req.body.length, 'bytes');204res.send('Binary data received');205});206```207208### Text Body Parser209210Parse text request bodies into string and populate `req.body`.211212```javascript { .api }213/**214* Parse text request bodies into string215* @param {object} options - Parser configuration options (optional)216* @returns {Function} Middleware function217*/218express.text(options?: object): Function;219```220221**Text Parser Options:**222223```javascript { .api }224interface TextOptions {225/**226* Controls maximum request body size (default: '100kb')227*/228limit?: string | number;229230/**231* Content-Type verification function or false to skip (default: 'text/plain')232*/233type?: string | string[] | Function | false;234235/**236* Custom error verification function237*/238verify?: Function;239240/**241* Default charset when not specified (default: 'utf-8')242*/243defaultCharset?: string;244}245```246247**Usage Examples:**248249```javascript250// Parse text/plain requests251app.use(express.text());252253// Parse custom text types254app.use(express.text({255type: 'text/csv',256limit: '2mb'257}));258259// Handle text uploads260app.post('/data', (req, res) => {261console.log(req.body); // String containing text data262console.log('Text length:', req.body.length);263res.send('Text data received');264});265```266267### Static File Serving268269Serve static files from specified directory.270271```javascript { .api }272/**273* Serve static files from specified directory274* @param {string} root - Root directory for static files275* @param {object} options - Static serving options (optional)276* @returns {Function} Middleware function277*/278express.static(root: string, options?: object): Function;279```280281**Static Options:**282283```javascript { .api }284interface StaticOptions {285/**286* Enable dotfiles serving ('allow', 'deny', 'ignore') (default: 'ignore')287*/288dotfiles?: string;289290/**291* Set ETag generation (true, false, 'weak', 'strong') (default: true)292*/293etag?: boolean | string;294295/**296* Set file extension fallbacks297*/298extensions?: string[];299300/**301* Fallback file when file not found302*/303fallthrough?: boolean;304305/**306* Enable immutable directive in Cache-Control (default: false)307*/308immutable?: boolean;309310/**311* Directory index files (default: ['index.html'])312*/313index?: string[] | false;314315/**316* Enable lastModified header (default: true)317*/318lastModified?: boolean;319320/**321* Set max-age for Cache-Control (default: 0)322*/323maxAge?: number | string;324325/**326* Enable redirect for trailing slash (default: true)327*/328redirect?: boolean;329330/**331* Function to set custom headers332*/333setHeaders?: Function;334}335```336337**Usage Examples:**338339```javascript340// Basic static file serving341app.use(express.static('public'));342343// Serve from specific path344app.use('/static', express.static('public'));345346// Static serving with options347app.use(express.static('public', {348dotfiles: 'ignore', // Ignore dotfiles349etag: false, // Disable ETag generation350extensions: ['html', 'htm'], // Try these extensions351index: ['index.html'], // Index files352maxAge: '1d', // Cache for 1 day353redirect: false, // Don't redirect /foo to /foo/354setHeaders: (res, path, stat) => {355res.set('X-Timestamp', Date.now());356}357}));358359// Multiple static directories360app.use(express.static('public'));361app.use(express.static('uploads'));362app.use(express.static('assets'));363364// Virtual path prefix365app.use('/css', express.static('public/stylesheets'));366app.use('/js', express.static('public/javascripts'));367app.use('/images', express.static('public/images'));368```369370### Middleware Combination Patterns371372Common patterns for combining built-in middleware.373374**Usage Examples:**375376```javascript377const express = require('express');378const app = express();379380// Standard web application middleware stack381app.use(express.json()); // Parse JSON bodies382app.use(express.urlencoded({ extended: true })); // Parse form data383app.use(express.static('public')); // Serve static files384385// API server middleware stack386app.use(express.json({ limit: '10mb' })); // Large JSON payloads387app.use(express.raw({388type: 'application/octet-stream',389limit: '50mb'390})); // Binary uploads391392// Content-type specific parsing393app.use('/api/json', express.json());394app.use('/api/form', express.urlencoded({ extended: true }));395app.use('/api/upload', express.raw({ limit: '100mb' }));396app.use('/api/text', express.text());397398// Conditional middleware based on content type399app.use((req, res, next) => {400if (req.is('application/json')) {401express.json()(req, res, next);402} else if (req.is('application/x-www-form-urlencoded')) {403express.urlencoded({ extended: true })(req, res, next);404} else {405next();406}407});408```409410### Error Handling with Built-in Middleware411412Handle errors that occur during body parsing.413414**Usage Examples:**415416```javascript417// JSON parsing with error handling418app.use(express.json());419420// Error handler for body parsing errors421app.use((err, req, res, next) => {422if (err instanceof SyntaxError && err.status === 400 && 'body' in err) {423console.error('Bad JSON:', err.message);424return res.status(400).json({ error: 'Invalid JSON' });425}426next(err);427});428429// Size limit error handling430app.use((err, req, res, next) => {431if (err.type === 'entity.too.large') {432return res.status(413).json({433error: 'Request entity too large',434limit: err.limit435});436}437next(err);438});439440// Comprehensive error handling for all body parser middleware441app.use((err, req, res, next) => {442// Handle different types of body parser errors443if (err.type === 'entity.parse.failed') {444return res.status(400).json({445error: 'Invalid request body format',446details: err.message447});448}449450if (err.type === 'entity.verify.failed') {451return res.status(400).json({452error: 'Request body verification failed',453details: err.message454});455}456457if (err.type === 'request.aborted') {458return res.status(400).json({459error: 'Request aborted',460details: 'Client closed connection'461});462}463464if (err.type === 'request.timeout') {465return res.status(408).json({466error: 'Request timeout',467details: 'Request body read timeout'468});469}470471if (err.type === 'charset.unsupported') {472return res.status(415).json({473error: 'Unsupported charset',474charset: err.charset475});476}477478if (err.type === 'encoding.unsupported') {479return res.status(415).json({480error: 'Unsupported encoding',481encoding: err.encoding482});483}484485// Pass other errors to the next error handler486next(err);487});488```489490### Body Parser Error Types491492Common error types thrown by Express built-in middleware:493494```javascript { .api }495interface BodyParserError extends Error {496type: 'entity.too.large' | // Request body size exceeded limit497'entity.parse.failed' | // JSON/form parsing failed498'entity.verify.failed' | // Custom verify function failed499'request.aborted' | // Client aborted request500'request.timeout' | // Request timeout501'charset.unsupported' | // Unsupported character set502'encoding.unsupported' | // Unsupported content encoding503'parameters.too.many' | // Too many parameters (urlencoded)504'stream.encoding.set'; // Stream encoding already set505506status: number; // HTTP status code507statusCode: number; // Alias for status508expose: boolean; // Whether error should be exposed to client509length?: number; // Content length that caused error510limit?: number; // Size limit that was exceeded511charset?: string; // Unsupported charset512encoding?: string; // Unsupported encoding513}514```515516### Custom Body Parser Configuration517518Advanced configuration for specific use cases.519520**Usage Examples:**521522```javascript523// Custom JSON parser for API versioning524app.use('/api/v1', express.json());525app.use('/api/v2', express.json({526reviver: (key, value) => {527// Transform v2 data format528if (key === 'date' && typeof value === 'string') {529return new Date(value);530}531return value;532}533}));534535// Different limits for different endpoints536app.use('/api/upload', express.json({ limit: '50mb' }));537app.use('/api/data', express.json({ limit: '1mb' }));538539// Content type specific handling540app.use(express.json({541type: ['application/json', 'application/vnd.api+json']542}));543544app.use(express.text({545type: ['text/plain', 'text/csv', 'application/csv']546}));547```