{"id":17542,"library":"condition-middleware","title":"Conditional Express Middleware","description":"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.","status":"active","version":"1.1.0","language":"javascript","source_language":"en","source_url":"ssh://git@github.com/cenietob/conditional-middleware","tags":["javascript","express","middleware","conditional","typescript"],"install":[{"cmd":"npm install condition-middleware","lang":"bash","label":"npm"},{"cmd":"yarn add condition-middleware","lang":"bash","label":"yarn"},{"cmd":"pnpm add condition-middleware","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"This package is an Express.js middleware and requires an Express application context to function. It is typically a peer dependency.","package":"express","optional":false}],"imports":[{"note":"The library primarily uses ES module syntax for its default export. While CommonJS might work in some transpiled environments, native ESM is the intended usage. Ships with TypeScript types.","wrong":"const condition = require('condition-middleware');","symbol":"condition","correct":"import condition from 'condition-middleware';"},{"note":"Type import for advanced TypeScript usage, though the primary export is a function.","symbol":"ConditionMiddlewareFunction","correct":"import type { ConditionMiddlewareFunction } from 'condition-middleware';"}],"quickstart":{"code":"import express from 'express';\nimport condition from 'condition-middleware';\n\n// Dummy middleware functions for demonstration\nconst initialMiddleware = (req, res, next) => { console.log('Initial'); req.user = { role: 'guest' }; next(); };\nconst validateRequestAdmin = (req, res, next) => { console.log('Validating admin request'); next(); };\nconst otherMiddlewareAdmin = (req, res, next) => { console.log('Admin specific logic'); next(); };\nconst validateRequestOthers = (req, res, next) => { console.log('Validating other request'); next(); };\nconst otherMiddlewares = (req, res, next) => { console.log('Common middleware after condition'); next(); };\nconst finalMiddleware = (req, res, next) => { console.log('Final middleware'); res.send('Done!'); };\nconst errorMiddleware = (err, req, res, next) => { console.error('Error:', err.message); res.status(500).send('Server Error'); };\n\nconst app = express();\n\n// Condition function that returns a boolean\nconst isAdmin = (req) => {\n    // Simulate different roles for demonstration\n    const userRole = req.headers['x-user-role'] || 'guest';\n    req.user.role = userRole;\n    console.log(`User role: ${req.user.role}`);\n    return req.user.role === 'admin';\n};\n\napp.get(\n    '/',\n    initialMiddleware,\n    condition(isAdmin)(\n        [validateRequestAdmin, otherMiddlewareAdmin], // true path\n        [validateRequestOthers] // false path\n    ),\n    otherMiddlewares,\n    finalMiddleware,\n    errorMiddleware\n);\n\napp.listen(3000, () => {\n    console.log('Server running on http://localhost:3000');\n    console.log('Test with:');\n    console.log('curl http://localhost:3000 -H \"x-user-role: admin\"');\n    console.log('curl http://localhost:3000');\n});\n","lang":"typescript","description":"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."},"warnings":[{"fix":"Place global or route-specific error-handling middleware after the `condition` block in the Express middleware chain.","message":"Error-handling middlewares are not directly accepted inside a condition middleware chain. Standard error handling should occur outside the `condition` block.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"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.","message":"When using the object-based condition syntax, if the value returned by your condition function does not match any key in the provided object, no middleware within the conditional block will be executed.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-23T00:00:00.000Z","next_check":"2026-07-22T00:00:00.000Z","problems":[{"fix":"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.","cause":"Attempting to import the default ESM export using CommonJS `require` syntax, or incorrect named import.","error":"TypeError: condition is not a function"},{"fix":"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.","cause":"The condition function or a middleware inside the conditional block is attempting to access a property (e.g., `req.user.role`) that has not been initialized or is `undefined` on the `req` object.","error":"Cannot read properties of undefined (reading 'role')"}],"ecosystem":"npm","meta_description":null,"install_score":null,"install_tag":null,"quickstart_score":null,"quickstart_tag":null}