Middleware Express.js

  • Middleware in Express.js is a function that has access to the request (req) and response (res) objects, as well as the next() function in the application’s request-response cycle.

    Middleware acts as a bridge between the request and the response, allowing developers to process, modify, or control requests before they reach the final route handler.

  • 🔹 What is Middleware?

    Middleware is a function that sits between a client request and the server response in an Express.js application. It can perform tasks such as:

    • Logging requests

    • Validating data

    • Handling authentication

    • Modifying request or response objects

    Middleware functions run in the order they are defined in the application, allowing developers to control how requests are processed before reaching the final route handler.

    Example:

Using Middleware in Express.js

This code demonstrates how to use middleware in Express.js. The middleware logs every incoming request’s method and URL, then passes control to the next function using next(). The root route (/) responds with "Hello, Express Middleware!", showing how middleware integrates into the request–response cycle.

const express = require('express');
const app = express();

// Simple middleware to log requests
app.use((req, res, next) => {
  console.log(`${req.method} request for ${req.url}`);
  next(); // Pass control to the next middleware
});

app.get('/', (req, res) => {
  res.send('Hello, Express Middleware!');
});

app.listen(3000, () => console.log('Server running on port 3000'));
  • Explanation:

    • app.use() registers a middleware function

    • next() passes the request to the next function or route handler

    • Middleware runs before the final response is sent

Lesson image
  • Include labels: “Processing”, “Request”, “Response”.

    🔹 Built-in Middleware

    Express.js provides built-in middleware functions that simplify common tasks without writing extra code.

    Common Built-in Middleware:

    • express.json() – Parses incoming JSON requests

    • express.urlencoded() – Parses URL-encoded data from HTML forms

    • express.static() – Serves static files like images, CSS, JS

    Example:

Parsing JSON Requests in Express.js

This code demonstrates how to handle JSON data sent by clients in Express.js. The express.json() middleware parses incoming JSON request bodies, allowing the /users POST route to access req.body and respond with a confirmation message.

// Parse JSON body
app.use(express.json());

app.post('/users', (req, res) => {
  console.log(req.body); // JSON data sent by client
  res.send('User data received');
});
  • Explanation:

    • express.json() automatically parses JSON requests

    • Middleware ensures the route handler receives data in a usable format

Lesson image
  • 🔹 Custom Middleware

    Custom middleware functions are defined by developers to handle specific tasks tailored to the application. These can include logging, authentication, error handling, or modifying requests.

    Example – Logging Middleware:

Creating Custom Middleware in Express.js

This code demonstrates how to create custom middleware in Express.js. The logger function logs the current date, request method, and URL for every incoming request, then passes control to the next middleware or route using next(). The root route (/) confirms that the middleware is active.

function logger(req, res, next) {
  console.log(`${new Date()} - ${req.method} ${req.url}`);
  next();
}

app.use(logger);

app.get('/', (req, res) => {
  res.send('Custom middleware works!');
});
  • Example – Authentication Middleware:

Authentication Middleware in Express.js

This code demonstrates how to implement authentication middleware in Express.js. The auth function checks the request’s authorization header and either allows access with next() or responds with 401 Unauthorized. The /dashboard route is protected and only accessible with valid credentials.

function auth(req, res, next) {
  if (req.headers.authorization === '12345') {
    next(); // Allow request
  } else {
    res.status(401).send('Unauthorized');
  }
}

app.get('/dashboard', auth, (req, res) => {
  res.send('Welcome to Dashboard');
});
  • Explanation:

    • Custom middleware can control access, log activity, or modify requests

    • Multiple custom middleware functions can be chained using next()