how to use .env in javascript

To use .env in JavaScript, you can use dotenv package which loads environment variables from a .env file into process.env. Here's how you can use it:

  1. Install dotenv package using npm.
npm install dotenv
19 chars
2 lines
  1. Create a .env file in the root directory of your project and add environment variables with key-value pairs. For example:
DB_HOST=localhost
DB_USER=root
DB_PASSWORD=secret
50 chars
4 lines
  1. Require and configure dotenv at the beginning of your JavaScript file.
index.tsx
require('dotenv').config()
27 chars
2 lines
  1. Access environment variables using process.env.
index.tsx
const dbConfig = {
  host: process.env.DB_HOST,
  user: process.env.DB_USER,
  password: process.env.DB_PASSWORD
};

console.log(dbConfig);
140 chars
8 lines

This will output:

index.tsx
{
  host: 'localhost',
  user: 'root',
  password: 'secret'
}
62 chars
6 lines

Make sure to add .env to .gitignore file to keep your sensitive data out of version control.

gistlibby LogSnag