Imagine finishing a web application on your local machine. Everything works perfectly. Your database connection is successful, API integrations respond correctly, and the application runs without errors.
You deploy the same application to production, but suddenly the database connection fails. An external API returns an authentication error, or the application starts using the wrong payment gateway credentials.
What happened?
In many cases, the problem is not your application code. It is the configuration.
Every application depends on settings that change depending on where it runs. These settings include database credentials, API endpoints, email server details, payment gateway keys, application modes, and many others.
Managing these settings directly inside source code creates unnecessary maintenance and security problems.
This is why developers use environment variables.
In this guide, we will explain what environment variables are, how they work, how to use them in PHP, Laravel, and Node.js, and how to manage application secrets safely across different environments.
What Are Environment Variables?
Environment variables are named values made available to an application by the environment in which it runs.
Think of them as external settings that your application can read whenever it needs configuration information.
For example, an application might require:
APP_ENV=production
APP_DEBUG=false
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=store_database
DB_USERNAME=store_userInstead of writing these values directly into application code, you can read them dynamically.
Your application remains the same, but its configuration can change depending on the environment.
For example:
Configuration | Development | Production |
|---|---|---|
APP_ENV | local | production |
APP_DEBUG | true | false |
DB_HOST | localhost | production database host |
DB_DATABASE | development_db | production_db |
MAIL_MAILER | log | smtp |
PAYMENT_MODE | sandbox | live |
This makes it easier to maintain one codebase across multiple environments.
Why Are Environment Variables Important?
Environment variables are useful for several reasons.
1. Separate configuration from application code
Your application logic should not depend on hardcoded server addresses, database credentials, or API endpoints.
Keeping configuration separate makes the code easier to maintain and deploy.
For example, instead of writing:
$databaseHost = "192.168.1.100";You can use:
$databaseHost = getenv('DB_HOST');The application reads the value from its runtime environment.
2. Protect sensitive information
Applications frequently need credentials such as:
Database usernames and passwords.
Payment gateway API keys.
SMTP credentials.
Third-party API tokens.
Encryption keys.
Cloud service credentials.
Hardcoding these values creates a risk of accidentally exposing them through source control, code reviews, or shared repositories.
Environment-based configuration helps separate these credentials from application code.
However, environment variables are not automatically a secure secrets vault. Their visibility and exposure depend on the operating system, hosting platform, processes, and deployment configuration.
3. Simplify deployment
The same application can run in development, staging, and production without maintaining separate source code versions.
Only the environment-specific configuration needs to change.
4. Make application maintenance easier
When an API endpoint changes or a database server is migrated, developers can update the configuration without modifying application logic.
This reduces unnecessary code changes and deployment risks.
Understanding the .env File
One of the most common ways developers manage environment variables is through a .env file.
A .env file contains configuration values written as key-value pairs.
Example:
APP_NAME=MyApplication
APP_ENV=local
APP_DEBUG=true
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=my_database
DB_USERNAME=root
DB_PASSWORD=local_password
MAIL_HOST=smtp.example.com
MAIL_PORT=587The application uses a suitable environment-variable loader or framework integration to read these values.
A .env file is particularly useful during local development because it allows each developer to maintain their own configuration without changing shared application code.
What is the difference between .env and environment variables?
These terms are related, but they are not exactly the same.
An environment variable is a value supplied to a running process by its execution environment.
A .env file is simply a text file that a library, framework, or deployment process can read and use to populate configuration values.
For example, a PHP application using a dotenv library can load values from a .env file into the application's environment.
A production hosting platform can also supply environment variables directly without requiring a .env file.
How to Use Environment Variables in PHP
PHP provides built-in functions for reading environment variables.
One common option is getenv().
Example:
<?php
$databaseHost = getenv('DB_HOST');
echo $databaseHost;You can also use $_ENV when the relevant PHP environment configuration makes those values available.
<?php
$environment = $_ENV['APP_ENV'] ?? 'local';
echo $environment;For safer application configuration, provide sensible defaults for non-sensitive settings and validate required configuration during application startup.
Example:
<?php
$databaseHost = getenv('DB_HOST');
if (!$databaseHost) {
throw new RuntimeException(
'DB_HOST environment variable is missing.'
);
}This makes configuration errors easier to identify instead of allowing an application to fail later during a database operation.
Using environment variables in PHP without a framework
If you are building a plain PHP application, you can use a dotenv library such as vlucas/phpdotenv.
Install it through Composer:
composer require vlucas/phpdotenvLoad the environment configuration:
<?php
require_once __DIR__ . '/vendor/autoload.php';
$dotenv = Dotenv\Dotenv::createImmutable(__DIR__);
$dotenv->load();
$databaseHost = $_ENV['DB_HOST'] ?? null;Your .env file might contain:
DB_HOST=127.0.0.1
DB_DATABASE=application_db
DB_USERNAME=root
DB_PASSWORD=local_passwordThe dotenv library loads these values into the application environment.
Note that createImmutable() does not overwrite existing process environment variables by default. This is useful because deployment-provided values can take precedence over local defaults.
How to Use Environment Variables in Laravel
Laravel provides built-in support for environment configuration through the .env file.
When you create a Laravel application, a .env file is generally generated from .env.example.
Example:
APP_NAME=LaravelApp
APP_ENV=local
APP_KEY=base64:your_application_key
APP_DEBUG=true
APP_URL=http://localhost
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_db
DB_USERNAME=root
DB_PASSWORD=secretLaravel uses these values through its configuration system.
For example, the database configuration file can access environment variables:
'mysql' => [
'driver' => 'mysql',
'host' => env('DB_HOST', '127.0.0.1'),
'database' => env('DB_DATABASE', 'laravel'),
'username' => env('DB_USERNAME', 'root'),
'password' => env('DB_PASSWORD', ''),
],Important Laravel best practice
Avoid calling env() directly throughout controllers, services, or business logic.
Instead, read environment values inside configuration files and access the resulting configuration through Laravel's config() helper.
For example:
$databaseHost = config('database.connections.mysql.host');Why?
Laravel's configuration caching changes how configuration is loaded. When configuration is cached, the .env file is not loaded in the usual way during requests or Artisan commands.
After changing production configuration, you may need to rebuild the configuration cache:
php artisan config:clear
php artisan config:cacheThis is an important detail when deploying Laravel applications.
How to Use Environment Variables in Node.js
Node.js provides built-in access to environment variables through process.env.
Example:
const port = process.env.PORT || 3000;
const environment = process.env.NODE_ENV || 'development';
console.log(`Application running on port ${port}`);
console.log(`Environment: ${environment}`);You can provide environment variables when starting an application.
For example, on Linux or macOS:
APP_ENV=production PORT=8080 node app.jsFor applications that use a .env file, a package such as dotenv can load configuration.
Install it:
npm install dotenvLoad it near the beginning of your application:
require('dotenv').config();
const databaseHost = process.env.DB_HOST;
console.log(databaseHost);Example .env file:
APP_ENV=development
PORT=3000
DB_HOST=localhost
DB_DATABASE=node_app
DB_USERNAME=root
DB_PASSWORD=local_passwordNode.js also supports native environment-file loading in modern releases, so an additional package is not always necessary. Check the Node.js documentation for the exact options supported by your runtime version.
Development vs. Staging vs. Production
A common mistake is using the same configuration across every environment.
Different environments have different purposes, and their configuration should reflect those differences.
Development environment
This is where developers build and test features.
Typical settings include:
Local database connections.
Debugging enabled.
Test API credentials.
Local email logging.
Detailed error reporting.
Staging environment
Staging should represent production as closely as practical.
It is generally used for:
QA testing.
Integration testing.
User acceptance testing.
Release verification.
Performance checks.
Staging should use separate credentials and test accounts, not production secrets copied for convenience.
Production environment
Production serves real users and handles actual business operations.
Typical settings include:
Production database credentials.
Live payment gateway credentials.
Debugging disabled.
Production API endpoints.
Restricted access to sensitive configuration.
Centralized error monitoring.
The important rule is simple: each environment should have its own configuration and appropriately scoped credentials.
Common Environment Variable Mistakes Developers Should Avoid
Environment variables simplify configuration, but incorrect handling can create security and operational problems.
Here are some common mistakes.
1. Committing the .env File to Git
One of the most dangerous mistakes is accidentally committing a .env file containing actual credentials.
For example:
DB_PASSWORD=my_real_database_password
PAYMENT_API_KEY=live_secret_keyIf this file reaches a public repository, the credentials may be exposed.
Add .env to your .gitignore file:
.env
.env.*
!.env.exampleThis is a useful starting point, but check your project conventions and ensure that only files intended to be excluded are ignored.
If a secret has already been committed, removing the file in a later commit is not enough. Rotate the exposed credential and address its presence in repository history.
2. Using Production Credentials in Development
Never use production database credentials or live payment keys simply because they make local testing easier.
Use separate development credentials and sandbox accounts.
This reduces the impact of accidental requests and unintended data modifications.
3. Exposing Secrets in Frontend Code
This is particularly important for React, Vue, Angular, and other frontend applications.
Frontend applications execute in the user's browser. Any configuration bundled into browser-delivered JavaScript should be considered public.
For example:
VITE_API_URL=https://api.example.com
VITE_PAYMENT_SECRET=actual_secret_keyA public API URL is fine, but a private payment secret must never be exposed through a frontend build.
Some frameworks use prefixes such as VITE_ or NEXT_PUBLIC_ to identify values that are intentionally exposed to the browser.
Never use those public prefixes for private credentials.
Keep sensitive operations on the server.
4. Forgetting to Configure Production Variables
An application may work perfectly on a developer's computer because all required settings exist locally.
After deployment, a missing DB_HOST or API_KEY can prevent the application from starting.
Create a configuration checklist and validate required settings during application startup.
5. Logging Sensitive Values
Avoid logging complete database connection strings, passwords, API tokens, or authorization headers.
For example, do not do this:
console.log(process.env.PAYMENT_API_KEY);Logs are often accessible to more people and systems than the application secrets themselves.
Log the configuration key name or a safe status message instead.
6. Building Secrets into Docker Images
Avoid putting actual secrets into Docker build arguments or image environment instructions.
Build arguments and image configuration can leave sensitive information in build metadata, image layers, or inspection output.
Provide runtime configuration through the deployment platform or a suitable secrets-management mechanism.
Best Practices for Managing Environment Variables
If you are maintaining an application in a production environment, follow these practices.
1. Maintain an .env.example file
Keep a sample configuration file in source control.
Example:
APP_NAME=MyApplication
APP_ENV=local
APP_DEBUG=true
DB_HOST=
DB_DATABASE=
DB_USERNAME=
DB_PASSWORD=
PAYMENT_API_KEY=Use placeholder values rather than actual credentials.
2. Use separate credentials for every environment
Development, staging, and production should not share the same database passwords or API secrets.
3. Validate required configuration
Check that mandatory configuration values exist before processing requests.
4. Keep secrets outside source control
Never commit private API keys, database passwords, or production credentials.
5. Use a dedicated secrets manager for production
For sensitive production systems, consider services such as AWS Secrets Manager, Azure Key Vault, Google Cloud Secret Manager, or HashiCorp Vault.
These systems can provide access controls, audit logging, and secret rotation capabilities.
6. Apply least-privilege access
An application should only have access to the credentials and permissions it actually needs.
7. Rotate compromised credentials immediately
If an API key or database password is exposed, revoke or rotate it. Deleting the value from a file does not invalidate the original credential.
8. Never assume environment variables are completely secret
Depending on the hosting environment, they may be visible to privileged users, processes, debugging tools, or diagnostic output.
For high-value credentials, use your platform's recommended secret injection or retrieval mechanism.
How to Troubleshoot Environment Variable Issues
When an application cannot connect to a database or an external API, configuration should be one of the first things you inspect.
Here is a simple troubleshooting checklist.
Problem | What to check |
|---|---|
Database connection failed | DB_HOST, DB_PORT, DB_DATABASE |
Authentication failed | DB_USERNAME, DB_PASSWORD |
API returns unauthorized | API key, token, environment |
Wrong API endpoint | API_BASE_URL |
Configuration changes not applied | Runtime configuration cache |
Application fails after deployment | Missing required variables |
Frontend exposes a secret | Public build-time environment variables |
For PHP, you can inspect a variable with:
var_dump(getenv('DB_HOST'));For Node.js:
console.log(process.env.DB_HOST);Do not print actual secrets when troubleshooting production systems. Check whether a value exists or whether a connection succeeds without exposing its contents.
Final Thoughts
Environment variables are a fundamental part of modern web application development.
They help developers separate application logic from environment-specific configuration, simplify deployments, and reduce the risk of exposing sensitive information in source code.
Whether you are working with plain PHP, Laravel, Node.js, or a frontend framework, understanding how environment variables work can save considerable debugging time.
However, remember that a .env file is not a complete security solution. Production applications should use appropriate secret-management facilities, restricted access, and a clear credential rotation process.
Start by reviewing your existing application configuration. Identify hardcoded values, separate development and production credentials, and make sure sensitive information never reaches your public repository or frontend bundle.
Good configuration management is not just about making an application work. It is about making it reliable, maintainable, and secure.
Explore more practical developer resources and online tools at Agilelogics.com.
Frequently Asked Questions
What is an environment variable in simple terms?
An environment variable is an external configuration value that an application reads while running. It can contain settings such as database hosts, application modes, API endpoints, and credentials.
What is the difference between .env and .env.example?
A .env file generally contains the actual local configuration values used by an application. A .env.example file contains sample configuration keys and placeholder values that help other developers set up the project.
Should .env files be committed to Git?
Files containing actual secrets should not be committed to Git. Keep a sanitized .env.example file in the repository instead.
Are environment variables secure for storing passwords?
They are better than hardcoding passwords in source code, but they are not automatically secure. Their exposure depends on the runtime and hosting environment. Dedicated secrets managers are preferable for sensitive production credentials.
Can I use environment variables in PHP?
Yes. PHP provides functions such as getenv() and, depending on configuration, the $_ENV superglobal. You can also use libraries such as vlucas/phpdotenv to load .env files.
What happens if an environment variable is missing?
The application may receive an empty or undefined value, depending on the runtime and how the variable is accessed. Validate required configuration and fail with a clear, safe error message when a required value is missing.
Are frontend environment variables private?
No. Variables included in browser-delivered frontend bundles should be treated as public. Never place database passwords, private API keys, or other server-side secrets in frontend configuration.
Written by
Alex Rivera
AI/ML writer covering AI assistants, coding tools, and generative AI platforms — pricing, capabilities, and how they actually compare.