{"id":17802,"library":"middleware-if-unless","title":"Middleware if/unless","description":"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.","status":"active","version":"1.6.0","language":"javascript","source_language":"en","source_url":"https://github.com/BackendStack21/middleware-if-unless","tags":["javascript","middleware","if","unless","typescript"],"install":[{"cmd":"npm install middleware-if-unless","lang":"bash","label":"npm"},{"cmd":"yarn add middleware-if-unless","lang":"bash","label":"yarn"},{"cmd":"pnpm add middleware-if-unless","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Core routing engine used for advanced route matching in iff/unless criteria.","package":"find-my-way","optional":false}],"imports":[{"note":"The default export is a function that acts as a factory to extend middleware. It is often aliased to `iu` or similar.","wrong":"import { createIffUnless } from 'middleware-if-unless';","symbol":"createIffUnless","correct":"import createIffUnless from 'middleware-if-unless';"},{"note":"Import the type definition for a middleware extended with `iff` and `unless` methods. This is for TypeScript usage.","symbol":"IffUnlessMiddleware","correct":"import createIffUnless, { type IffUnlessMiddleware } from 'middleware-if-unless';"},{"note":"For CommonJS, the package exports a factory function that should be called immediately to get the middleware extender.","wrong":"const { iu } = require('middleware-if-unless');","symbol":"iu","correct":"const iu = require('middleware-if-unless')();"}],"quickstart":{"code":"import express from 'express';\nimport createIffUnless from 'middleware-if-unless';\n\nconst app = express();\n\ninterface CustomRequest extends express.Request {\n  body: string;\n}\n\nconst myMiddleware: express.RequestHandler = (req: CustomRequest, res, next) => {\n  req.body = 'hit';\n  console.log('Middleware executed!');\n  next();\n};\n\n// Extend the middleware with iff/unless capabilities\nconst extendedMiddleware = createIffUnless()(myMiddleware);\n\n// Use 'unless': middleware runs for all requests EXCEPT /not/allowed\napp.use(extendedMiddleware.unless([\n  '/not/allowed'\n]));\n\n// Use 'iff': middleware runs ONLY for POST/PUT/DELETE/PATCH to /tasks/:id\napp.use(extendedMiddleware.iff([\n  {\n    methods: ['POST', 'DELETE', 'PUT', 'PATCH'],\n    url: '/tasks/:id',\n  },\n]));\n\napp.get('/', (req: CustomRequest, res) => {\n  res.send(`Root path. Middleware response: ${req.body ?? 'not hit'}`);\n});\n\napp.get('/not/allowed', (req: CustomRequest, res) => {\n  res.send(`Not Allowed path. Middleware response: ${req.body ?? 'not hit'}`);\n});\n\napp.post('/tasks/123', (req: CustomRequest, res) => {\n  res.send(`Task create. Middleware response: ${req.body ?? 'not hit'}`);\n});\n\nconst PORT = process.env.PORT ?? 3000;\napp.listen(PORT, () => {\n  console.log(`Server listening on port ${PORT}`);\n  console.log('Try:');\n  console.log(`- GET http://localhost:${PORT}/ (should show 'hit')`);\n  console.log(`- GET http://localhost:${PORT}/not/allowed (should show 'not hit')`);\n  console.log(`- POST http://localhost:${PORT}/tasks/123 (should show 'hit')`);\n});\n","lang":"typescript","description":"This quickstart demonstrates how to apply a custom Express-like middleware conditionally using `iff` and `unless` methods based on request paths and HTTP methods."},"warnings":[{"fix":"Upgrade your Node.js runtime to version 22.0.0 or newer. Consider using nvm or similar tools for managing Node.js versions.","message":"Node.js engine requirement has been updated to `>=22.0.0`. Older Node.js versions are no longer supported, requiring environment upgrades.","severity":"breaking","affected_versions":">=1.6.0"},{"fix":"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`.","message":"The underlying `find-my-way` router dependency has undergone significant major version upgrades (e.g., to v5.x and then v7+ in `middleware-if-unless` v1.3.0 and v1.4.0 respectively). While `middleware-if-unless` aims for backward compatibility, direct usage or assumptions about `find-my-way`'s internal behavior might be affected by its breaking changes.","severity":"breaking","affected_versions":">=1.3.0"},{"fix":"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()`.","message":"The package provides a factory function as its default export. For CommonJS, `require('middleware-if-unless')()` is needed to get the middleware extender. Directly `require('middleware-if-unless')` without calling it will result in an uncallable function or object without `iff` and `unless` methods.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Ensure your middleware is extended: `const extendedMiddleware = createIffUnless()(yourMiddleware);`. Then use `extendedMiddleware.iff(...)` or `extendedMiddleware.unless(...)`.","message":"The `iff` and `unless` methods are added *to* your middleware function. You must pass your middleware function to the `createIffUnless()` factory function to enable these methods. Attempting to call `iff` or `unless` on an un-extended middleware will result in a TypeError.","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":"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);`","cause":"The `unless` (or `iff`) method was called on a middleware that has not been extended by the `middleware-if-unless` factory.","error":"TypeError: extendedMiddleware.unless is not a function"},{"fix":"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.","cause":"Attempting to `require()` an ESM-only version of the package in a CommonJS context without proper configuration, or when Node.js is forcing ESM interpretation.","error":"Error [ERR_REQUIRE_ESM]: require() of ES Module .../node_modules/middleware-if-unless/dist/index.js from ... not supported."},{"fix":"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.","cause":"The package is not installed or the import/require path is incorrect.","error":"Error: Cannot find module 'middleware-if-unless'"}],"ecosystem":"npm","meta_description":null,"install_score":null,"install_tag":null,"quickstart_score":null,"quickstart_tag":null}