How to Keep a Connection String in an Environment Variable

Your connection string usually holds a password, so it should not live in your code. This how-to moves it into an environment variable, the standard approach used by most hosting platforms.

What you need

Steps

  1. **Create a file named .env** in your project's top folder:
DATABASE_URL=postgresql://app:localpass@localhost:5432/shop_dev

No quotes or spaces around the = are needed for simple values.

  1. Tell git to ignore it. Add this line to .gitignore (create the file if it does not exist):
.env
  1. Add an example file for others called .env.example, with a fake value:
DATABASE_URL=postgresql://user:password@localhost:5432/dbname

Commit .env.example, not .env.

  1. Load the variable in your code.

Python, after pip install python-dotenv:

import os
from dotenv import load_dotenv

load_dotenv()                       # reads .env into the environment
url = os.environ["DATABASE_URL"]

Node.js, after npm install dotenv:

require("dotenv").config();
const url = process.env.DATABASE_URL;

Recent versions of Node.js can also load a file directly with node --env-file=.env app.js.

  1. Remove the old hard-coded string from your code and use url instead.
  1. Set the real value on your hosting platform. Most platforms have a settings page for environment variables or secrets. Use the production connection string there; it never needs to touch your laptop.

How to check it worked

Common problems

ProblemCauseFix
KeyError or undefined value.env not loaded, or the name is misspeltLoad it before reading; check spelling and case
Works locally, fails on the hostVariable not set on the platformAdd it in the platform's settings
.env already committed earlierIt is in git historyChange the password, then remove the file from git tracking
Password with special characters breaks the URLCharacters like @ need encodingPercent-encode them, for example @ as %40

Why this matters

Environment variables keep secrets out of code, let the same code run in development and production with different databases, and make it simple to change a password without editing files. Our talk notes on keeping connection strings secret explain the reasons in more depth.

A free learning page for beginners. Practise on a test database, never on real customer data, and check the official documentation for your database version.

Related pages on this site