Database Environment Variable Configuration

Set up DATABASE_URL and related environment variables for different platforms. Covers .env files, Vercel, Heroku, AWS, Docker, and CI/CD pipelines.

Best Practices

Detailed Explanation

Environment Variables for Database Connections

Storing database connection strings in environment variables is the standard approach for keeping credentials out of your codebase.

.env Files (Local Development)

Create a .env file in your project root:

# Database
DATABASE_URL="postgresql://postgres:postgres@localhost:5432/myapp"

# Individual variables (alternative)
DB_HOST="localhost"
DB_PORT="5432"
DB_NAME="myapp"
DB_USER="postgres"
DB_PASSWORD="postgres"
DB_SSL="false"

Load with your framework or a library like dotenv:

require('dotenv').config();
// or in Next.js, .env.local is loaded automatically

Platform-Specific Setup

Vercel

vercel env add DATABASE_URL production
# Paste your connection string when prompted

Or in the Vercel dashboard: Project Settings > Environment Variables.

Vercel automatically injects environment variables for database integrations (Vercel Postgres, Neon, PlanetScale).

Heroku

heroku config:set DATABASE_URL="postgresql://user:pass@host:5432/db"

Heroku automatically sets DATABASE_URL when you add a database add-on (Heroku Postgres, JawsDB MySQL, etc.).

AWS (ECS / Lambda)

For ECS, set environment variables in the task definition:

{
  "containerDefinitions": [{
    "environment": [
      { "name": "DATABASE_URL", "value": "postgresql://..." }
    ]
  }]
}

For Lambda, set them in the function configuration or use AWS Secrets Manager with a runtime lookup.

Docker / Docker Compose

services:
  app:
    environment:
      - DATABASE_URL=postgresql://user:pass@postgres:5432/mydb
    # Or reference a .env file:
    env_file:
      - .env

Multiple Environments

Use separate .env files per environment:

.env                # Default / shared values
.env.local          # Local overrides (gitignored)
.env.development    # Development-specific
.env.production     # Production-specific (gitignored)
.env.test           # Test-specific

Next.js loads these in order of precedence. Variables in .env.local override .env.

CI/CD Pipelines

GitHub Actions

env:
  DATABASE_URL: ${{ secrets.DATABASE_URL }}

steps:
  - run: npm test

GitLab CI

variables:
  DATABASE_URL: $DATABASE_URL  # Set in GitLab CI/CD settings

Security Checklist

  • Add .env, .env.local, and .env.production to .gitignore
  • Use platform-specific secret storage in production
  • Never log the full DATABASE_URL — mask the password
  • Use different credentials per environment
  • Rotate credentials periodically

Use Case

Setting up a new project with proper environment variable management across local development, staging, and production environments, or migrating from hardcoded credentials to environment-based configuration.

Try It — Connection String Builder

Open full tool