How to Use Environment Variables in JavaScript with Dotenv
最終更新日 February 18, 2025

Introduction

Hardcoding sensitive information in your source files is like writing your password on a sticky note and leaving it on your laptop for everyone to see—not a great idea! A better, more secure approach is to use environment variables, which securely store sensitive data like API keys and passwords outside your codebase.

Not all JavaScript frameworks automatically import environment variables, so using a module like dotenv —a lightweight, zero-dependency library—is good practice to simplify this process. Dotenv reads the variables defined in a .env file and loads them into Node.js's process.env object, which acts as a global store for environment variables as key-value pairs (all values saved as strings). This setup ensures your sensitive information is securely accessible throughout your application without exposing it in your code.

Now, let’s get into how to use environment variables with dotenv with a practical example: sending a WhatsApp message using the Vonage Messages API!

Install Dotenv

Run the following commands on your terminal to initialize npm, install dotenv, and initialize the git repository on the project:

// initialize npm on the project
npm init -y

// install dotenv
npm install dotenv --save

// initialize git repo
git init

Use Dotenv

To start using dotenv, create a .env file in the root directory of your project. This file will hold your environment variables. You can follow the full tutorial on sending a WhatsApp message to find these values in your Vonage application:

VONAGE_API_KEY="your-api-key"
VONAGE_API_SECRET="your-api-secret"
VONAGE_APPLICATION_ID="your-application-id"
VONAGE_PRIVATE_KEY="path/to/your/private.key"
TO_NUMBER="recipient-phone-number"
WHATSAPP_NUMBER="sender-phone-number"

Note: if your variable has spaces in it, wrap it in quotation marks.

Send a WhatsApp Message with Vonage Messages API

Next, create a send-whatsapp-message.js file.

Add this line as the application’s entry point to configure dotenv:

require('dotenv').config();

Add this line and run it, then remove it once you’ve confirmed dotenv is working:

console.log(process.env);

To access environment variables in Node.js, use process.env followed by the variable name. For example:

const VONAGE_APPLICATION_ID = process.env.VONAGE_APPLICATION_ID;

Add the remaining code:

// initialize dependencies 
const VONAGE_APPLICATION_ID = process.env.VONAGE_APPLICATION_ID;
const VONAGE_PRIVATE_KEY = process.env.VONAGE_PRIVATE_KEY;

const TO_NUMBER = process.env.TO_NUMBER;
const WHATSAPP_NUMBER = process.env.WHATSAPP_NUMBER;

const { Vonage } = require('@vonage/server-sdk');
const { WhatsAppText } = require('@vonage/messages');

const vonage = new Vonage({
  applicationId: VONAGE_APPLICATION_ID,
  privateKey: VONAGE_PRIVATE_KEY,
});

// the logic
vonage.messages.send(
  new WhatsAppText({
    text: 'This is a WhatsApp Message text message sent using the Messages API',
    to: TO_NUMBER,
    from: WHATSAPP_NUMBER,
  }),
)
  .then((resp) => console.log(resp.messageUUID))
  .catch((error) => console.error(error));

Now, if you run the code, it should access your environment variables to send the message:

node send-whatsapp-message.js

Another way to invoke .env is by calling it inside a script. This means you won’t need require('dotenv').config() at the top of your send-whatsapp-message.js file. Instead, go to your project’s package.json file and make a script called“dev”like the following:

"scripts": {
"dev": "node -r dotenv/config send-whatsapp-message.js"

If you run the script, you’ll still get your environment variables!

npm run dev

Manage Multiple Environments

In complex projects, you may need different .env files for development, testing, and production environments. Tools like dotenv-cli can help you manage multiple environments.

For example, you can use different .env files:

  • .env.local

  • .env.production

Load them with the dotenv-cli CLI:

$ dotenv -e .env.production node send-whatsapp-message.js

Deploy Securely

For secure deployment, .env files should never be committed to source control! Use .gitignore to exclude them.

To do this, create a .gitignore file with the following content:

.env

Now, when you commit to git, everything but the file(s) listed will be pushed to the repository.

Conclusion

Now that you’ve learned how to use environment variables in JavaScript, you can stop hardcoding your personal information in your code and pushing it to prod for the world to see! Do you have other best practices using environmental variables? If you do, please share them and tag me - I'd love to hear about them! Also, feel free to join our community Slack and follow us on X, formerly known as Twitter. Happy coding!

Diana PhamDeveloper Advocate

Diana is a developer advocate at Vonage. She likes eating fresh oysters.

Ready to start building?

Experience seamless connectivity, real-time messaging, and crystal-clear voice and video calls-all at your fingertips.

Subscribe to Our Developer Newsletter

Subscribe to our monthly newsletter to receive our latest updates on tutorials, releases, and events. No spam.