Set environment variables for apps

environment variables, env, secrets, dotenv, passenger, config · 0 found this helpful

Environment variables hold settings that change between your laptop, staging, and live, such as database passwords and API keys. Code reads them, so secrets never go into Git.

Node.js and Python apps

The Developer section doesn't have a screen for app variables yet. You have two choices.

  1. Keep them in a .env file outside your public folder, and load it when the app starts. See the .env section below.
  2. Open a request at https://barbrick.ca/submitticket.php and we'll set them for you, usually the same day. Then restart the app from Account → Hosting → your site → Developer.

Read them in code:

// Node.js
const url = process.env.DATABASE_URL;
# Python
import os
url = os.environ["DATABASE_URL"]

See Run a Node.js app and Run a Python app.

PHP sites: a .env file

For PHP and WordPress, the simplest way is a file the web server can't serve.

  1. Put .env outside public_html, such as /home/yourusername/.env:
DB_NAME=yourusername_bakery
DB_USER=yourusername_shop
DB_PASSWORD=change-me
STRIPE_KEY=sk_test_example
  1. Set its permissions to 600.
  2. Load it in PHP with a library such as vlucas/phpdotenv:
<?php
require __DIR__ . '/vendor/autoload.php';
Dotenv\Dotenv::createImmutable('/home/yourusername')->load();
$password = $_ENV['DB_PASSWORD'];

Install it with Composer.

For WordPress, read values in wp-config.php:

$env = parse_ini_file( '/home/yourusername/.env' );
define( 'DB_PASSWORD', $env['DB_PASSWORD'] );

Apache style: SetEnv

# .htaccess: sets a variable for PHP
SetEnv APP_ENV production

Read it with getenv('APP_ENV') or $_SERVER['APP_ENV']. Our LiteSpeed servers pass these values to PHP. Don't put secrets in .htaccess, since a mistake can expose them.

Shell

export APP_ENV=production        # this session only
echo 'export APP_ENV=production' >> ~/.bashrc    # for each SSH login

Cron jobs don't read ~/.bashrc. Put variables in the cron line. See Schedule tasks with cron jobs.

Rules

  • Never commit .env. Add it to .gitignore, and commit a .env.example with fake values.
  • Use different values for staging and live.
  • Rotate a secret that leaks. Change the password in Databases too.
  • Don't print variables in error pages.

If something goes wrong

Problem Fix
Value is undefined or null Restart the app. Check the name
.env downloadable from the web It's inside public_html. Move it
Variable missing in cron Set it in the cron command
Special characters break Wrap the value in quotes

Was this helpful?

Still stuck? Ask us and we'll walk you through it.