SyntaxStudy
Sign Up
Node.js Understanding Middleware and next()
Node.js Beginner 10 min read

Understanding Middleware and next()

Middleware in Express are functions that run during the request-response cycle. Each middleware receives req, res, and next. Calling next() passes control to the next middleware in the chain.

Middleware can execute code, modify the request/response objects, end the cycle, or call next().

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

// --- Application-level middleware ---

// Request logger:
app.use((req, res, next) => {
    console.log(`[${new Date().toISOString()}] ${req.method} ${req.url}`);
    next(); // MUST call next() or the request hangs
});

// Attach a request ID:
app.use((req, res, next) => {
    req.requestId = Math.random().toString(36).slice(2);
    res.setHeader('X-Request-ID', req.requestId);
    next();
});

// --- Route-level middleware ---
function requireJson(req, res, next) {
    if (req.headers['content-type'] !== 'application/json') {
        return res.status(415).json({ error: 'Content-Type must be application/json' });
    }
    next();
}

app.post('/api/data', requireJson, (req, res) => {
    res.json({ message: 'Data received', id: req.requestId });
});

// --- Error-handling middleware (4 parameters) ---
app.use((err, req, res, next) => {
    console.error(err.stack);
    res.status(500).json({ error: err.message || 'Internal Server Error' });
});

app.listen(3000);