I am trying to use the dotenv
NPM package and it is not working for me. I have a file config/config.js
with the following content:
I had the same problem. I had created a file named .env, but in reality the file ended up being .env.txt.
I created a new file, saved it in form of 'No Extension' and boom, the file was real .env and worked perfectly.
For React apps created with the create-react-app
template, you don't need to use dotenv
directly. react-scripts
does that for you.
Simply creates a .env
file in the top level directory of your project and add all your envs there, but notice that they MUST start with REACT_APP
prefix, otherwise they will be ignored.
More details in their documentation. I just spent a couple of hours dealing with this and hope it will save you some time.
I solved this just renaming the file to .env to y file was named config.env , when I renamed to .env , it works.
I spent a lot of time going through these fixes. I was developing locally and just had to restart the server because the .env file isn't hot reloaded.
My problem was stupid. I created the .env in a text editor, and when I saved it it actually saved as
'.env.txt'
which was only visible after I did a
'ls -a'
in terminal and saw the file name.
A quick:
mv .env.txt .env
And I was in business
If you are facing this problem it could be that the environment variable(s) is added/loaded after the file that requires the specific variable
const express = require('express');
const app = express();
const mongoose = require('mongoose');
const dotenv = require('dotenv');
const morgan = require('morgan');
const passport = require('passport'); //you want to use process.env.JWT_SECRET (you will get undefined)
dotenv.config();
in the above case, you will get undefined
for the process.env.JWT_SECRET
So the solution is that you put dotenv.config()
before const passport = require('passport');
const express = require('express');
const app = express();
const mongoose = require('mongoose');
const dotenv = require('dotenv');
const morgan = require('morgan');
dotenv.config();
const passport = require('passport'); //you want to use process.env.JWT_SECRET (you will get the value for the enviroment variable)