Skip to main content
coreydaley.dev

Keep API keys out of .env files with the macOS keychain

A .env file is a plaintext list of your secrets sitting in your project folder. It’s convenient, and it’s one git add . away from being public. Every Mac already has an encrypted alternative that scripts can read: the login keychain, through the built-in security command.

Store a key in the keychain

security add-generic-password -a "$USER" -s openai-api-key -w

Putting -w last makes security prompt for the value, so the key never lands in your shell history. -s is the name you’ll look it up by. Add -U to replace a key that’s already stored.

Read it back

security find-generic-password -s openai-api-key -w

-w prints only the value. If macOS asks whether to allow access, choose Always Allow to skip the prompt for that program from then on.

Load keys into your shell

Export keys when a shell starts, in ~/.zshrc:

export OPENAI_API_KEY="$(security find-generic-password -s openai-api-key -w)"

Or only inside one project. With direnv, put the same line in the project’s .envrc, and the key is set while you’re in that folder and unset when you leave. The .envrc contains the command, not the key, so committing it by mistake doesn’t leak anything.

Trade-offs

  • The value is still in the environment of the shell and every program it starts. That’s how most tools expect to receive keys; it’s just no longer in a file.
  • The login keychain stays on this Mac. It doesn’t sync to your other Macs.
  • Teams and CI need a shared secret store, such as GitHub Actions secrets or a cloud secrets manager. The keychain is for your own machine.
  • Password managers with a command-line tool, like 1Password’s op, can do the same job across devices.

Where Secret Store fits

Secret Store is for keys you copy and paste by hand: into a dashboard, a config screen, or a teammate’s setup. It syncs through iCloud Keychain and clears the clipboard after 90 seconds, but it doesn’t have a command-line tool, and the security command can’t read its items. For keys a script loads, use the login keychain as above; for the ones you paste, use Secret Store.

Download on the App Store

Free on Mac, iPhone and iPad. No in-app purchases, no limits, no account.