Back to blog

2026-06-03 · 6 min read

Request Trust Middleware for Express.js: Integration Guide

How to add pre-handler request trust enforcement to Express.js routes for bot defense and abuse prevention.

Express middleware runs before route handlers

Express middleware functions receive req, res, and next. Calling next() passes control to the next middleware or route handler. Returning a response without calling next() terminates the request at the middleware layer.

Trust enforcement middleware should be mounted before route handlers for the paths being protected. For granular control, route-level middleware is more appropriate than app.use(), which applies to all routes.

IP resolution behind proxies

Express applications behind Nginx, AWS ALB, or Cloudflare need to read the client IP from X-Forwarded-For rather than req.socket.remoteAddress. The first IP in the XFF chain is the client; subsequent entries are proxy hops.

Validate that X-Forwarded-For is being set by a trusted proxy, not by the client itself. A client that can forge XFF can claim any IP address, undermining IP-based signals entirely.

Timeout handling in async middleware

Trust API calls are asynchronous. Wrap them in a Promise.race() against a timeout promise — typically 3-4 seconds — so a slow API response does not hold open Express connections indefinitely.

On timeout or network error, call next() to fail open. On ALLOW, call next(). On CHALLENGE, redirect to the challenge URL. On BLOCK, return res.status(403).send() with a minimal response body.