Suggest an editImprove this articleRefine the answer for “What is middleware in Express.js?”. Your changes go to moderation before they’re published.Approval requiredContentWhat you’re changing🇺🇸EN🇺🇦UAPreviewTitle (EN)Short answer (EN)Middleware is a `(req, res, next)` function that runs between receiving the request and sending the response: it can read or modify `req`/`res`, stop the request, or pass control onward by calling `next()`. **Key point:** if a middleware doesn't call `next()`, the processing chain stops there - Express never reaches the next middleware or route; error-handling middleware always takes 4 arguments: `(err, req, res, next)`.Shown above the full answer for quick recall.Answer (EN)Image## 1. What middleware is in Express.js > **Middleware** is a **function** that runs **between receiving the request (Request)** and **sending the response (Response)**. Every middleware can: 1. Read or modify the `req` object (the request); 2. Read or modify the `res` object (the response); 3. Stop the request (e.g. return an error or a response); 4. Pass control onward, by calling the `next()` function. You can picture it like this: ```javascript Client → [Middleware 1] → [Middleware 2] → [Route Handler] → Response ``` ## 2. A simple middleware example ```javascript const express = require('express'); const app = express(); // Middleware: logging every request app.use((req, res, next) => { console.log(`${req.method} ${req.url}`); next(); // pass control to the next handler }); app.get('/', (req, res) => { res.send('Home page'); }); app.listen(3000, () => console.log('Server running')); ``` On every request: ```javascript GET / → The method and URL get logged → The response is sent ``` ## 3. What a middleware's structure looks like ```javascript function middleware(req, res, next) { // 1. Do something with the request // 2. Optionally modify res (e.g. add a header) // 3. Must call next() if we want to continue the chain } ``` If `next()` is **not called**, the chain **breaks**, Express never reaches the next middleware or route. ## 4. Types of middleware in Express | Type | Where it's used | Example | |---|---|---| | Application-level | Applied to the whole app | `app.use(...)` | | Router-level | Only for a specific router | `router.use(...)` | | Built-in | Built into Express (`express.json()`, `express.static()`) | | | Third-party | External packages (e.g. `morgan`, `cors`, `helmet`) | | | Error-handling | Handle errors, take **4 arguments** (`err, req, res, next`) | | ## 5. An example with several middleware ```javascript app.use(express.json()); // a built-in middleware for JSON parsing app.use((req, res, next) => { console.log('First middleware'); next(); }); app.use((req, res, next) => { console.log('Second middleware'); next(); }); app.get('/', (req, res) => { res.send('Third: the route'); }); ``` Output for GET `/`: ```javascript First middleware Second middleware Third: the route ``` ## 6. Error-handling middleware > Error-handling middleware in Express **always takes 4 arguments**: > `(err, req, res, next)` ```javascript app.use((err, req, res, next) => { console.error('Error:', err.message); res.status(500).send('Something went wrong'); }); ``` This middleware is called whenever an error happens somewhere in the code, or you call `next(err)`. ## 7. A practical middleware example ```javascript // Checking a token function authMiddleware(req, res, next) { if (req.headers.authorization === 'secret123') { next(); // all good, continue } else { res.status(401).send('Access denied'); } } app.get('/private', authMiddleware, (req, res) => { res.send('Secret information'); }); ``` Now `/private` is only reachable with the correct header. ## 8. Express's built-in middleware | Middleware | Purpose | |---|---| | `express.json()` | Parses a JSON request body | | `express.urlencoded()` | Parses data from HTML forms | | `express.static()` | Serves static files (HTML, CSS, JS, images) | ## 9. Popular third-party middleware | Package | Purpose | |---|---| | morgan | Request logging | | cors | Allowing cross-origin requests | | helmet | Hardening HTTP headers | | express-session | User sessions | | body-parser (deprecated, now built in) | Request-body parsing | ## 10. Summary > **Middleware in Express.js** is functions that run **in the HTTP request-processing chain**. > > They can: > > - modify `req` and `res`; > - perform checks, logging, parsing, etc.; > - pass control onward via `next()`; > - handle errors. > > Middleware is what makes Express a **flexible**, **modular**, and **extensible** framework.For the reviewerNote to the moderator (optional)Visible only to the moderator. Helps review go faster.