Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NestJS conditional module import

Is there a way to import a module conditionally? I want to check if the .env file exists, so I configure the env variables using the ConfigModule.

    imports: [
    UsersModule,
    ConfigModule.forRoot({ load: [configuration] }), //I want to use this just if the .env file exists
    MongooseModule.forRoot(
      `mongodb+srv://${process.env.DATABASE_USER}:${process.env.DATABASE_PASSWORD}@${process.env.DATABASE_URL}`,
    ),
  ],

Why: I deployed an api and configured the environment variables using heroku, and in production it works, but I dont have this variables to run the code in development, and I can't expose the .env in my public repository because this contains my database credentials. Because of this, I thinked to create a .env file and put it on .gitignore to don't publish with this file

like image 751
Thierry P. Oliveira Avatar asked Jun 13 '26 02:06

Thierry P. Oliveira


1 Answers

You can do this pretty easily with a spread and a ternary check on whatever condition you want. Just return an empty array in the case that the check evaluates to false and the module will not be included.

@Module({
  imports: [
   ...(isEnvPresent ? [ConfigModule.forRoot({ load: [configuration] })] : []),
   UsersModule,
  ],
})
like image 142
Jesse Carter Avatar answered Jun 15 '26 16:06

Jesse Carter