Middleware if/unless

raw JSON →
1.6.0 verified Thu Apr 23 auth: no javascript

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.

error TypeError: extendedMiddleware.unless is not a function
cause The `unless` (or `iff`) method was called on a middleware that has not been extended by the `middleware-if-unless` factory.
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);
error Error [ERR_REQUIRE_ESM]: require() of ES Module .../node_modules/middleware-if-unless/dist/index.js from ... not supported.
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.
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.
error Error: Cannot find module 'middleware-if-unless'
cause The package is not installed or the import/require path is incorrect.
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.
breaking Node.js engine requirement has been updated to `>=22.0.0`. Older Node.js versions are no longer supported, requiring environment upgrades.
fix Upgrade your Node.js runtime to version 22.0.0 or newer. Consider using nvm or similar tools for managing Node.js versions.
breaking 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.
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`.
gotcha 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.
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()`.
gotcha 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.
fix Ensure your middleware is extended: `const extendedMiddleware = createIffUnless()(yourMiddleware);`. Then use `extendedMiddleware.iff(...)` or `extendedMiddleware.unless(...)`.
npm install middleware-if-unless
yarn add middleware-if-unless
pnpm add middleware-if-unless

This quickstart demonstrates how to apply a custom Express-like middleware conditionally using `iff` and `unless` methods based on request paths and HTTP methods.

import express from 'express';
import createIffUnless from 'middleware-if-unless';

const app = express();

interface CustomRequest extends express.Request {
  body: string;
}

const myMiddleware: express.RequestHandler = (req: CustomRequest, res, next) => {
  req.body = 'hit';
  console.log('Middleware executed!');
  next();
};

// Extend the middleware with iff/unless capabilities
const extendedMiddleware = createIffUnless()(myMiddleware);

// Use 'unless': middleware runs for all requests EXCEPT /not/allowed
app.use(extendedMiddleware.unless([
  '/not/allowed'
]));

// Use 'iff': middleware runs ONLY for POST/PUT/DELETE/PATCH to /tasks/:id
app.use(extendedMiddleware.iff([
  {
    methods: ['POST', 'DELETE', 'PUT', 'PATCH'],
    url: '/tasks/:id',
  },
]));

app.get('/', (req: CustomRequest, res) => {
  res.send(`Root path. Middleware response: ${req.body ?? 'not hit'}`);
});

app.get('/not/allowed', (req: CustomRequest, res) => {
  res.send(`Not Allowed path. Middleware response: ${req.body ?? 'not hit'}`);
});

app.post('/tasks/123', (req: CustomRequest, res) => {
  res.send(`Task create. Middleware response: ${req.body ?? 'not hit'}`);
});

const PORT = process.env.PORT ?? 3000;
app.listen(PORT, () => {
  console.log(`Server listening on port ${PORT}`);
  console.log('Try:');
  console.log(`- GET http://localhost:${PORT}/ (should show 'hit')`);
  console.log(`- GET http://localhost:${PORT}/not/allowed (should show 'not hit')`);
  console.log(`- POST http://localhost:${PORT}/tasks/123 (should show 'hit')`);
});