#1 India's Top IT Training Institute
×

About Uncodemy

Know more about who we are and what we stand for.

About Us

About Us

Discover our mission to equip individuals with essential IT skills and industry expertise.

Read More →
UnCodeMy Gallery

UnCodeMy Gallery

Explore highlights from our IT training sessions and success stories.

Read More →
Mentors

Mentors

Meet the industry experts who train and guide you through your course.

Read More →
Free Resources

Free Resources

Free tutorials, interview questions, tools and calculators to help you learn.

Explore →
×

Free Resources

Learn, practice and plan your career — bilkul free.

Tutorials

Tutorials

Step-by-step written tutorials to learn any technology at your own pace.

Read More →
Free Counselling

Free Counselling

Book a free video counselling session and pick the right course for you.

Read More →
Online Compiler

Online Compiler

Write, run and test your code online — no setup required.

Read More →
Express - Advanced Topics

Creating Custom Middleware

Middleware in Express is a function that sits between an incoming request and the final route handler. Custom middleware is middleware you write yourself to handle a concern shared by many routes, such as logging, checking a login token, timing requests or rejecting malformed input. Instead of copying the same lines into every handler, you write them once and plug them in where needed.

The shape of a middleware function

A middleware function receives three arguments: req, res and next. It can read or change the request and response objects. When it is done, it must either send a response or call next() to pass control to the next function in line. Express runs middleware in the exact order you register it.

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

// 1. Logs method, path and how long the request took
function requestTimer(req, res, next) {
  const start = Date.now();
  res.on('finish', () => {
    const ms = Date.now() - start;
    console.log(`${req.method} ${req.originalUrl} ${res.statusCode} - ${ms}ms`);
  });
  next();
}

// 2. A middleware factory: returns middleware configured by its argument
function requireRole(role) {
  return (req, res, next) => {
    if (req.user?.role !== role) {
      return res.status(403).json({ error: 'Forbidden' });
    }
    next();
  };
}

app.use(requestTimer);               // every request
app.use(express.json());

app.delete('/api/users/:id', requireRole('admin'), (req, res) => {
  res.status(204).end();
});

Where you can attach it

  • Application level: app.use(fn) runs for every request. Add a path, as in app.use('/api', fn), to limit it to URLs beginning with that prefix.
  • Route level: pass one or more functions before the handler, as with requireRole('admin') above.
  • Router level: call router.use(fn) on an express.Router() so it applies only to that group of routes.

Order is not just a detail. A logger registered after the routes never sees requests the routes have already answered, and an authentication check placed after express.static() cannot protect the static files. Register general middleware, such as parsers and loggers, first, then authentication, then routes, and finally the error handler.

Sharing data with later handlers

Middleware often attaches information to req for code further down the chain. Authentication middleware might set req.user, and a request ID middleware might set req.id. For values meant only for rendering, res.locals is the conventional place.

Error-handling middleware

A middleware with four parameters, (err, req, res, next), is treated as an error handler. Express skips it during normal flow and jumps to it when any earlier function calls next(err) or throws synchronously. Register it last, after all routes.

In Express 4, an error thrown inside an async handler is not caught automatically. Wrap the body in try/catch and call next(err), or the request will hang and Node will report an unhandled rejection.

A minimal error handler logs the error and sends a generic message, for example res.status(err.status || 500).json({ error: 'Something went wrong' }). Avoid sending the raw error stack to clients in production, since it can reveal file paths and internal details.

The hanging request mistake

If middleware neither sends a response nor calls next(), the browser waits until it times out. This usually happens in an if branch that forgot one of them. The opposite mistake is calling next() after sending a response, which leads to the error "Cannot set headers after they are sent to the client". Using return res.status(...) when you reply early prevents both.

Takeaway

Every middleware ends by responding or calling next(). Order matters, factories let you configure middleware, and the four-argument version belongs at the end to catch errors.

Ready to master real-world web development?

Learn HTML, CSS3, Bootstrap and JavaScript hands-on with mentor-led sessions.

Explore Course