0
0
Expressframework~5 mins

Why middleware is Express's core concept

Choose your learning style9 modes available
Introduction

Middleware in Express helps handle requests step-by-step. It lets you add features like logging, security, or data parsing easily.

You want to log every request to your server.
You need to check if a user is logged in before showing a page.
You want to handle errors in one place.
You want to parse incoming data like JSON automatically.
You want to serve static files like images or stylesheets.
Syntax
Express
app.use(function (req, res, next) {
  // your code here
  next();
});
Middleware functions take three arguments: request, response, and next.
Calling next() passes control to the next middleware in line.
Examples
This middleware logs the URL of every request.
Express
app.use((req, res, next) => {
  console.log('Request URL:', req.url);
  next();
});
This built-in middleware parses JSON data sent in requests.
Express
app.use(express.json());
This middleware checks if a user is logged in before continuing.
Express
app.use((req, res, next) => {
  if (!req.user) {
    res.status(401).send('Not logged in');
  } else {
    next();
  }
});
Sample Program

This example shows two middleware functions: one logs every request, the other parses JSON data. Then a route handles POST requests to '/data' and sends back the received data.

Express
import express from 'express';
const app = express();

// Middleware to log request method and URL
app.use((req, res, next) => {
  console.log(`${req.method} ${req.url}`);
  next();
});

// Middleware to parse JSON body
app.use(express.json());

// Route handler
app.post('/data', (req, res) => {
  res.send(`Received data: ${JSON.stringify(req.body)}`);
});

app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});
OutputSuccess
Important Notes

Middleware runs in the order you add it with app.use().

Always call next() unless you send a response to avoid hanging requests.

Summary

Middleware lets you add reusable steps to handle requests.

It is the core way Express processes requests and responses.

Using middleware keeps your code organized and flexible.