How to Create and Use .env File in Node JS and React JS?
- Create Node App:
mkdir my-request-app
cd my-request-app
npm init
2. Install dotenv:
npm install dotenv
3. Create .env file
touch .env//at .env
API_URL="http://localhost:8002"
4. server.js
const dotenv = require('dotenv');
dotenv.config();console.log(`Your App Name is ${process.env.APP_NAME}`);
console.log(`Your App Environment is ${process.env.APP_ENV}`);
console.log(`Your App Port is ${process.env.API_URL}`);
5. Run App:
node server.js
In Reactjs:
- No need to install any package.
- Create following Environment file:
.env
: Default..env.local
: Local overrides. This file is loaded for all environments except test..env.development
,.env.test
,.env.production
: Environment-specific settings..env.development.local
,.env.test.local
,.env.production.local
: Local overrides of environment-specific settings.
3. Add configuration content:
.env.development
REACT_APP_API_URL=http://localhost:8002
.env.production
REACT_APP_API_URL=http://piyas.com/api
N.B: The only important thing is to use REACT_APP_ as a prefix for each environment variable.
4. Edit package.json
"scripts": {"start:dev": "NODE_ENV=development nodemon server.js","test": "echo \"Error: no test specified\" && exit 1"},
5. Run:
npm start:devHow to read variables values in js files ?
===
console.log(process.env.NODE_ENV) //which mode(default)
console.log(process.env.REACT_APP_API_URL)
In Nextjs:
Environment Variables of Next JS:
- Create
.env
(all environments),.env.development
(development environment), and.env.production
(production environment).
.env.local
always overrides the defaults set.
2. Add the prefix NEXT_PUBLIC to all of your environment variables.
NEXT_PUBLIC_API_URL=http://localhost:3000/
3. Use with prefix process.env
process.env.NEXT_PUBLIC_API_URL
4. Stop the server and restart it:
npm run dev
Important Notes
1- Don't forget to add your all env files to git-ignore file to prevent tracking them after any modification
2- After each time u modify in env file restart the project otherwise its won't listen to your new changes
3- stick to your company/team for env files naming convention
as not all deployments processes accepts the .env.envName convention
for example vercel doesn’t accept ‘.’ in the env file name at all