Search code examples
node.jsnestjsmiddleware

exporting nest js middleware to another project


I'm trying to export a custom middleware project in NestJS to all my other projects(and import this in all of them). My actual class is acl-jwt.middleware.ts in its bootstrap src folder.

In the acl-jwt.middleware.ts I have:

import { Injectable, NestMiddleware,  } from '@nestjs/common';

@Injectable()
export class AclJwtMiddleware implements NestMiddleware {
  use(req: any, res: any, next: () => void) {
    console.log("ACL JWT Middleware !!")
    next();
  }
}

and my app.module.ts has:

import { Module, NestModule, MiddlewareConsumer, RequestMethod } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { AclJwtMiddleware } from './acl-jwt.middleware';

@Module({
  imports: [],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer.apply(AclJwtMiddleware).forRoutes({ path: '*', method: RequestMethod.ALL });
  }
}

And in my another project's app.module.ts, I'm importing this like the following

import { AclJwtMiddleware } from 'mi';

@Module({
  imports: [],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer.apply(AclJwtMiddleware).forRoutes({ path: '*', method: RequestMethod.ALL });
  }
}

mi is my hosted package.

And then when I run my second project, I get the following error:

src/app.module.ts:16:34 - error TS2307: Cannot find module 'mi' or its corresponding type declarations.

16 import { AclJwtMiddleware } from 'mi';

Am I not exporting something? Or am I not importing it properly?

I've been searching all over the internet but I couldn't find something with my use case. Any help would be really good. Thank you all! :)


Solution

  • You'd need to make sure that in your package.json of your mi package, you have either main or files that points to the properly exported file/directory. If it is a barrel file, like index.js, then you need to make sure it exports the middleware properly.