Skip to main content

Managing Secrets

Alchemy provides a built-in Secret system for handling sensitive values like API keys, passwords, and credentials. Secrets are automatically encrypted when stored in state files using a password.

Creating Secrets

Use alchemy.secret() to wrap sensitive values:
Secrets require a password to be set. Without a password, secret operations will fail.

Setting the Password

The password is used to encrypt and decrypt secrets. You can provide it in two ways:

Global Password

Set the password when creating your application:

Environment Variable

Alchemy automatically reads from the ALCHEMY_PASSWORD environment variable:
Never commit your .env file or password to version control. Add .env to .gitignore.

Secret from Environment Variables

Alchemy provides a convenient helper for creating secrets from environment variables:

Using secret.env

Using secret()

Use alchemy.secret.env.VAR_NAME for better error messages when environment variables are missing.

How Secrets Work

Encryption in State Files

When resources are saved to state files (.alchemy/), secrets are automatically encrypted:
The encrypted value can only be decrypted with the correct password.

Secret Lifecycle

Named Secrets

You can assign names to secrets for better debugging:
Named secrets appear in logs and error messages:

Secret Wrapping and Unwrapping

The Secret class provides utilities for working with secret values:

Wrap

Ensure a value is wrapped in a Secret:

Unwrap

Extract the unencrypted value from a Secret:
Be careful when unwrapping secrets. Avoid logging or exposing unencrypted values.

Type Guard

Check if a value is a Secret:

Secret Safety Features

toString Protection

Secrets override toString() to prevent accidental exposure:

console.log Protection

Secrets implement custom inspect for Node.js:
This prevents secrets from accidentally appearing in logs or debug output.

Scoped Secrets

You can use different passwords for different scopes:

Recovering from Lost Passwords

If you lose your encryption password, you can erase secrets and start fresh:
This will treat all secrets as undefined. You’ll need to re-deploy with new secret values.

Best Practices

Example: Complete Secret Setup

Next Steps