Page cover image

Environment Variables

Environment variables keep secrets out of your code, and have different settings for different stages of your application (like development, testing, and production).

What are Environment Variables

Environment variables are key-value pairs stored outside of your application's configuration that can affect how it runs.

They're often used for:

  • Configuring different environments (development, production, etc.).

  • Storing secrets, like API keys, which should not be hard-coded or stored in the source code.

  • Parameterizing settings so that they can be changed without altering the application's code.

Setting Environment Variables

On Your Local Development Machine

Windows (Command Prompt):

set MY_VARIABLE=my_value

Windows (PowerShell):

$env:MY_VARIABLE = "my_value"

Linux/macOS:

export MY_VARIABLE=my_value

Reading Environment Variables in Code

Python:

import os
my_variable = os.environ.get('MY_VARIABLE')

Node.js:

const myVariable = process.env.MY_VARIABLE;

Using .env Files for Local Development

For local development, instead of setting variables in the command line every time, you can use .env files.

Tools like dotenv for Node.js and python-decouple for Python allow you to load environment variables from .env files into your application.

Example .env file:

DATABASE_URL=postgres://user:password@localhost:5432/mydatabase
SECRET_KEY=mysecretkey
DEBUG=True

Environment Variables in Production

In production, environment variables can be set:

  • Directly on the server: Use the methods mentioned above.

  • Using a platform's dashboard: Platforms like Heroku or AWS Elastic Beanstalk allow you to set environment variables via their dashboard.

  • Container Orchestration Systems: Systems like Kubernetes allow you to set environment variables for your containers in your deployment configurations.

Best Practices

  1. Don't Commit Secrets: Never commit secrets (API keys, database passwords, etc.) to version control. Instead, use environment variables.

  2. Use .env files for Local Development Only: .env files are great for local development but shouldn't be used in production settings. Instead, set environment variables directly on your production servers or through your orchestration tool.

  3. Have Clear Documentation: If you're working on a team, ensure everyone knows what environment variables are required for the application to run and what they're used for.

Some environment variables can be set as key-value in softwares such as gitlab & when you push code it automatically identifies these variables

Last updated