0
0
ExpressConceptBeginner · 3 min read

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.

javascript
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');
});
Output
Server running on http://localhost:3000 GET /
🎯

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, and next() 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.
âś…

Key Takeaways

Middleware in Express runs between receiving a request and sending a response to add extra processing.
Each middleware function must call next() to continue the request cycle unless it ends the response.
Middleware is useful for tasks like logging, authentication, parsing data, and error handling.
Using middleware keeps your app organized by separating common tasks from route handlers.