express-init

raw JSON →
1.1.2 verified Sat Apr 25 auth: no javascript maintenance

Express middleware initialization utility that allows middleware to perform asynchronous setup before the server starts. Version 1.1.2 supports Express 4.x. It calls a user-defined `init` function on each middleware serially before invoking a final callback. Unlike other async setup patterns (e.g., Promises), it uses callbacks and is tightly coupled to Express middleware structure. Maintenance is low; last release was several years ago. Differentiating factor: lightweight, no additional dependencies, and middleware-based initialization pattern.

error initialize is not a function
cause Using ES module import syntax on a CJS-only module.
fix
Use const initialize = require('express-init'); instead of import initialize from 'express-init';
error TypeError: middleware.init is not a function
cause Middleware attached to app does not have an `init` function defined.
fix
Add an init function to your middleware: middleware.init = function(app, callback) { ... }
error Callback must be a function
cause The second argument to initialize() is missing or not a function.
fix
Call initialize(app, function(err) { ... }) with a valid callback.
breaking Only supports Express 4.x. Not compatible with Express 3.x or 5.x.
fix Ensure your Express version is 4.x.
deprecated The package uses callback-based asynchronous pattern. Modern codebases prefer Promises or async/await.
fix Consider wrapping initialization in a Promise or using alternative libraries that support async/await.
gotcha Middleware init functions are called only once, even if the middleware is used multiple times in the same app.
fix Ensure that your init function does not rely on being called multiple times.
gotcha The library does not handle errors from init functions gracefully; throwing in init will crash the process.
fix Always call callback with an error if initialization fails; do not throw.
gotcha Works only with middleware that have an `init` function attached. Middleware without init are skipped silently.
fix Ensure your middleware explicitly defines an `init` method if async initialization is needed.
npm install express-init
yarn add express-init
pnpm add express-init

Demonstrates defining an Express middleware with an init function and using express-init to initialize all middleware before starting the server.

const express = require('express');
const initialize = require('express-init');

const app = express();

const myMiddleware = (req, res, next) => {
  console.log('Request received');
  next();
};
myMiddleware.init = (app, callback) => {
  // Simulate async init (e.g., DB connection)
  setTimeout(() => {
    console.log('Middleware initialized');
    callback();
  }, 100);
};

app.use(myMiddleware);
app.get('/', (req, res) => res.send('Hello'));

initialize(app, (err) => {
  if (err) throw err;
  app.listen(3000, () => console.log('Server started'));
});