condition-middleware is an Express.js middleware utility that enables conditional execution of other middleware functions based on a runtime predicate. It allows developers to define complex branching logic within their Express route definitions, executing different middleware stacks depending on a boolean, numeric, or string-based condition evaluated against the request object. This approach streamlines the creation of dynamic request processing flows, avoiding cumbersome `if/else` statements directly in route handlers. The package currently stands at version 1.1.0 and ships with TypeScript types, facilitating its use in modern JavaScript and TypeScript projects. While a formal release cadence isn't specified, its current version indicates active maintenance. Its key differentiator is simplifying the composition of conditional middleware, which is a common pattern for authentication, authorization, or feature toggling, compared to manual conditional chaining or other more complex conditional middleware solutions.
npm install condition-middlewareVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates how to use `condition-middleware` to execute different Express middleware chains based on a dynamic boolean condition, such as a user's role extracted from request headers.
Place global or route-specific error-handling middleware after the `condition` block in the Express middleware chain.
Ensure that your condition function's return values explicitly map to keys in the middleware object, or provide a default fallback mechanism in your logic.
Use `import condition from 'condition-middleware';` for ESM. If using CommonJS, ensure your build system correctly transpiles or configure `module.exports = require('./dist/index').default;` in a wrapper.Ensure that any objects or properties accessed in your condition function (e.g., `req.user`) are properly initialized by preceding middlewares, or add null/undefined checks in your condition logic.