Im trying to use 3 different file,
.env, using PORT=80
.env.staging, using PORT=8080
.env.dev, using PORT=3030
my server.js is as such
import express from 'express';
import mongoose from 'mongoose';
import cors from 'cors';
import dotenv from 'dotenv';
const nodeEnv = process.env.NODE_ENV || 'development';
dotenv.config({ path: `.env.${nodeEnv}` });
console.log(`Loaded environment variables for ${process.env.NODE_ENV}:`);
const { PORT } = process.env;
mongoose.connect(MONGO_URL)
.then(() => {
console.log('Connected to MongoDB');
app.listen(PORT, '0.0.0.0', () => {
console.log(`Server is running on port ${PORT}`);
});
})
.catch((error) => {
console.error('Error connecting to MongoDB:', error);
});
and my package.json
"scripts": {
"start-prod": "NODE_ENV=production node server.js",
"start-staging": "NODE_ENV=staging node server.js",
"start-dev": "NODE_ENV=dev node server.js"
},
Whatever the start I do, the first console.log return dev, staging or prod, but the 2nd console log for PORT will always return 80 (value for PORT in .env)
So it’s always .env that is taken into account.
I tried at least 10 different combinations found on stack overflow. After some test if I change .env for .env.prod for exemple everything break because no environnement variable is taken into account which makes me think that the .env.staging and .env.dev are just not existent when I run them on the terminal.
Another strange point, I’m coding on VS code and
.env has dark blue const name and white value,
.env.staging / .env.dev had light blue or yellow const name and orange values.
If anyone has a solution it would help a lot.
Thank you