get value from .env in javascript

To get a value from .env file in Javascript, you need to use a package called dotenv.

Firstly, install the package by running this command in your project directory:

npm install dotenv
19 chars
2 lines

Then, create a .env file in the root directory of your project and add your environment variables like this:

index.tsx
PORT=3000
SECRET_KEY=ThisIsASecretKey
DB_URL=mongodb://localhost/mydatabase
76 chars
4 lines

In your Javascript code, require the dotenv package and call its config() method, which reads the .env file and adds its contents to process.env. You can then access the values of the environment variables using process.env.VARIABLE_NAME.

index.tsx
require('dotenv').config();

const port = process.env.PORT;
const secretKey = process.env.SECRET_KEY;
const dbUrl = process.env.DB_URL;

console.log(`Server running on port ${port}`);
console.log(`Secret key is ${secretKey}`);
console.log(`Database URL is ${dbUrl}`);
268 chars
10 lines

gistlibby LogSnag