Swiftorial Logo
Home
Swift Lessons
Tutorials
Learn More
Career
Resources

Environment Variables Best Practices

Introduction

Environment variables are a set of dynamic values that can affect the way running processes behave on a computer. They are used to configure operating systems and applications. Proper management of environment variables is crucial for application security, portability, and maintainability.

1. Use Descriptive Variable Names

Choose clear and descriptive names for your environment variables. This helps others understand their purpose without needing additional documentation.

Example:

DATABASE_URL
API_KEY

2. Keep Secrets Secure

Never hard-code sensitive information like passwords, API keys, or tokens in your source code. Instead, store them in environment variables.

Example:

export DATABASE_PASSWORD="your_secure_password"
export API_KEY="your_api_key"

3. Use a .env File for Local Development

For local development, use a .env file to store environment variables. This file should be included in your .gitignore to prevent it from being committed to version control.

Example of a .env file:

DATABASE_URL=postgres://user:password@localhost:5432/mydatabase
API_KEY=your_api_key

4. Limit the Scope of Environment Variables

Set environment variables only for the scope where they are needed. Avoid setting them globally unless absolutely necessary.

Example of setting an environment variable for a single command:

DATABASE_URL=postgres://user:password@localhost:5432/mydatabase python app.py

5. Validate Environment Variables

Always validate the presence and correctness of environment variables at the start of your application. This helps in catching configuration errors early.

Example in Python:

import os

def get_env_variable(var_name):
    try:
        return os.environ[var_name]
    except KeyError:
        raise EnvironmentError(f"Set the {var_name} environment variable")

6. Use Default Values

When appropriate, provide default values for environment variables. This ensures your application can run with sensible defaults even if some variables are not set.

Example in a shell script:

DATABASE_URL=${DATABASE_URL:-"postgres://user:password@localhost:5432/mydatabase"}
echo $DATABASE_URL

7. Document Environment Variables

Maintain clear documentation for all required environment variables. This documentation should include the variable names, their purpose, and example values.

Example documentation:

DATABASE_URL: URL for the database connection. Example: postgres://user:password@localhost:5432/mydatabase
API_KEY: API key for accessing the service. Example: your_api_key

Conclusion

Proper management of environment variables is critical for the security and maintainability of your applications. By following these best practices, you can ensure that your environment variables are handled safely and effectively.