Configuring Environment Variables for Node.js via cPanel
Configuring Environment Variables for Node.js via cPanel
Why Use Environment Variables?
Environment variables allow you to securely store settings like database credentials, API keys, and environment-specific flags (e.g., production
, development
) outside your Node.js source code. This improves security and flexibility across environments.
Step-by-Step Setup Guide
1. Log into Your cPanel Account
- Visit yourdomain.com/cpanel
- Enter your cPanel username and password
2. Open “Setup Node.js App” or “Application Manager”
- Search for Setup Node.js App in the cPanel dashboard
- Click on it to see your existing Node.js applications
3. Select Your Application
- Find your Node.js app in the list
- Click the Edit or Settings button next to it
4. Add Environment Variables
- Scroll down to the Environment Variables section
- Click Add Variable
- Input your variable name and value:
NODE_ENV
→production
DB_HOST
→localhost
API_KEY
→your-secure-api-key
- Click Save or Update
5. Restart the Application
- Scroll up to the top of the app settings panel
- Click Restart to apply the changes
Accessing Environment Variables in Your App
Use process.env
in your Node.js code to access the values:
const dbHost = process.env.DB_HOST;
const environment = process.env.NODE_ENV;
Tip: Never hard-code sensitive data (like passwords or tokens) into your app code. Always use environment variables for such configurations.
Common Environment Variables
NODE_ENV
— Defines the environment (e.g., development or production)PORT
— The port your app should listen on (often set automatically)DB_HOST
,DB_USER
,DB_PASS
— For database credentialsSECRET_KEY
— For encryption/authentication tokens
Troubleshooting
- Ensure your app is restarted after updating variables
- Check logs if your app fails to st