Rajib Dey
Rajib Dey

Reputation: 45

NestJS HTTP Module needs to be imported in every feature module

In nestjs the http module needs to be imported into every feature module. Is there any way to import the http module only once throughout the full application?

Although in all the feature modules the http configurations are the same, why do we need to import and configure in each one.

Thanks.

Upvotes: 3

Views: 3288

Answers (3)

Nate May
Nate May

Reputation: 4062

The HttpModule has a static register method which receives a configuration object with exactly 1 option { global: true }

Just import it into your root model like this.

@Module({
  imports: [
    HttpModule.register({ global: true }),
  ],
  // ... controllers & providers
})

BONUS:

The ConfigModule similarly has a forRoot static method and a isGlobal config option

Upvotes: 0

German Velazquez
German Velazquez

Reputation: 51

If you don't want to create a wrapper module, you can also:

@Module({
  imports: [
    {
      ...HttpModule.register(httpModuleOptions),
      global: true
    }
  ],
})
export class AppModule {}

Upvotes: 5

Jay McDoniel
Jay McDoniel

Reputation: 70450

You could make a global module that imports it and exports it like so:

@Global()
@Module({
  imports: [HttpModule.register(httpModuleOptions)],
  exports: [HttpModule],
})
export class GlobalHttpModule {}

Now import it in the AppModule and you can use HttpService anywhere

Upvotes: 13

Related Questions