Understanding Middleware in Express.js

📘 Express.js 👁 37 views 📅 Nov 05, 2025
⏱ Estimated reading time: 3 min

Middleware in Express.js is a function that executes during the request-response cycle. It can modify the request or response objects, end the request-response cycle, or call the next middleware in the stack.

Think of middleware as layers through which a request passes before reaching the final route handler.


1. Types of Middleware

  1. Application-Level Middleware

    • Bound to an instance of express() using app.use() or app.METHOD().

    • Example: Logging, authentication, request parsing.

  2. Router-Level Middleware

    • Bound to an instance of express.Router().

    • Helps organize routes and middleware for specific route groups.

  3. Built-in Middleware

    • Express provides some built-in middleware, e.g.:

      • express.json() – Parses JSON request bodies.

      • express.urlencoded() – Parses URL-encoded request bodies.

  4. Third-Party Middleware

    • Middleware provided by npm packages, e.g.:

      • cors – Enable Cross-Origin Resource Sharing.

      • morgan – HTTP request logging.

      • body-parser – Parsing request bodies (now mostly replaced by express.json()).

  5. Error-Handling Middleware

    • Middleware that catches errors and sends responses.

    • Signature: (err, req, res, next).


2. Middleware Function Signature

function middlewareFunction(req, res, next) { // Modify req or res console.log('Middleware executed'); next(); // Pass to next middleware }
  • req – Request object

  • res – Response object

  • next – Function to pass control to the next middleware


3. Using Middleware

Example 1: Application-Level Middleware

const express = require('express'); const app = express(); const port = 3000; // Middleware to log request details app.use((req, res, next) => { console.log(`${req.method} ${req.url}`); next(); // Pass to next handler }); // Route app.get('/', (req, res) => { res.send('Hello, Middleware!'); }); app.listen(port, () => { console.log(`Server running at http://localhost:${port}`); });

Example 2: Using Built-in Middleware

app.use(express.json()); // Parse JSON request bodies app.post('/data', (req, res) => { res.json({ message: 'Data received', data: req.body }); });

Example 3: Error-Handling Middleware

// Route that throws an error app.get('/error', (req, res, next) => { const err = new Error('Something went wrong!'); next(err); // Pass error to error-handling middleware }); // Error-handling middleware app.use((err, req, res, next) => { res.status(500).json({ error: err.message }); });

4. Middleware Execution Flow

  1. Incoming request hits first middleware in the stack.

  2. Middleware modifies req/res or performs actions.

  3. Calls next() → passes control to next middleware or route handler.

  4. If next() is not called → request stops here.

  5. Errors can be passed using next(err) → goes to error-handling middleware.


5. Key Points

  • Middleware can be global (app.use) or route-specific.

  • Order of middleware matters.

  • Middleware is essential for tasks like:

    • Logging requests

    • Parsing request bodies

    • Authentication & authorization

    • Error handling


Middleware is one of the core concepts in Express.js, making it flexible and modular.


🔒 Some advanced sections are available for Registered Members
Register Now

Share this Post


← Back to Tutorials

Popular Competitive Exam Quizzes