Advertisement
Advanced Node.js, Express & Middleware

How would you implement conditional middleware in Express that only applies to certain requests based on a runtime condition?

Short answer

Conditional middleware wraps the actual middleware logic in a function that checks a condition (a header, a feature flag, a specific route pattern) and either calls the wrapped middleware or simply calls next() directly to skip it -- useful for applying expensive or…

Save Node.js mock interview
Advertisement
AModel answer
Conditional middleware wraps the actual middleware logic in a function that checks a condition (a header, a feature flag, a specific route pattern) and either calls the wrapped middleware or simply calls next() directly to skip it -- useful for applying expensive or environment-specific middleware (like detailed request logging) only when actually needed, rather than unconditionally on every single request.
function conditionalMiddleware(condition, middleware) {
  return (req, res, next) => condition(req) ? middleware(req, res, next) : next();
}

app.use(conditionalMiddleware(
  (req) => req.headers['x-debug'] === 'true',
  detailedLoggingMiddleware
));
Real-world example
An API applies its expensive, verbose request/response logging middleware only when a request includes a specific debug header, avoiding the overhead of detailed logging for the vast majority of normal production traffic while still allowing engineers to opt into detailed diagnostics for a specific troubleshooting session.
Likely follow-ups
  • What's the performance consideration of checking a condition on every single request versus only conditionally registering middleware at startup?
  • How would you apply this same conditional pattern to enable a feature flag-gated middleware?
Related topics