Environment variables keep settings such as database passwords, API keys and the port number outside your code. The same code can then run on your laptop, a staging server and production with different values. This guide shows where to set them on cPanel hosting and on a VPS.
Before you start
- A Node.js app on cPanel hosting or a Linux VPS.
- A list of the variables your app expects (often in a
.env.examplefile in the project).
Read environment variables in code
Node.js exposes every variable on process.env:
const port = process.env.PORT || 3000;
const dbUrl = process.env.DATABASE_URL;Values are always strings. Convert them when you need a number or boolean, for example Number(process.env.PORT).
Use a .env file
- Create a file named
.envin the project root:NODE_ENV=production PORT=3000 DATABASE_URL=mysql://appuser:CHANGE_ME@localhost:3306/appdb - Node.js 20.6 and later can load it without any package:
node --env-file=.env server.js - On older versions install
dotenvand load it at the very top of your entry file:npm install dotenvrequire('dotenv').config(); - Add
.envto.gitignoreso it is never committed.
Warning: Never place a .env file inside public_html or any folder the web server serves directly. Keep the app folder outside the document root so the file cannot be downloaded.
Set variables in cPanel
- Log in to cPanel (from the MdmHost dashboard open Services and click the cPanel button).
- Go to cPanel → Software → Setup Node.js App and click the pencil icon next to your app.
- Under Environment variables click Add Variable, enter the name and value, and click Done.
- Click Save, then Restart so the app picks up the change.
Full details of the app screen are in Set up a Node.js app in cPanel.
Set variables with PM2
Put them in the env block of ecosystem.config.js, then reload with the new values:
pm2 restart ecosystem.config.js --update-envSee PM2 process manager for the full ecosystem file.
Set variables in a systemd service
If you run the app as a systemd unit, point it to an environment file:
[Service]
EnvironmentFile=/home/deploy/myapp/.env
ExecStart=/usr/bin/node /home/deploy/myapp/server.jsRun sudo systemctl daemon-reload and restart the service after editing.
Next.js build-time vs runtime variables
In Next.js, variables starting with NEXT_PUBLIC_ are written into the browser JavaScript at build time. Change them and you must rebuild with npm run build. Variables without the prefix are only available on the server and are read at runtime. Never give a secret the NEXT_PUBLIC_ prefix.
Troubleshooting
- Variable is
undefined— the app was not restarted, the name has a typo, or dotenv is loaded after the code that reads it. - Works locally, not on the server — the
.envfile was not uploaded (it is usually excluded from Git), so create it on the server.
