{"id":17557,"library":"create-nestjs-middleware-module","title":"Configurable NestJS Middleware Module Creator","description":"create-nestjs-middleware-module is a lightweight utility library designed to simplify the integration and configuration of Express or Fastify middleware into NestJS applications. It abstracts away the boilerplate of implementing `NestModule` and `MiddlewareConsumer` by providing a `createModule` function, allowing developers to define middleware factories that can accept options. The library currently supports NestJS versions 8 through 11 and requires Node.js >=18.0.0. It aims to provide an idiomatic NestJS way to encapsulate middleware logic within a modular structure, enabling configuration via `forRoot` or `forRootAsync` methods, and offering fine-grained control over routing, similar to NestJS's built-in `MiddlewareConfigProxy`. Its current stable version is 0.4.0, with releases occurring as needed to maintain compatibility with new NestJS versions.","status":"active","version":"0.4.0","language":"javascript","source_language":"en","source_url":"https://github.com/iamolegga/create-nestjs-middleware-module","tags":["javascript","nest","nestjs","nest.js","middleware","config","configure","typescript"],"install":[{"cmd":"npm install create-nestjs-middleware-module","lang":"bash","label":"npm"},{"cmd":"yarn add create-nestjs-middleware-module","lang":"bash","label":"yarn"},{"cmd":"pnpm add create-nestjs-middleware-module","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Peer dependency required for core NestJS functionalities, including module creation and middleware interfaces.","package":"@nestjs/common","optional":false}],"imports":[{"note":"This is the primary function to create a configurable NestJS module from your middleware factory. Always use named import.","wrong":"const { createModule } = require('create-nestjs-middleware-module');","symbol":"createModule","correct":"import { createModule } from 'create-nestjs-middleware-module';"},{"note":"Use this type assertion to allow calling the `forRoot()` method without arguments for modules where options are not required, improving developer experience.","symbol":"FacadeModuleStaticOptional","correct":"import { createModule, FacadeModuleStaticOptional } from 'create-nestjs-middleware-module';"},{"note":"Type utility for defining synchronous module options for your created middleware module.","symbol":"SyncOptions","correct":"import { SyncOptions } from 'create-nestjs-middleware-module';"},{"note":"Type utility for defining asynchronous module options for your created middleware module, typically used with `forRootAsync`.","symbol":"AsyncOptions","correct":"import { AsyncOptions } from 'create-nestjs-middleware-module';"}],"quickstart":{"code":"import { Module, NestModule, MiddlewareConsumer, INestApplication } from '@nestjs/common';\nimport { NestFactory } from '@nestjs/core';\nimport { Request, Response, NextFunction } from 'express';\nimport { createModule, FacadeModuleStaticOptional } from 'create-nestjs-middleware-module';\n\n// 1. Define your middleware factory and its options\ninterface LoggerMiddlewareOptions {\n  prefix?: string;\n}\n\nfunction createCustomLoggerMiddleware(options?: LoggerMiddlewareOptions) {\n  const prefix = options?.prefix || 'APP';\n  return (req: Request, res: Response, next: NextFunction) => {\n    console.log(`[${prefix}] Request: ${req.method} ${req.url}`);\n    next();\n  };\n}\n\n// 2. Create your NestJS module using createModule\nexport const CustomLoggerModule = createModule<LoggerMiddlewareOptions>(\n  createCustomLoggerMiddleware\n) as FacadeModuleStaticOptional<LoggerMiddlewareOptions>;\n\n// 3. Use the module in your main application\n@Module({\n  imports: [\n    // Example: Configure with options\n    CustomLoggerModule.forRoot({\n      prefix: 'API',\n      forRoutes: ['/data*'] // Apply to routes starting with /data\n    }),\n    // Example: Use without options (requires FacadeModuleStaticOptional assertion)\n    CustomLoggerModule.forRoot(), // Apply to all routes by default\n  ],\n  controllers: [],\n  providers: [],\n})\nclass AppModule implements NestModule {\n  configure(consumer: MiddlewareConsumer) {\n    // Additional NestJS native middleware configuration if needed\n    // For instance, if you want to exclude specific paths from the CustomLoggerModule's default application\n    // consumer\n    //   .apply(SomeOtherMiddleware)\n    //   .exclude('/admin*')\n    //   .forRoutes('*');\n  }\n}\n\nasync function bootstrap() {\n  const app: INestApplication = await NestFactory.create(AppModule);\n  await app.listen(process.env.PORT || 3000);\n  console.log(`Application is running on: ${await app.getUrl()}`);\n}\n\n// To run this example, you would typically have an Express/Fastify adapter configured\n// and a controller responding to /data* or other routes.\nbootstrap();","lang":"typescript","description":"This quickstart demonstrates how to define a functional middleware with options, convert it into a configurable NestJS module using `createModule`, and then integrate it into a `AppModule` with both explicit options and default usage."},"warnings":[{"fix":"Upgrade your NestJS version to >=8.0.0 and your Node.js version to >=16.0.0. Consider updating your `package.json` `engines` and `@nestjs/common` peer dependency.","message":"Version 0.3.0 dropped support for NestJS versions older than 8 and Node.js versions older than 16. Ensure your project meets these minimum requirements before upgrading.","severity":"breaking","affected_versions":">=0.3.0"},{"fix":"Apply the `as FacadeModuleStaticOptional<YourOptionsInterface>` type assertion to the module created by `createModule` if you intend to allow `forRoot()` without any arguments.","message":"When using `createModule` with optional configurations, it's recommended to cast the result to `FacadeModuleStaticOptional<Options>` to allow calling `forRoot()` without arguments. Without this, TypeScript will require an empty object even if options are truly optional.","severity":"gotcha","affected_versions":">=0.2.0"},{"fix":"Test your custom middleware on the target platform (Express or Fastify). You might need to conditionally implement logic or create separate middleware factories for different platforms if incompatibilities arise.","message":"This library supports both Express and Fastify platforms; however, not all middleware created for one platform will inherently work with the other. Ensure your custom middleware functions are compatible with the NestJS platform adapter you are using.","severity":"gotcha","affected_versions":">=0.1.0"},{"fix":"Review your application's middleware order, especially if you have global middleware defined both natively and via `create-nestjs-middleware-module` in NestJS v11.","message":"NestJS v11 introduced changes to how middleware registered in global modules is executed, now always running first regardless of dependency graph position. While this library simplifies middleware creation, be aware of the overall middleware execution order in NestJS v11+ applications.","severity":"breaking","affected_versions":">=0.4.0"}],"env_vars":null,"last_verified":"2026-04-23T00:00:00.000Z","next_check":"2026-07-22T00:00:00.000Z","problems":[{"fix":"Ensure the module is correctly imported and that `createModule` has been called with the middleware factory. Double-check the import path `from 'create-nestjs-middleware-module'` and verify the export name of your custom module. If the error occurs when calling `forRoot()` without arguments, ensure `FacadeModuleStaticOptional` type assertion is used.","cause":"Attempting to call `.forRoot()` on the module created by `createModule` before it has been properly initialized or if the import path is incorrect.","error":"TypeError: Cannot read properties of undefined (reading 'forRoot')"},{"fix":"Ensure any services or providers required by your middleware factory are either provided directly within the `createModule`'s configuration (if supported by a future API), made available globally, or refactor your middleware to receive only configuration options directly.","cause":"Your middleware factory (passed to `createModule`) has dependencies that NestJS's DI container cannot resolve because the module isn't providing them or the dependencies aren't globally available.","error":"Error: Nest can't resolve dependencies of the XModule (?). Please make sure that the argument at index [0] is available in the XModule context."},{"fix":"Ensure your middleware factory function correctly accepts an `options` parameter of type `T` (or `void` if no options are expected) and returns either a single middleware function `(req, res, next) => void` or an array of such functions. Verify the `T` generic type argument passed to `createModule` matches your `Options` interface.","cause":"The middleware factory function passed to `createModule` does not match the expected signature (e.g., it expects options but is called without, or vice-versa, or the return type is incorrect).","error":"TS2345: Argument of type '(req: Request, res: Response, next: NextFunction) => void' is not assignable to parameter of type 'MiddlewareFactory<T>'."}],"ecosystem":"npm","meta_description":null,"install_score":null,"install_tag":null,"quickstart_score":null,"quickstart_tag":null}