What is Middleware in Express: Simple Explanation and Example
Middleware in Express is a function that runs during the request-response cycle to process requests or responses. It can modify requests, responses, or end the cycle, helping organize code and add features like logging or authentication.How It Works
Think of middleware as a helpful assistant in a restaurant kitchen. When an order (request) comes in, the assistant checks it, maybe adds some notes, and then passes it to the chef (final handler). Middleware functions sit between the request and response, doing tasks like checking user login, logging details, or changing data.
Each middleware function gets the request and response objects, plus a special next() function. Calling next() tells Express to move to the next middleware or the final response. If a middleware doesn’t call next(), the request stops there, like the assistant handling the order fully.
Example
This example shows a simple middleware that logs the request method and URL before sending a response.
import express from 'express'; const app = express(); // Middleware function to log request info app.use((req, res, next) => { console.log(`${req.method} ${req.url}`); next(); // Pass control to next middleware or route }); app.get('/', (req, res) => { res.send('Hello from Express middleware!'); }); app.listen(3000, () => { console.log('Server running on http://localhost:3000'); });
When to Use
Use middleware when you want to add reusable steps to handle requests in your app. Common uses include:
- Logging requests to see who visits your site.
- Checking if a user is logged in before allowing access.
- Parsing data sent by users, like JSON or form data.
- Handling errors in one place.
Middleware helps keep your code clean by separating these tasks from your main route logic.
Key Points
- Middleware functions run in order for every request unless stopped.
- They receive
req,res, andnext()to control flow. - Calling
next()moves to the next middleware or route. - Middleware can modify requests or responses.
- They help organize code and add features like authentication or logging.