# create-nestjs-middleware-module

> NestJS configured middleware module made simple

Latest version **0.5.0** (published 2026-08-31) · MIT license · 0 weekly downloads

## Install

```sh
npm install create-nestjs-middleware-module
pnpm add create-nestjs-middleware-module
yarn add create-nestjs-middleware-module
bun add create-nestjs-middleware-module
```

## Health

**Score 75/100 (B)** — status: active.

Positive: has types; esm support; no vulnerabilities; has provenance; recently updated; high maintenance score; high quality score.

Warnings: low downloads; pre 1.0.

## Facts

| | |
|---|---|
| Version | 0.5.0 |
| Published | 2026-08-31 |
| First published | 2019-10-29 |
| Weekly downloads | 0 |
| License | MIT |
| TypeScript types | bundled |
| Module format | ESM + CommonJS |
| Node | >=22.12.0 |
| Dependencies | 0 |
| Unpacked size | 25.1 KB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| Provenance | attested (GitHub Actions) |
| GitHub stars | 40 |
| Author | iamolegga |
| Maintainers | iamolegga |
| Keywords | nest, nestjs, nest.js, middleware, config, configure |

## Links

- npm: https://www.npmjs.com/package/create-nestjs-middleware-module
- Repository: https://github.com/iamolegga/create-nestjs-middleware-module
- Homepage: https://github.com/iamolegga/create-nestjs-middleware-module#readme
- Issues: https://github.com/iamolegga/create-nestjs-middleware-module/issues
- npm.io page: https://npm.io/package/create-nestjs-middleware-module

## Alternatives

- [jsforce](https://npm.io/package/jsforce.md) — 851.2K weekly downloads
- [react-native-qrcode-svg](https://npm.io/package/react-native-qrcode-svg.md) — 693.5K weekly downloads
- [@salesforce/plugin-data](https://npm.io/package/@salesforce/plugin-data.md) — 394.9K weekly downloads
- [@backstage/plugin-search-common](https://npm.io/package/@backstage/plugin-search-common.md) — 308.5K weekly downloads
- [@chain-registry/types](https://npm.io/package/@chain-registry/types.md) — 38.4K weekly downloads

## Recent versions

- 0.5.0 (latest) — 2026-08-31
- 0.5.0-alpha.beaf7f (alpha) — 2026-08-31
- 0.4.0-alpha.d891eb — 2026-08-31
- 0.4.0-alpha.0ef9c8 — 2025-01-24
- 0.4.0 — 2025-01-23
- 0.3.1-alpha.2dc35e — 2025-01-23
- 0.3.1-alpha.5636bd — 2025-01-23
- 0.3.1-alpha.79f3d6 — 2024-11-26
- 0.3.1 — 2023-08-17
- 0.3.0-alpha.3dd795 — 2023-08-17
- 0.3.0 — 2023-08-16
- 0.2.2-alpha.2b27d5 — 2023-08-16
- 0.2.2-alpha.62a949 — 2023-08-14
- 0.2.2-alpha.0b0f99 — 2023-08-09
- 0.2.2-alpha.a3f95d — 2023-08-07
- … 548 more at https://npm.io/package/create-nestjs-middleware-module/versions

## README

<h1 align="center">create-nestjs-middleware-module</h1>

<p align="center">
  <a href="https://www.npmjs.com/package/create-nestjs-middleware-module">
    <img alt="npm" src="https://img.shields.io/npm/v/create-nestjs-middleware-module" />
  </a>
  <a href="https://www.npmjs.com/package/create-nestjs-middleware-module">
    <img alt="npm" src="https://img.shields.io/npm/dm/create-nestjs-middleware-module" />
  </a>
  <a href="https://github.com/iamolegga/create-nestjs-middleware-module/actions">
    <img alt="GitHub branch checks state" src="https://badgen.net/github/checks/iamolegga/create-nestjs-middleware-module">
  </a>
  <a href="https://qlty.sh/gh/iamolegga/projects/create-nestjs-middleware-module">
    <img src="https://qlty.sh/gh/iamolegga/projects/create-nestjs-middleware-module/coverage.svg" alt="Code Coverage" />
  </a>
  <a href="https://snyk.io/test/github/iamolegga/create-nestjs-middleware-module">
    <img alt="Known Vulnerabilities" src="https://snyk.io/test/github/iamolegga/create-nestjs-middleware-module/badge.svg" />
  </a>
  <a href="https://libraries.io/npm/create-nestjs-middleware-module">
    <img alt="Libraries.io" src="https://img.shields.io/librariesio/release/npm/create-nestjs-middleware-module">
  </a>
  <img alt="Dependabot" src="https://badgen.net/github/dependabot/iamolegga/create-nestjs-middleware-module">
  <img alt="Supported platforms: Express & Fastify" src="https://img.shields.io/badge/platforms-Express%20%26%20Fastify-green" />
</p>

<p align="center">NestJS configured middleware module made simple</p>

## What is it?

It is a tiny helper library that helps you create simple _idiomatic_ **NestJS** module based on `Express`/`Fastify` middleware in just a few lines of code with routing out of the box.

---

<p align="center"><b>This is the documentation for v0.5. Compatibility with earlier versions:</b></p>

| create-nestjs-middleware-module | NestJS | Node.js |
| ------------------------------- | ------ | ------- |
| v0.5                            | 11.2+, 12 | >=22.12 |
| [v0.4](https://github.com/iamolegga/create-nestjs-middleware-module/tree/v0.4.0#readme) | 8, 9, 10, 11 | >=18 |

---

## Install

```sh
npm i create-nestjs-middleware-module
```

or

```sh
yarn add create-nestjs-middleware-module
```

## Usage

Let's imaging you have some middleware factory, for example, simple logger:

```ts
export interface Options {
  maxDuration: number
}

export function createResponseDurationLoggerMiddleware(opts: Options) {
  return (request, response, next) => {
    const start = Date.now();

    response.on('finish', () => {
      const message = `${request.method} ${request.path} - ${duration}ms`;

      const duration = Date.now() - start;

      if (duration > maxDuration) {
        console.warn(message);
      } else {
        console.log(message);
      }
    });

    next();
  };
}
```

And you want to create an idiomatic NestJS module based on that middleware. Just pass this middleware factory to `createModule` function:

```ts
import { createModule } from 'create-nestjs-middleware-module';
import { Options, createResponseDurationLoggerMiddleware } from './middleware';

export const TimingModule = createModule<Options>(createResponseDurationLoggerMiddleware);
```

That's it, your module is ready. Let's see what API it has:

```ts
import { TimingModule } from './timing-module';
import { MyController } from './my.controller';

@Module({
  imports: [

    // 1. `.forRoot()` method accept params satisfying `Options` interface
    TimingModule.forRoot({ maxDuration: 1000 }),

    // 2. `.forRoot()` method accept additional optional routing params
    TimingModule.forRoot({
      maxDuration: 1000,

      // both `forRoutes` and `exclude` properties are optional
      // and has the same API as NestJS buil-in `MiddlewareConfigProxy`
      // @see https://docs.nestjs.com/middleware#applying-middleware
      forRoutes: [MyController],
      exclude: [{ method: RequestMethod.ALL, path: 'always-fast' }],
    }),

    // 3. `.forRootAsync()` method with only factory
    TimingModule.forRootAsync({
      useFactory: async () => {
        return { maxDuration: 1000 }
      }
    }),

    // 4. `.forRootAsync()` method with dependencies
    TimingModule.forRootAsync({
      imports: [ConfigModule],
      inject: [ConfigService],
      useFactory: async (config: ConfigService) => {
        return { maxDuration: config.maxDurationForAPIHandler }
      }
    }),

    // 5. `.forRootAsync()` method with routing
    TimingModule.forRootAsync({
      imports: [ConfigModule],
      inject: [ConfigService],
      useFactory: async (config: ConfigService) => {
        return {
          maxDuration: config.maxDurationForAPIHandler

          // both `forRoutes` and `exclude` properties are optional
          // and has the same API as NestJS buil-in `MiddlewareConfigProxy`
          // @see https://docs.nestjs.com/middleware#applying-middleware
          forRoutes: [MyController],
          exclude: [{ method: RequestMethod.ALL, path: 'always-fast' }],
        };
      }
    }),
  ]
  controllers: [MyController /*, ... */]
})
class App {}
```

## More examples

See examples of usage in `__tests__` folder or [nestjs-session](https://github.com/iamolegga/nestjs-session/blob/master/src/index.ts) and [nestjs-cookie-session](https://github.com/iamolegga/nestjs-cookie-session/blob/master/src/index.ts) packages

## Notes

1. `createModule` callback function can return not only one middleware, but array of it.

```ts
import { createModule } from 'create-nestjs-middleware-module';


interface Options {
  // ...
}

createModule<Options>((options) => {
  function firstMidlleware() { /* ... */ }
  function secondMidlleware() { /* ... */ }
  return [firstMidlleware, secondMidlleware]
});
```

2. If your `Options` interface has not __required__ properties it can be frustrating to force end-users of your module to call `forRoot({})`, and for better developer expirience you can cast `createModule(...)` result to `FacadeModuleStaticOptional<Options>`, then `forRoot()` could be called without arguments and without TS error. In such case `createModule` callback function will be called with empty object `{}`.

```ts
import { createModule, FacadeModuleStaticOptional } from 'create-nestjs-middleware-module';

interface Options {
  maxDuration?: number;
}

createModule<Options>((options) => {
  typeof options // always "object" even if not passed to `forRoot()`

  return (request, response, next) => {
    // ...
    next();
  };
}) as FacadeModuleStaticOptional<Options>;
```

3. For better developer experience of end-users of your module you can also export interfaces of `forRoot` and `forRootAsync` argument:

```ts
import {
  AsyncOptions,
  SyncOptions,
} from 'create-nestjs-middleware-module';

interface Options {
  // ...
}

export type MyModuleOptions = SyncOptions<Options>;

export type MyModuleAsyncOptions = AsyncOptions<Options>;
```

4. This library is tested against `express` and `fastify`. But you should be aware that middlewares of `express` are not always work with `fastify` and vise versa. Sometimes you can check platforms internally. Sometimes maybe it's better to create 2 separate modules for each platform. It's up to you.

## Migration

### v0.5

NestJS 8, 9 and 10 are dropped: `@nestjs/common` and `@nestjs/core` are peer
dependencies with the range `^11.2.0 || ^12.0.0`, and Node.js >=22.12 is
required. The package is also published from `dist/` with an `exports` map
instead of copying the build output into the package root, so deep imports into
the package no longer resolve — import from the package root.

The default route changed from `*` to `{/*splat}`, which fixes the global
prefix root. With `app.setGlobalPrefix('v1')` and no explicit `forRoutes`, a
module built with this library behaved like this:

| request | before | after |
| -------------- | ----------------- | ---------- |
| `/v1` | **no middleware** | middleware |
| `/v1/anything` | middleware | middleware |

`path-to-regexp` v8, used by express@5 and @fastify/middie@9, no longer accepts
the unnamed `*` wildcard, so NestJS converted it into `/v1/{*path}` — a pattern
that matches everything under the prefix but not the prefix itself. Nothing
changes if the end-user passes their own `forRoutes`, or if no global prefix is
set; paths excluded from the global prefix keep the middleware as before.

<h2 align="center">Do you use this library?<br/>Don't be shy to give it a star! ★</h2>

<h3 align="center">Also if you are into NestJS you might be interested in one of my <a href="https://github.com/iamolegga#nestjs">other NestJS libs</a>.</h3>

---
_Source: https://npm.io/package/create-nestjs-middleware-module · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
