Environment Variables in Node.js
Overview
Environment variables are a way to store configuration settings and sensitive information separately from your code. This helps keep your application secure and flexible across different environments (development, testing, production).
Setting Up Environment Variables
In a Node.js application, you can create a file named .env
in the root directory to define your environment variables:
# .env
DATABASE_URL=mongodb://localhost:27017/mydatabase
SECRET_KEY=mysecretkey
Using dotenv Package
To load environment variables from the .env
file, you need to install the dotenv
package:
npm install dotenv
Then, require and configure it at the beginning of your application:
// server.js or app.js
require('dotenv').config(); // Load environment variables
const dbUrl = process.env.DATABASE_URL;
console.log('Database URL:', dbUrl);
Accessing Environment Variables
You can access environment variables in your application using process.env.VARIABLE_NAME
. Here's an example:
// Using environment variables
const express = require('express');
const app = express();
require('dotenv').config();
app.get('/', (req, res) => {
res.send('Secret Key: ' + process.env.SECRET_KEY);
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
Best Practices
Here are some best practices for using environment variables:
- Never commit your
.env
file to version control (add it to.gitignore
). - Use descriptive variable names to make it clear what each variable does.
- Consider using a service like
dotenv-safe
for additional security.