I’m creating a NestJs Application and I’ve 2 env files, named
.local.env
& .development.env
In local setting the variable from npm run start:dev
and the start:dev
looks like this "start:dev": "NODE_ENV=dev nest start --watch",
Now while importing the file i’m using the below snippet to load the specific file in local,
import { ApolloDriver, ApolloDriverConfig } from "@nestjs/apollo";
import { TypeOrmModule } from "@nestjs/typeorm";
import { GraphQLModule } from "@nestjs/graphql";
import { CONSTANTS } from "../../../CONSTANTS";
import { ConfigModule } from "@nestjs/config";
import { databaseProviders } from "src/typeorm.config";
import { moduleIndex } from "./modules.index";
import { User } from "../graphQL/Users/users.entity";
let region: string = CONSTANTS.DEVELOPMENT_REGION;
if (process.env.NODE_ENV.toLowerCase() === CONSTANTS.DEVELOPMENT_REGION) {
region = "development"
} else if (process.env.NODE_ENV.toLowerCase() === CONSTANTS.DEVELOPMENT_LOCAL_REGION) {
region = "local"
} else if (process.env.NODE_ENV.toLowerCase() === CONSTANTS.DEVELOPMENT_STAGE_REGION) {
region = "stage"
} else if (process.env.NODE_ENV.toLowerCase() === CONSTANTS.DEVELOPMENT_PROD_REGION) {
region = "prod"
}
console.log("Region: ", region);
const importsArray = [
GraphQLModule.forRoot<ApolloDriverConfig>({
driver: ApolloDriver,
autoSchemaFile: CONSTANTS.SCHEMA_FILE_PATH
}),
ConfigModule.forRoot({
envFilePath: `.${region}.env`,
isGlobal: true,
}),
TypeOrmModule.forRootAsync(databaseProviders),
TypeOrmModule.forFeature([User])
]
const expArray = [...importsArray, ...moduleIndex];
export default expArray;
This configuration works prettymuch well in local, but when I build the project in Amazon Linux and run it using pm2 it’s not reading the NODE_ENV
variable, neither the file itself.
I’m using ConfigService
for reading env variables. like below,
import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
@Injectable()
export class AppConfig {
static service: ConfigService;
constructor(service: ConfigService) {
AppConfig.service = service;
}
static get(key: string): any {
return AppConfig.service.get(key);
}
}
Use,
import { AppConfig } from '../app.config';
and using it like AppConfig.get('JWT_SECRET')
.
Can anyone please suggest me how can I handle .env issue on ec2.
Thanks in advance.