I’m encountering a ReferenceError: dotenv is not defined issue in my Node.js backend application managed by PM2. Here’s the breakdown:
Environment Details:
Node.js version: 18.20.5
PM2 version: 5.x
Backend framework: Express.js
Problem Description:
When I try to run my application with PM2, I see the following error in the logs:
ReferenceError: dotenv is not defined
at Object.<anonymous> (/root/DevTrust/backend/server.js:20:1)
at Module._compile (node:internal/modules/cjs/loader:1364:14)
What I've Tried So Far:
Installed dotenv using: npm install dotenv –force
Verified it’s in node_modules using npm list dotenv
Ensured the top of server.js has:
javascript
require('dotenv').config();
Verified .env exists in the backend folder and contains required variables:
makefile
OPENAI_API_KEY=your_actual_api_key
Restarted PM2 with:
bash
pm2 restart backend
pm2 save
Tried running the server directly using node server.js (it works fine).
Logs from PM2:
When running pm2 logs backend –lines 50, I see repeated ReferenceError: dotenv is not defined.
Expected Behavior:
The backend server should load environment variables from the .env file without any errors when started with PM2.
Actual Behavior:
It keeps failing with ReferenceError: dotenv is not defined.
How can I ensure that dotenv is properly loaded and recognized by PM2 when running the backend server?
Any insights or suggestions are appreciated. Thanks in advance!