Script Valley
REST API Development: Beginner to Production
Building Your First API with Node.js and ExpressLesson 2.4

Express middleware โ€” what it is and how to use it

middleware concept, next() function, request pipeline, global middleware, route-level middleware, error-handling middleware, middleware order

Express Middleware Pipeline

Middleware is a function that runs between receiving a request and sending a response. It has access to req, res, and a next function that passes control to the next middleware in the chain.

Writing Middleware

// Logger middleware
const logger = (req, res, next) => {
  console.log(`${req.method} ${req.url} โ€” ${new Date().toISOString()}`);
  next(); // MUST call next() or the request hangs
};

// Apply globally โ€” runs for every request
app.use(logger);

// Apply to a specific route only
app.get('/admin', isAdmin, (req, res) => {
  res.json({ secret: 'admin data' });
});

Error-Handling Middleware

Error middleware takes four parameters โ€” err, req, res, next. Express identifies it by the argument count.

// Must be registered LAST, after all routes
app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(err.status || 500).json({
    error: err.message || 'Internal Server Error'
  });
});

Middleware order matters. app.use(express.json()) must come before routes that read req.body. Error middleware must be registered after all routes. Forgetting next() in non-terminal middleware silently stalls the request.

Up next

Project folder structure for a scalable Express API

Sign in to track progress

Express middleware โ€” what it is and how to use it โ€” Building Your First API with Node.js and Express โ€” REST API Development: Beginner to Production โ€” Script Valley โ€” Script Valley