Search code examples
node.jsenvironment-variablesdotenv

How do I assign an env variable in a node js application?


I working through this tutorial to create a WhatsApp chatbot.

In the tutorial, API keys are defined within index.js.

I would like to store the API keys in a .env file and use the dotenv package.

Here is an extract of the original version of index.js:

import { createBot } from 'whatsapp-cloud-api';
const { createBot } = require('whatsapp-cloud-api');

(async () => {
  try {
    // replace the values below
    const from = 'YOUR_WHATSAPP_PHONE_NUMBER_ID';
    const token = 'YOUR_TEMPORARY_OR_PERMANENT_ACCESS_TOKEN';
    const to = 'PHONE_NUMBER_OF_RECIPIENT';
    const webhookVerifyToken = 'YOUR_WEBHOOK_VERIFICATION_TOKEN';

I would like to replace the strings, such as 'YOUR_WHATSAPP_PHONE_NUMBER_ID', with a string defined in the .env file. For example, I tried:

const { createBot } = require('whatsapp-cloud-api');
const dotenv = require('dotenv');
dotenv.config();

(async () => {
  try {
    const from = process.env.FROM;
    const token = process.env.TOKEN;
    const to = process.env.TO; 
    const webhookVerifyToken = process.env.WEBHOOKVerifyToken;

after defining a .env file in the root directory with:

const FROM = YOUR_WHATSAPP_PHONE_NUMBER_ID
const TOKEN = YOUR_TEMPORARY_OR_PERMANENT_ACCESS_TOKEN
const TO = PHONE_NUMBER_OF_RECIPIENT
const WEBHOOKVerifyToken = YOUR_WEBHOOK_VERIFICATION_TOKEN

I just get an error that suggests the env strings have not been assigned. What am I doing wrong?

P.S. I am new to javascript and node.js so the answer may be obvious.


Solution

  • change your .env file to:

    FROM=YOUR_WHATSAPP_PHONE_NUMBER_ID
    TOKEN=YOUR_TEMPORARY_OR_PERMANENT_ACCESS_TOKEN
    TO=PHONE_NUMBER_OF_RECIPIENT
    WEBHOOKVerifyToken=YOUR_WEBHOOK_VERIFICATION_TOKEN
    

    more info: documentation