---
name: encrypting-env-files
description: Encrypt .env files with dotenvx so they can be committed, keep .env.keys out of Git, and decrypt the values only at run time. Covers set, encrypt, run, the private keys in CI, and the Git filter that dotenvx protect installs. Use when adding or changing encrypted environment files, or running a command with them.
license: MIT
compatibility: Requires @dotenvx/dotenvx 2. Tested with 2.38.
metadata:
author: famiglio
category: tooling
---
# Encrypting Env Files
Encrypt each `.env` file with a public key, commit it, and decrypt it in memory when the application starts. The private keys stay in `.env.keys`, which never enters Git.
## Prerequisites
- `.env.keys` and `.env.local` are in `.gitignore` before you encrypt anything.
## Procedure
1. **Set values through dotenvx**, so they are encrypted when written. The first call creates the key pair:
```bash
pnpm exec dotenvx set DATABASE_URL "postgresql://…"
pnpm exec dotenvx set API_KEY "…" -f .env.production
```
To encrypt a file written by hand, run `pnpm exec dotenvx encrypt -f <file>`.
2. **Commit the encrypted files**, such as `.env` and `.env.production`. Each one has a `DOTENV_PUBLIC_KEY` header and `encrypted:` values. Use one key pair for each environment.
3. **Never commit `.env.keys`,** and never copy it into an image or a build artifact. People share it through a password manager.
4. **Run with the values:**
```bash
pnpm exec dotenvx run -f .env.production -- node dist/index.js
```
In CI and on servers, set only the private key of that environment, such as `DOTENV_PRIVATE_KEY_PRODUCTION`, as a platform secret.
<!-- ‹guest · 2026-12-05› -->
5. **Never print decrypted values.** Do not run `dotenvx get` or `dotenvx decrypt` where the output is logged, including an agent's transcript.
6. **Ask before you run `dotenvx protect`** or `dotenvx ext precommit`, which calls it in version 2. It changes the person's global Git setup, not the project: it adds a required `dotenvx.protect` filter to `~/.gitconfig`, and `.env*` patterns to `~/.config/git/attributes`. The filter holds the absolute path of the dotenvx that ran it, so run it from a global install, never from a temporary folder. Then `git add` fails for a `.env` file with plain values, in every repository.
## Verification
```bash
git check-ignore .env.keys
git ls-files | grep -E '(^|/)\.env\.keys$' || echo "No .env.keys in Git."
grep -L 'encrypted:' $(git ls-files '*.env' '.env*' | grep -v -E '\.example$') || true
```
The first command prints `.env.keys`, the second finds none, and the third lists no tracked file without encrypted values.
این نسخه با نشانهگذاری اختصاصی حساب شما نمایش داده میشود. برای نصب سریع، به تب نصب و راهاندازی بروید.