configure .env file in javascript

To configure a .env file in a Node.js project using Javascript, you can follow these steps:

  1. Install dotenv package:
index.tsx
npm install dotenv
19 chars
2 lines
  1. Create a .env file in the root of your project directory.

  2. Add your environment variables to the .env file in KEY=VALUE format:

index.tsx
PORT=3000
DB_URL=localhost:27017/mydb
SECRET_KEY=abc123
56 chars
4 lines
  1. Load the environment variables in your Javascript code using the dotenv package:
index.tsx
require('dotenv').config()
27 chars
2 lines
  1. You can now access your environment variables within your node application using process.env.KEY. For example:
index.tsx
const port = process.env.PORT || 3000;
const dbUrl = process.env.DB_URL;
const secretKey = process.env.SECRET_KEY;
115 chars
4 lines

In the above code snippet, we're accessing the environment variables PORT, DB_URL, and SECRET_KEY using process.env. We've also set a default value for PORT in case it's not defined in the .env file.

Note: It's important to add the .env file to your .gitignore file, so that you don't accidentally commit sensitive information to version control.

gistlibby LogSnag