Reputation: 5103
I try to return my env variables in an express file but I get null
.
This is my folder structure
--backend
--.env
--src
--index.ts
--frontend
//.env
TEST: mytest
//index.ts
app.get("/api/test", (request, response) => {
response.send({test: [process.env.TEST]})
})
Upvotes: 0
Views: 263
Reputation: 5103
Fixed this by doing two things:
Firstly created .env
file by using the terminal. (see reference)
Then, I moved .env
file to the root
folder of my backend (removing it from src
)
Upvotes: 0
Reputation: 2670
Install https://www.npmjs.com/package/dotenv
Usage As early as possible in your application, require and configure dotenv.
require('dotenv').config()
// server.js
console.log(`Your port is ${process.env.PORT}`); // undefined
const dotenv = require('dotenv');
dotenv.config();
console.log(`Your port is ${process.env.PORT}`); // 8626
so in your case
/src/
index.ts
.env
You can also check for errors
const result = dotenv.config()
if (result.error) {
throw result.error
}
console.log(result.parsed)
Upvotes: 3
Reputation: 5411
.env
, it should be:TEST=mytest
.env
is not in the same folder as index.ts
file, you may need to provide the path to the .env
file.At the beginning of your index.ts
file :
require('dotenv').config({path : path.resolve(__dirname, '../.env')});
Upvotes: 1