Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 43 ยท Middleware

Writing Your Own Middleware

Write your own Express middleware: a request ID, a response timer, an auth guard and configurable middleware factories, with async handling and testing tips.

Packages cover the common jobs, but the most valuable middleware in your app is the code only you need: attach the current user, stamp each request with an ID, enforce a business rule before a group of routes. Writing middleware is easy because you already know the whole contract from How Middleware Works: a function (req, res, next) that responds, calls next(), or passes an error.

In this lesson you will write four useful ones, then learn the factory pattern that makes middleware configurable. The real Express versions are read-only blocks; each idea also runs on our stand-in framework, which has the same (req, res, next) shape, so the middleware bodies are the same code you would write for real.

Anatomy of good middleware

One job Do a single thing and do it well.
One exit Respond, next(), or next(err). Never two.
Attach data Put results on req or res.locals.
Be configurable Return it from a factory function.
1 / 2

Request ID

A request ID ties together every log line from one request. If a user reports "my request failed at 14:03", an ID lets you find exactly that request. Read the incoming ID if a proxy already set one, otherwise create one, and send it back in the response:

JavaScript
import { randomUUID } from 'node:crypto';

export function requestId(req, res, next) {
  req.id = req.get('x-request-id') ?? randomUUID();
  res.set('X-Request-Id', req.id);
  next();
}

Because randomUUID() gives different text every run, the runnable version below uses a counter, so the output is predictable.

Node.js A request ID middleware

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Two generated IDs, then one reused from a proxy. In a large app you also pass this ID into your logger so every line carries it (Logging and Debugging).

Timing a response

Timing needs work before the handler and after the response. You cannot do the second part by running code after next(), because next() returns as soon as your handler has started (it may be async). Listen for the response finish event instead:

JavaScript
export function timer(req, res, next) {
  const start = performance.now();
  res.on('finish', () => {
    const ms = (performance.now() - start).toFixed(1);
    console.log(`${req.method} ${req.originalUrl} ${res.statusCode} ${ms}ms`);
  });
  next();
}

Putting the elapsed time into a header is trickier: headers are sent with the first byte, so you would have to hook the moment before they go out. The response-time package does that with the on-headers module; for logging, finish is enough.

Node.js Timing with the finish event

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The slow route is marked slow: true because the timer measured from before the handler to the end of the response, including the awaited delay.

An authentication guard

A guard checks credentials and either stops the request or attaches the user for later handlers. This one reads a Bearer token (real token handling is in JWT Authentication; here a lookup table stands in):

JavaScript
const sessions = new Map([['abc123', { id: 1, name: 'Ada', role: 'admin' }]]);

export function authenticate(req, res, next) {
  const header = req.get('authorization') ?? '';
  const token = header.startsWith('Bearer ') ? header.slice(7) : null;
  const user = token ? sessions.get(token) : null;
  if (!user) {
    return res.status(401).json({ error: 'Authentication required' });
  }
  req.user = user;
  next();
}

app.get('/profile', authenticate, (req, res) => res.json(req.user));

The two rules from earlier apply: return after responding, and call next() exactly once on success. Choose the status carefully: 401 means "I don't know who you are", while 403 means "I know who you are and you may not do this".

Middleware factories

The authenticate function above has its configuration baked in. When a function needs options, make a factory: a function that takes the options and returns the middleware. You have already used them: express.json({ limit: '1mb' }) and morgan('dev') both call a function to get a middleware.

JavaScript
export function requireRole(role) {
  return (req, res, next) => {
    if (req.user?.role !== role) {
      return res.status(403).json({ error: `Requires the ${role} role` });
    }
    next();
  };
}

app.get('/admin/stats', authenticate, requireRole('admin'), showStats);
app.get('/editor/drafts', authenticate, requireRole('editor'), showDrafts);

The inner function is a closure, so it remembers role. Note that you write requireRole('admin') with parentheses: forgetting them registers the factory itself as middleware, and Express would call it with (req, res, next) and treat req as the role. A telltale sign is that nothing works and no error mentions roles.

Node.js Guard plus a role factory

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Four calls show 401 (no token), 200 (valid user), 403 (wrong role) and 200 (admin). Splitting authentication from authorization like this lets you stack guards freely.

Async middleware

Middleware can be async. In Express 5 a rejected promise is forwarded to your error handler automatically, so you do not need a try/catch just to call next(err):

JavaScript
export async function loadUser(req, res, next) {
  req.user = await db.users.find(req.get('x-user-id'));
  next(); // still required to continue
}

In Express 4 you must catch the error yourself and call next(err), or the request hangs and the process may log an unhandled rejection. Our stand-in imitates Express 5 here. More in Error Handling.

Habits of reliable middleware

  • Never mutate shared state per request. Variables outside the function are shared by all requests; put per-request data on req or res.locals.
  • Name things. req.id and req.user are conventional; avoid clobbering built-ins like req.params or req.body.
  • Call next() once, and only if you did not respond.
  • Keep it fast. Middleware on every request is on your hot path; do slow work only on the routes that need it.
  • Test it alone. A middleware is a function, so you can call it with fake req, res and a next spy (see Testing Express Apps).

Share small middleware across routes by exporting them from a middleware/ folder and importing them where needed. Project Setup and Structure shows the layout.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does a timing middleware use res.on('finish') instead of running code after next()?

    Handlers can be asynchronous, so next() returns early. The finish event fires when the response has actually been sent.
  2. 2. What is a middleware factory?

    Factories like requireRole('admin') use a closure to remember their options and return the (req, res, next) function.
  3. 3. A user is logged in but lacks the admin role. Which status code fits best?

    403 means the server knows who you are but you are not allowed. 401 means authentication is missing or invalid.
  4. 4. You write app.get('/admin', authenticate, requireRole, handler) and every request fails strangely. What is the most likely mistake?

    A factory must be called, as in requireRole('admin'). Passing it uncalled registers the wrong function.

Summary

  • Middleware is a plain function: respond, call next(), or call next(err), exactly once.
  • Attach per-request data to req (or res.locals), never to shared variables.
  • Use res.on('finish') for work that needs the final status or timing.
  • Guards return early with 401 (not authenticated) or 403 (not allowed).
  • Factories return configured middleware through a closure; remember the parentheses.
  • Express 5 forwards rejected promises from async middleware to the error handler.

Next: The Request Object.