npm install dotenv
.env
file in the root directory:KEY=your-secret-key
API_URL=https://api.example.com
// ES Module
import 'dotenv/config';
const key = process.env.KEY;
// CommonJS
require('dotenv').config();
const key = process.env.KEY;
.env
is in .gitignore
to prevent exposing sensitive data.Custom Path
Specify a custom .env
file location:
require('dotenv').config({ path: './config/.env' });
Expanding Variables
Use variables inside .env
:
DB_USER=admin
DB_PASS=secret
DATABASE_URL=mysql://${DB_USER}:${DB_PASS}@localhost:3306/mydb
Load them in Node.js:
require('dotenv').config({ expand: true });
console.log(process.env.DATABASE_URL);
// Output: mysql://admin:secret@localhost:3306/mydb
Using in Scripts
Instead of manually requiring dotenv
, you can load it automatically when running your script:
node -r dotenv/config server.js