Environment variables and secrets: a practical guide

Keep configuration and secrets out of your code, read them safely in Node, Python and PHP, and manage them on Launchpad.

A closed terracotta strongbox with a cream key resting on top

This guide is for developers who want their apps to run the same code on a laptop and in production, with passwords and API keys kept out of the repository. It explains what environment variables are for, how to work with them locally, and how Launchpad stores them and hands them to your app.

By the end you will have a .env and .env.example set up correctly, code that reads and validates its configuration at startup, and a plan for the day a secret leaks.

Config, secrets and the twelve-factor idea

An app has two kinds of settings. Config changes between environments: the database address, the log level, the public URL. Secrets are config that would cause harm if someone else saw them: database passwords, API keys, session signing keys.

The twelve-factor app methodology recommends storing both in environment variables rather than in code. The same build can then run anywhere, and changing a setting does not need a code change. More importantly, secrets never enter your Git history, where they would be visible to everyone with read access, forever.

A useful test: could you make the repository public right now without leaking anything? If not, something that belongs in a variable is in your code.

Local development: .env and .env.example

Locally, keep variables in a .env file at the project root and never commit it. Commit a .env.example instead, with the same names and empty or harmless values. It documents what the app needs, and Launchpad reads it when you deploy from GitHub to pre-fill variable names.

Config
# .env.example: commit this
DATABASE_URL=
SESSION_SECRET=
STRIPE_SECRET_KEY=
LOG_LEVEL=info
Config
# .env: never commit this
DATABASE_URL=postgres://dev:dev@localhost:5432/app_dev
SESSION_SECRET=local-only-not-a-real-secret
STRIPE_SECRET_KEY=sk_test_replace_me
LOG_LEVEL=debug

Add .env to .gitignore before you create it, not after:

Text
.env
.env.local
!.env.example

When you upload a zip to Launchpad, files named .env are skipped on purpose, so a local secrets file cannot end up in a build by accident.

Reading variables in your code

Every language reads environment variables from the process. Loading a .env file is a local convenience; in production on Launchpad, variables are already in the environment when your app starts.

Node.js

Node 20.6 and later can load a .env file without a library. Use the flag only in your development script, not in start:

JSON
{
  "scripts": {
    "dev": "node --env-file=.env server.js",
    "start": "node server.js"
  }
}
JavaScript
const port = process.env.PORT || 3000;
const databaseUrl = process.env.DATABASE_URL;
const logLevel = process.env.LOG_LEVEL ?? 'info';

Python

Locally, the python-dotenv package loads .env. In production it finds no file and changes nothing.

Python
import os
from dotenv import load_dotenv

load_dotenv()

port = int(os.environ.get("PORT", "8000"))
database_url = os.environ["DATABASE_URL"]
log_level = os.environ.get("LOG_LEVEL", "info")

os.environ["NAME"] raises an error when the variable is missing, which is what you want for required values. os.environ.get returns a default for optional ones.

PHP

Plain PHP reads variables with getenv():

PHP
<?php
$databaseUrl = getenv('DATABASE_URL');
$logLevel = getenv('LOG_LEVEL') ?: 'info';

Laravel loads .env itself. Call env() only inside files in the config folder and read values elsewhere with config(), because env() returns null once the configuration is cached. Laravel also needs APP_KEY; generate one with php artisan key:generate --show and add it as a variable.

Validate required variables at startup

A missing variable should stop the app at startup with a clear message, not cause a confusing error on the first request an hour later. Check everything up front.

JavaScript
// config.js
const required = ['DATABASE_URL', 'SESSION_SECRET', 'STRIPE_SECRET_KEY'];
const missing = required.filter((name) => !process.env[name]);

if (missing.length > 0) {
  console.error(`Missing required environment variables: ${missing.join(', ')}`);
  process.exit(1);
}

module.exports = {
  port: Number(process.env.PORT) || 3000,
  databaseUrl: process.env.DATABASE_URL,
  sessionSecret: process.env.SESSION_SECRET,
  stripeSecretKey: process.env.STRIPE_SECRET_KEY,
  logLevel: process.env.LOG_LEVEL || 'info',
};

Require ./config at the top of your entry file. On Launchpad the app then exits before the health check, the deployment fails, the previous version keeps running, and the logs name the missing variables. The message lists names only, never values.

How Launchpad handles variables

Each app has a Variables tab. Values are stored encrypted, hidden in the dashboard and never written to logs. Launchpad hands them to your app when it starts.

Environment variables: stored encrypted in the dashboard, injected at start, read by the app
Variables are encrypted at rest and handed to the app when it starts

Because variables are read at start, changing one does not affect the running app. After you add or edit variables, a banner appears; press Redeploy now to start the app with the new values. Batch several changes together and redeploy once.

Names use letters, numbers and underscores and cannot start with a number. The app's AI assistant can see variable names to help you debug, but never their values.

Variables Launchpad sets for you

  • PORT is the port your app must listen on, on 0.0.0.0. It matches the port in the app's settings.
  • LAUNCHPAD_URL and LAUNCHPAD_HOST hold the app's own address, useful for building absolute links and callback URLs.
  • DATABASE_URL is added when you connect a PostgreSQL or MySQL database to the app, and REDIS_URL when you connect Redis. They contain the full connection string, password included.

If you connect your own domain, set your own variable such as APP_URL=https://example.com for links that should use it. Do the same if you build with your own Dockerfile, rather than relying on LAUNCHPAD_URL being present.

Build-time and runtime variables

Most server code reads variables while it runs, so a redeploy with new values is enough. Some frameworks instead copy values into the built files at build time. In Next.js, any variable starting with NEXT_PUBLIC_ is written into the JavaScript sent to browsers when next build runs. Vite does the same with VITE_ variables.

Two consequences follow. First, a change to one of these values only takes effect after a new build, so always redeploy rather than restarting. Second, anything with those prefixes is public: every visitor can read it in their browser. Never give a secret a NEXT_PUBLIC_ or VITE_ name.

If a build-time value does not appear in the built site after a redeploy, the build did not see it. Check the spelling and prefix, or have the browser fetch the value from a small server route at runtime instead.

Step by step: add and rotate a secret on Launchpad

  1. Create the secret at the provider (for example a new API key) with the narrowest permissions it allows.
  2. Open your app and go to Variables.
  3. Add the name, such as STRIPE_SECRET_KEY, and paste the value.
  4. Press Redeploy now on the banner and wait for Live.
  5. To rotate, create a new key at the provider while the old one still works.
  6. Replace the value under Variables, press Redeploy now and confirm the app works.
  7. Revoke the old key at the provider.

When a secret leaks

If a secret was committed, pasted in a chat or printed in a log, treat it as compromised. Rotate it straight away using the steps above, then check the provider's logs for misuse. Deleting the commit or rewriting history does not help on its own: clones, forks and caches may already hold it.

Common mistakes

  • Committing .env. Add it to .gitignore first, and commit only .env.example.
  • Editing a variable and expecting it to apply. Running apps keep the values they started with. Press Redeploy now.
  • Secrets with public prefixes. NEXT_PUBLIC_ and VITE_ values reach every browser. Keep secrets server-side.
  • Logging the environment. console.log(process.env) puts every secret in your runtime logs. Log names, not values.
  • Hard-coding localhost. A DATABASE_URL of localhost works on your laptop only. Connect a database and use the injected value.

Security notes

Give each environment its own secrets: development, staging and production should never share a database password or API key. Use the least privileged key a provider offers, such as restricted API keys scoped to the calls you make. Rotate secrets when someone with access leaves the team.

Launchpad keeps variable values out of its own logs, but your code can still print them. Review error handlers and debug output, and make sure exception reports do not include the full environment. Restrict who on your account can manage apps, since anyone who can deploy code can read the variables from inside it.

Troubleshooting

SymptomCauseFix
App works locally, crashes on LaunchpadA variable exists in .env but not under VariablesAdd it, then Redeploy now
New value has no effectApp not redeployed after the changePress Redeploy now on the banner
NEXT_PUBLIC_ value is old or undefinedValue is baked in at build timeRedeploy to rebuild; check the exact name and prefix
Database connection refusedCode uses a local address, or no database connectedConnect a database and read DATABASE_URL
Laravel shows an encryption key errorAPP_KEY missingGenerate it and add it under Variables

Frequently asked questions

Can the AI assistant see my secret values?

No. Values are stored encrypted and hidden in the dashboard. The app's AI assistant sees variable names, never values, and AI tools you connect to your account see names only too.

Can I upload my .env file instead of typing each variable?

Not as part of a zip upload: .env files are skipped on purpose. Deploying from GitHub with a committed .env.example pre-fills the names so you only paste values.

Do I need a library like dotenv in production?

No. On Launchpad, variables are already in the process environment. A loader is only needed to read .env on your machine.

What is the difference between a variable and a secret?

Technically nothing: both are environment variables. The difference is how carefully you handle them. Treat anything that grants access as a secret.

Next steps

Keeping configuration out of code makes your app portable and your repository safe to share with your team. Next, make releases predictable and recoverable.

Share this articleLinkedIn (opens in a new tab)X (opens in a new tab)Facebook (opens in a new tab)
Was this article helpful?

Get new guides in your inbox.

One email a month. Unsubscribe anytime.