How to Store Private Keys as Environment Variables
When working with private keys (like JWT auth keys, API certificates, or SSH keys), you often need to store them as environment variables instead of keeping them in your code.
Why use environment variables?
- Keep secrets out of your codebase
- Different keys for different environments (dev, staging, prod)
- Better security practices
Problem: Private keys contain newlines and special characters that don't work well in environment variables.
Solution: Encode them as Base64 first.
Step 1: Convert Your Private Key to Base64
// Your private key (example: Apple Sign In JWT key)
const privateKey = `-----BEGIN PRIVATE KEY-----.................-----END PRIVATE KEY-----`;
// Convert to Base64
const base64Key = Buffer.from(privateKey).toString('base64');
console.log(base64Key);
Copy the output - this is what you'll save as your environment variable.
Step 2: Save as Environment Variable
Add to your .env
file:
PRIVATE_KEY=LS0tLS1CRUdJTiBQUklWQVRFIEtFFRRUZBQVNDQkswQ...
Step 3: Use in Your Code
// Decode the Base64 back to the original private key
const privateKey = Buffer.from(process.env.PRIVATE_KEY, 'base64').toString('ascii');
// Now you can use it normally
console.log(privateKey);
// Outputs: -----BEGIN PRIVATE KEY-----.................-----END PRIVATE KEY-----
Quick Reference
Encode: Buffer.from(key).toString('base64')
Decode: Buffer.from(process.env.KEY, 'base64').toString('ascii')