Topics in this subject
Node.js 3 min read Updated 11 Aug 2026

Express Middleware

Understanding the request-response cycle and the power of the next() function.

🧑‍🏫 Sabse pehle — simple mein samjho#

Socho ek factory ka conveyor belt hai. Jab request aati hai, toh wo seedha final route (database saving) tak nahi jaati. Raste mein kayi "checkpoints" (Middleware) aate hain. Ek checkpoint check karta hai ki JSON valid hai ya nahi, dusra check karta hai ki user logged in hai ya nahi. Agar sab theek hai toh ye log bolte hain "Aage badho!" (next()). Agar koi galti pakdi gayi, toh wo yahi se request ko wapas bhej dete hain. Middleware Express ki sabse badi superpower hai.

What is a Middleware?#

A middleware is simply a function that has access to the Request object (req), the Response object (res), and the next function in the application's request-response cycle.

// A custom logging middleware
const loggerMiddleware = (req, res, next) => {
    console.log(`[${new Date().toISOString()}] ${req.method} ${req.url}`);
    
    // CRITICAL: You MUST call next() to pass control to the next middleware/route.
    // If you forget next(), the request will hang forever!
    next(); 
};

Global vs Route-Level Middleware#

1. Application-Level (Global)#

Applied to every single request that comes into your server.

app.use(loggerMiddleware); // Every request will be logged
app.use(express.json());   // Every request body will be parsed as JSON

2. Route-Level (Specific)#

Applied only to specific routes. Great for authentication (e.g., checking if a user is logged in before allowing them to delete a post).

const checkAuth = (req, res, next) => {
    const isLogged = true; // Pretend we check a token here
    if (isLogged) {
        next(); // User is allowed, proceed to the route
    } else {
        res.status(401).json({ error: "Unauthorized access" });
        // Notice we do NOT call next() here. The cycle stops.
    }
};

// Applying it to a specific route
app.delete('/api/posts/:id', checkAuth, (req, res) => {
    res.json({ message: "Post deleted successfully" });
});

Third-Party Middleware#

The Node.js ecosystem is full of incredibly useful middlewares you can install via npm.

  • cors: Allows your frontend (running on a different port/domain) to communicate with your backend.
  • morgan: A highly configurable logging middleware (better than writing your own).
  • helmet: Automatically secures your Express apps by setting various HTTP headers.
const cors = require('cors');
// Enable CORS for all routes
app.use(cors()); 

The Order Matters!#

Express executes middleware in the exact order they are defined in your code. If you place a route before app.use(express.json()), that specific route will not be able to read the JSON body! Always set up global middlewares at the very top of your file.