Skip to main content

alchemy.secret()

Wraps a sensitive value so it will be encrypted when stored in state files. Requires a password to be set either globally in the alchemy application options or locally in an alchemy.run() scope.

Signature

Parameters

T
required
The sensitive value to encrypt in state files. Cannot be undefined.
string
Optional name for the secret. Used for debugging and logging. If not provided, an auto-generated name will be used.

Returns

Secret<T>
A Secret wrapper that encrypts the value when serialized to state files.
T
The unwrapped sensitive value. Only accessible in code, never stored in state files.
string
The name of the secret.
'secret'
Type identifier for the Secret wrapper.

Environment Variable Helper

alchemy.secret.env

A convenient helper for creating secrets from environment variables with better error messages.
Advantages over alchemy.secret(process.env.X):
  • Automatically throws if the environment variable is not set
  • Provides clear error messages with the variable name
  • More concise syntax

Password Configuration

Secrets require a password for encryption/decryption. The password can be provided in two ways:

Global Password

Set a password when creating the application scope:

Scoped Password

Set a password for a specific scope using alchemy.run():

Secret Class

The Secret class provides static methods for working with secrets:

Secret.wrap()

Ensures a value is wrapped in a Secret.
T | Secret<T>
required
The value to wrap. If already a Secret, returns it unchanged.
Example:

Secret.unwrap()

Unwraps a Secret if it is wrapped, otherwise returns the value.
T | Secret<U>
required
The value to unwrap.
Example:

Type Guard

isSecret()

Checks if a value is a Secret wrapper.
any
required
The value to check.
Returns: true if the value is a Secret, false otherwise. Example:

Examples

Basic Usage

Using Environment Variable Helper

Flexible Input Types

State File Representation

When secrets are stored in state files (.alchemy/{stage}/{resource}.json), they are encrypted:

Scoped Secrets

Error Recovery

If you lose the encryption password, you can use --erase-secrets to recover:

Security Best Practices

  1. Never commit passwords to version control: Store passwords in environment variables or use a secret management service.
  2. Use different passwords for different stages:
  3. Rotate passwords periodically: Update your password and redeploy to re-encrypt all secrets.
  4. Use alchemy.secret.env for better error messages:
  5. Don’t log or print secrets: