xxxxxxxxxx
//in your script file
import 'dotenv/config';
//alertnatively you can do this when you env file is not in your main folder
import dotenv from 'dotenv';
import path from 'path';
dotenv.config({path: './config/.env'});
//or
dotenv.config({path: path.resolve(__dirname, 'config/.env')});
xxxxxxxxxx
// Run npm i dotenv
// Create .env file
// Add your properties (EX: PORT = 3000);
// In your script type:
import dotenv from 'dotenv';
dotenv.config(); // to load the date from .env file
xxxxxxxxxx
// Terminal/CMD
npm i dotenv
//In .env file
SPECIAL_KEY = 0000000 //whatever the key
//In nodejs file - 2 point usage
//1 - initialisation
require('dotenv').config();
//2 - using the special key
const specialKey = process.env.SPECIAL_KEY
console.log(specialKey);
xxxxxxxxxx
#in you cmd type this command
npm i dotenv
#and then require it in you javascript using :
require("dotenv").config()
xxxxxxxxxx
This is used to add a specific path to locate the .env file if we use like this
.config() then this is finding .env file in our cwd - current working directory.
require('dotenv').config({ path: '/custom/path/to/.env' })
xxxxxxxxxx
require('dotenv').config()
console.log(process.env) // remove this after you've confirmed it is working
xxxxxxxxxx
#in you cmd type this command
npm i dotenv
#and then require it in you javascript using :
require("dotenv").config()
dotenv is used in Node.js to load environment variables from a .env file into process.env at runtime, allowing developers to keep sensitive information, such as API keys or database passwords, separate from their code and stored securely. This helps to prevent accidental exposure of sensitive information in version control systems or deployment pipelines.
xxxxxxxxxx
# file: .env
SECRET_KEY=secret_token_here
# filename: test.py
"""
create a file in local directory
touch .env
add entries with following format:
SECRET_KEY=secret_token_here
"""
from dotenv import load_dotenv
import os
# By Default below line will load a file ".env" in current working directory
load_dotenv(".env")
secret_key = os.getenv('SECRET_KEY')
print(secret_key)
# output:
> python .\test_env.py
secret_token_here