middleware-if-unless is a Node.js library that provides conditional execution of connect-like middleware based on routing criteria. Inspired by the popular `express-unless` module, it aims for higher performance by leveraging `find-my-way` for advanced route matching capabilities. It allows developers to define rules for when a middleware should (`iff`) or should not (`unless`) be applied to an incoming request, supporting various matching criteria like methods, URLs, functions, and even `Accept-Version` headers. The package ships with TypeScript types, promoting better developer experience and type safety. Currently at version 1.6.0, it maintains an active release cadence, with recent updates focusing on performance optimizations and dependency updates.
npm install middleware-if-unlessVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates how to apply a custom Express-like middleware conditionally using `iff` and `unless` methods based on request paths and HTTP methods.
Upgrade your Node.js runtime to version 22.0.0 or newer. Consider using nvm or similar tools for managing Node.js versions.
Review `find-my-way` changelogs for breaking changes between versions. Ensure your route definitions and matching logic are compatible with the integrated `find-my-way` version. Test thoroughly after upgrading `middleware-if-unless`.
Always invoke the `require`d module immediately: `const iu = require('middleware-if-unless')();`. For ESM, use `import createIffUnless from 'middleware-if-unless';` and then `createIffUnless()`.Ensure your middleware is extended: `const extendedMiddleware = createIffUnless()(yourMiddleware);`. Then use `extendedMiddleware.iff(...)` or `extendedMiddleware.unless(...)`.
Make sure to pass your middleware function to the `createIffUnless()` factory function: `const createIffUnless = require('middleware-if-unless'); const iu = createIffUnless(); const extendedMiddleware = iu(myMiddleware);`For CommonJS projects, ensure you are using a version of Node.js that supports hybrid modules or consider migrating your project to ESM. If possible, ensure your `package.json` specifies `"type": "module"` for ESM, or use dynamic `import()` for CJS if the library is truly ESM-only.
Ensure the package is installed via `npm install middleware-if-unless` or `yarn add middleware-if-unless`. Check for typos in the import/require statement.