Dynamic Middleware

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

dynamic-middleware is a utility library for Connect and Express applications that enables runtime replacement or disabling of middleware. It addresses the common difficulty of altering middleware after an HTTP server has started, a feature not natively supported by Connect or Express. The current stable version is 4.0.4. The library's release cadence is not specified but it has undergone significant architectural changes between major versions. It differentiates itself by providing a `create` method to wrap existing middleware, allowing for dynamic control over its execution via `enable()`, `disable()`, and `replace()` methods, specifically for `app.use()` and `app.get()` style middleware, which was improved in `4.x.x` to handle routes more effectively.

error TypeError: dynamic_middleware_1.default is not a function
cause Attempting to use ESM `import DynamicMiddleware from 'dynamic-middleware'` when the module is CommonJS and exports an object directly (not a default export).
fix
Use CommonJS const DynamicMiddleware = require('dynamic-middleware') to import the module correctly.
error TypeError: Cannot read properties of undefined (reading 'create')
cause This typically occurs when trying to access `create` on an undefined or incorrectly imported `DynamicMiddleware` object, often due to incorrect CommonJS vs. ESM import syntax.
fix
Ensure the module is imported with const DynamicMiddleware = require('dynamic-middleware') and that DynamicMiddleware is not null or undefined before calling .create().
error Middleware not affecting routes (e.g., app.get('/')) as expected, only app.use()
cause This behavior was characteristic of `dynamic-middleware` versions `3.x.x` and earlier due to how they manipulated Express/Connect's internal state, which was less effective for route-specific handlers.
fix
Upgrade to dynamic-middleware version 4.x.x or later, which has an improved internal state management system specifically designed to work correctly with route-specific middleware. Remember to update your code to the new API if upgrading from a 3.x.x version.
error TypeError: dm.handler is not a function
cause Trying to pass the `dynamic-middleware` instance (`dm`) directly to `app.get()` or `app.use()` instead of its `.handler()` method.
fix
Ensure you call .handler() on the DynamicMiddleware instance when integrating it into the Express/Connect application: app.get('/', dm.handler()). For error middleware, use .errorHandler().
breaking From `3.x.x` to `4.x.x`, the internal mechanism for managing middleware changed significantly. Older versions directly manipulated Express/Connect's internal state, which caused issues with route-specific middleware (`.get()`, `.post()`). Version `4.x.x` manages state internally, providing more robust handling for all middleware types.
fix Upgrade to `dynamic-middleware` version `4.x.x` or later. This will likely require adjusting your code to the new public API.
breaking The public interface of `dynamic-middleware` changed completely in `4.x.x`. Code written for `3.x.x` and earlier will require updates to adapt to the new API.
fix Review the `4.x.x` usage examples and documentation to refactor existing code. Key methods like `create` and the use of `.handler()` or `.errorHandler()` are central to the new API.
gotcha The provided examples and package structure strongly suggest `dynamic-middleware` is primarily a CommonJS module. Using ES module `import` syntax might lead to compatibility issues or require specific Node.js configuration for CJS interop, especially for older Node versions or without a transpilation step.
fix For Node.js environments, use the CommonJS `require()` syntax: `const DynamicMiddleware = require('dynamic-middleware')`. If ESM is strictly required, investigate tools like `rollup` or `webpack` for bundling, or Node.js's CJS-ESM interoperability features if supported by your Node.js version.
gotcha The library explicitly states compatibility with `express 3`, `express 4`, and `connect 3`. While it might work with newer versions of Express (e.g., Express 5), official compatibility is not guaranteed beyond these stated versions. Newer Express versions might introduce breaking changes that affect `dynamic-middleware`'s internal mechanisms.
fix Test thoroughly if using with Express versions newer than 4. If issues arise, consider pinning to an older Express version or exploring alternative solutions for dynamic middleware management in newer Express versions.
npm install dynamic-middleware
yarn add dynamic-middleware
pnpm add dynamic-middleware

This example demonstrates how to create, replace, and integrate dynamic middleware into an Express application, including a dynamic error handler.

const DynamicMiddleware = require('dynamic-middleware')
const express = require('express')

const app = express()

// a simple middleware
function myMiddleware(req, res, next) {
    res.end('1')
}

// create a dynamic one from it
let dm = DynamicMiddleware.create(myMiddleware)

app.get('/', dm.handler()) 

// disable the middleware, will reply with 404 now
// dm.disable()

// enable it back
// dm.enable()

// or replace it with something else
dm = dm.replace(function(req, res, next) {
    res.end('2')
})

// create a dynamic error middlware
let errorDm = DynamicMiddleware.create((err, req, res, next) => {
  console.error(err);
  res.status(500).send('Error: ' + err.message);
})

app.use(errorDm.errorHandler())

app.listen(3000, () => {
  console.log('Server running on port 3000');
});