Built-in Middleware in Express: What It Is and How It Works
built-in middleware are functions included by default that process requests before your route handlers. They help with common tasks like parsing JSON or serving static files without extra setup.How It Works
Think of built-in middleware in Express as helpers that automatically prepare or modify incoming requests before your app handles them. They act like assistants who check and organize the mail before you open it, so you get it in a ready-to-use form.
When a request comes in, Express runs it through these middleware functions in order. Each middleware can read or change the request and response objects, then pass control to the next middleware or route handler. This chain makes it easy to add common features without repeating code.
Example
This example shows how to use Express's built-in middleware to parse JSON request bodies and serve static files from a folder named public.
import express from 'express'; const app = express(); // Built-in middleware to parse JSON bodies app.use(express.json()); // Built-in middleware to serve static files from 'public' folder app.use(express.static('public')); app.post('/data', (req, res) => { // req.body is already parsed JSON res.send(`Received data: ${JSON.stringify(req.body)}`); }); app.listen(3000, () => { console.log('Server running on http://localhost:3000'); });
When to Use
Use built-in middleware whenever you need to handle common tasks like parsing JSON or URL-encoded data, serving static files, or managing request headers. They save time and keep your code clean by avoiding manual parsing or file handling.
For example, if your app accepts JSON data from users, use express.json() to automatically convert it into a JavaScript object. If you want to serve images, styles, or scripts, use express.static() to serve those files easily.
Key Points
- Built-in middleware are included with Express and require no extra installation.
- They run before your route handlers to prepare requests or responses.
- Common built-in middleware include
express.json(),express.urlencoded(), andexpress.static(). - Using them keeps your app code simpler and more maintainable.