Back to all posts

Middleware in Node.js


Middleware in Node.js is essentially a function that has access to the request and response objects, as well as the next middleware function in the application’s request-response cycle. It sits between the initial request and the final response, allowing you to perform various actions before the request reaches its destination or after the response is generated.


How it works:

  1. Request arrives: An incoming request triggers the execution of middleware functions.  
  2. Middleware execution: Each middleware function has the opportunity to:
    • Modify the request and response objects.  
    • Perform logic (e.g., authentication, logging, error handling).  
    • Call the next() function to pass control to the next middleware or route handler.
    • Terminate the request-response cycle by sending a response.  
  3. Response sent: Once all middleware functions have executed or a response has been sent, the response is returned to the client.

In below example:

  • The first middleware logs incoming requests.
  • The second middleware parses JSON request bodies.
  • The route handler responds with a list of users.
const express = require('express');
const app = express();

// Middleware function for logging
app.use((req, res, next) => {
  console.log(`${new Date()} ${req.method} ${req.url}`);
  next();
});

// Middleware for parsing JSON request bodies
app.use(express.json());

// Route handler
app.get('/users', (req, res) => {
  res.send('List of users');
});

app.listen(3000, () => {
  console.log('Server listening on port 3000');
});

By understanding middleware and its capabilities, you can build robust and efficient Node.js applications.