TL;DR - Quick Fix
Run this in your terminal:sed 's/=.*/=/' .env.local > .env.example
The Problem
As developers, we often struggle with maintaining .env.example
files in our repositories. The common workflow goes like this:
- Create a
.env.local
with actual values - Manually copy it to
.env.example
- Remove all sensitive values
- Forget to update
.env.example
when adding new variables - Repeat this process every time
This manual process is:
- Time-consuming
- Error-prone
- Easy to forget
- Often leads to outdated example files
The Solution
Add this one-liner to your package.json
scripts:
{
"scripts": {
"env:gen": "sed 's/=.*/=/' .env.local > .env.example"
}
}
Now you can generate your .env.example
file with a single command:
npm run env:gen
# or
yarn env:gen
# or
pnpm env:gen
How It Works
Let's break down the command:
sed 's/=.*/=/'
: Usessed
to replace everything after=
with nothing.env.local
: Reads from your actual env file> .env.example
: Outputs to the example file
For example, this:
DATABASE_URL=postgresql://user:password@localhost:5432/mydb
API_KEY=1234567890
DEBUG=true
Becomes:
DATABASE_URL=
API_KEY=
DEBUG=
Best Practices
-
Add to Your Development Workflow:
# After adding new env variables npm run env:gen git add .env.example git commit -m "chore: update env example"
-
Git Hooks: Consider adding this to your pre-commit hook to never forget updating the example file.
-
Documentation: Add comments in your
.env.local
file - they'll be preserved in the example:# Database configuration DATABASE_URL=your-value-here # API credentials API_KEY=your-key-here
When to Use This
This command is particularly useful when:
- Starting a new project
- Adding new environment variables
- Sharing your project with other developers
- Maintaining open-source projects
- Ensuring your example stays in sync with actual requirements
Pro Tips
-
Custom Variations:
{ "scripts": { "env:gen": "sed 's/=.*/=/' .env.local > .env.example", "env:gen:dev": "sed 's/=.*/=/' .env.development > .env.development.example", "env:gen:all": "npm run env:gen && npm run env:gen:dev" } }
-
Add Default Values:
NODE_ENV=development DEBUG=false PORT=3000
Note: This command works on Unix-based systems (macOS, Linux). For Windows, you might need to use WSL or alternative commands.