Reputation: 15578
I am using nestjs for my nodejs project, and I want to load the .env
file from outside of the project.
Here is the directory structure
.env
services
/nodejs
/my-apis
/src
/main.ts
and in my main.ts
import * as dotenv from "dotenv";
dotenv.config({ path: `../../../../.env` });
console.log("process.env.PORT", process.env.PORT);
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.setGlobalPrefix("/api");
await app.listen(process.env.PORT);
}
but it is not getting the values from .env
, what can be the issue?
Upvotes: 1
Views: 2783
Reputation: 15578
I was loading the env
file in main.ts
. My app.module.ts
was using some env variable to initialize Mongo.
So In my app.module.ts
env variable was undefined. So I loaded the env
in app.module.ts
instead of main.ts
Also I used __dir_name
for path
import * as dotenv from "dotenv";
dotenv.config({ path: `${__dirname}/../../../../.env` });
and this worked.
Upvotes: 0
Reputation: 56
https://stackoverflow.com/a/42335383/10562569
require('dotenv').config({path:__dirname+'/./../../.env'})
This might help. Customize it to your need.
Upvotes: 1