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
- a project in Python or Node.js that connects to a database
- your project under version control with git (recommended)
- your current connection string, for example
postgresql://app:localpass@localhost:5432/shop_dev
Steps
- **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.
- Tell git to ignore it. Add this line to
.gitignore(create the file if it does not exist):
.env
- 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.
- 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.
- Remove the old hard-coded string from your code and use
urlinstead.
- 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
- Run your app; it should connect exactly as before.
- Run
git status..envmust not appear in the list of files to commit. - Search your code for the password text. It should appear nowhere.
Common problems
| Problem | Cause | Fix |
|---|---|---|
| KeyError or undefined value | .env not loaded, or the name is misspelt | Load it before reading; check spelling and case |
| Works locally, fails on the host | Variable not set on the platform | Add it in the platform's settings |
.env already committed earlier | It is in git history | Change the password, then remove the file from git tracking |
| Password with special characters breaks the URL | Characters like @ need encoding | Percent-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.