In modern development, .env files are essential for managing environment-specific configuration. Whether you're building a Node.js backend, a Python app, or a full-stack project, you’ve probably seen a .env file somewhere. But what exactly is it?
What Is a .env File?
A .env file (short for environment) is a plain text file where you store environment variables as key-value pairs
These values are not hardcoded into your application, which means:
- Your config stays clean
- You can change settings without touching your code
- Sensitive data stays out of your Git repo
What Should You Store in .env?
- API keys
- Database URLs
- Secret tokens (like JWT secrets)
- Environment flags (e.g.,
NODE_ENV=production) - Any config that varies by environment
How to Use .env in Your Project🛠️
In Node.js
- Create a .env file in the root of your project, save in it your secret variables like a key-value pair:
PORT=3000
DB_HOST=localhost
JWT_SECRET=yourSuperSecretKeyHere
- Install the
dotenvpackage, in your terminal run:
npm install dotenv
- Load the
.envFile in Your Code At the top of your main file (likeserver.jsorindex.js), add this line:
require('dotenv').config();
- Now you can access your environment variables using:
const PORT = process.env.PORT;
const SECRET = process.env.JWT_SECRET;
Wait, What’s process.env? 🤔
In Node.js, process.env is a built-in object that gives you access to environment variables.
When you write process.env.JWT_SECRET, you're saying:
"Give me the value of the environment variable named JWT_SECRET."
It's how your app knows which port to use, what database to connect to, or what secret to use for signing tokens, without hardcoding them into your source files.
🚫 Don’t Commit .env to Git!
Always add it to your .gitignore:
# .gitignore
.env
Summary
-
.envfiles store environment variables - Keep secrets out of your code
- Use libraries like
dotenvto access them - Never commit
.envto version control
Top comments (1)
Some comments may only be visible to logged-in visitors. Sign in to view all comments.