What are Environment Variables? Secrets Management

Share

TL;DR

Environment variables store configuration and secrets outside your code. Instead of hardcoding API keys, you reference variables like process.env.API_KEY. This keeps secrets out of git, lets you use different values in development vs production, and makes it easy to rotate credentials without changing code.

The Simple Explanation

Your code needs to connect to a database. Instead of writing the password directly in your code (where anyone can see it), you put it in an environment variable. Your code reads the variable at runtime, and the actual secret never appears in your source files.

How to Use Them

.env file

DATABASE_URL=postgresql://user:password@localhost/mydb STRIPE_SECRET_KEY=sk_test_abc123 NEXT_PUBLIC_API_URL=https://api.example.com

Accessing in code

// Node.js / JavaScript const dbUrl = process.env.DATABASE_URL;

// Python import os db_url = os.environ.get('DATABASE_URL')

Best Practices

  • Never commit secrets: Add .env to .gitignore
  • Create .env.example: Show required variables with placeholder values
  • Validate at startup: Fail early if required variables are missing
  • Use different values per environment: Development, staging, production
  • Prefix client-side variables: NEXT_PUBLIC_ or VITE_ for browser access

Security note: Variables prefixed with NEXT_PUBLIC_ or VITE_ are exposed to the browser. Never put secret keys in client-accessible variables.

Common Patterns

  • DATABASE_URL: Database connection string
  • API_KEY / SECRET_KEY: Third-party service credentials
  • JWT_SECRET: Secret for signing tokens
  • NODE_ENV: development, production, or test

What is the difference between .env and .env.local files?

The .env file typically contains default or example values and may be committed to git. The .env.local file contains actual secrets for local development and should never be committed. Most frameworks prioritize .env.local over .env when both exist.

Should I commit my .env file to git?

Never commit .env files with real secrets. Instead, commit a .env.example file with placeholder values that shows what variables are needed. Add .env and .env.local to your .gitignore file to prevent accidental commits.

How do environment variables work in production?

In production, environment variables are set through your hosting platform's dashboard or secrets management system, not through .env files. Platforms like Vercel, Netlify, Railway, and AWS have built-in ways to securely store and inject environment variables.

Find Exposed Secrets

Scan your repo for hardcoded credentials and API keys.

Start Free Scan
Security Glossary

What are Environment Variables? Secrets Management