.env.local -
# Example .gitignore entry
.env.local
.env.*.local
// Example dotenv usage
require('dotenv').config( path: '.env.local' )
The most critical rule of .env.local is that it must be ignored by version control.
If you accidentally commit .env.local, you defeat its entire purpose. You will expose secrets to the repository and likely overwrite your teammates' local configurations.
Your .gitignore file should explicitly contain:
# local env files
.env.local
.env.*.local
In the world of modern web development, managing configuration and secrets is a delicate balancing act. You need API keys to test your integration, but you cannot commit those keys to GitHub. You need to toggle features between your machine and the production server, but you don't want to hardcode URLs in your source code. .env.local
Enter .env.local—the unsung hero of the local development environment. It is the bridge between a developer's specific machine setup and the shared codebase.
Suppose you're building a web application that uses a third-party API. You can store the API key in .env.local:
# .env.local
API_KEY=your_secret_api_key_here
In your application code, you can then access the API key using the API_KEY environment variable. # Example
The security model of .env.local is based on exclusion and isolation.
Because .env.local is never stored in the build artifact or deployment container, it reduces the risk of secret leakage through:
# .gitignore
.env
.env.local
By following these practices, you can manage environment-specific settings effectively and securely, keeping sensitive information out of your codebase and version control. // Example dotenv usage require('dotenv')
Because .env.local can override anything, add a validation script at the start of your application. Use libraries like zod to ensure required variables exist.
import z from 'zod';const envSchema = z.object( DATABASE_URL: z.string().url(), API_KEY: z.string().min(1), );
// This will throw a clear error if .env.local is missing a required key const env = envSchema.parse(process.env);