express-unless is a utility library for Express.js that enables conditional execution of middleware functions. It allows developers to attach an `unless` method directly to any Express middleware, providing granular control over when that middleware should be skipped. The library currently ships as version 2.1.3 and has seen stable releases, with the latest update in April 2021. It differentiates itself by offering a fluent API for defining skip conditions based on HTTP methods, request paths (including regular expressions and path/method pairs), file extensions, or a fully custom predicate function. This approach simplifies complex conditional routing logic often found in Express applications, providing a cleaner way to apply authentication, logging, or other cross-cutting concerns selectively.
npm install express-unlessVerified import paths — ran on the pinned version, not inferred.
This quickstart sets up an Express application demonstrating how to apply `unless` to an authentication middleware and a logging middleware, skipping them based on paths, methods, extensions, and custom functions.
Be aware that the middleware object itself is mutated. In TypeScript, cast the middleware to `any` or extend its interface if using `express.Request` and `express.Response` interfaces directly, e.g., `(myMiddleware as any).unless = unless;`.
Review the Express API documentation for `req.url` vs `req.originalUrl`. If your middleware is mounted at a subpath and you want conditions to apply relative to that subpath, explicitly set `useOriginalUrl: false` in your `unless` options.
Carefully consider the order of `app.use()` calls. Generally, apply `unless`-enhanced middleware before routers that might modify the request path properties. Test your conditional logic thoroughly across various routes.
Ensure that `mymid.unless = unless;` (or `(myMiddleware as any).unless = unless;` in TypeScript) is executed before attempting to call `mymid.unless(...)`. Verify `mymid` is a valid function.
Review the `unless` options: ensure `path` regular expressions are correct, `method` arrays include all intended methods, `ext` matches actual file extensions, and `custom` functions return the expected boolean value. Use `console.log` statements within a `custom` function to debug its return value and `req.originalUrl`/`req.url` values. Remember `unless` means 'skip if condition is met'.