Skip to main content

Module secrets

Module secrets 

Source
Expand description

Application secrets, declared at module scope and resolved from the runtime.

use encore::secrets::Secret;

static API_KEY: Secret = Secret::new("ApiKey");

fn authorization() -> String {
    format!("Bearer {}", *API_KEY.value())
}

§Scope

A secret’s declaration determines which services own and can access it:

  • Secret::new("ApiKey") is private to the service that declares it. Two services can each declare a secret with the same name and hold different values, so adding a secret to one service never collides with or silently reuses another service’s secret. Service-scoped secrets must be declared inside a service.
  • Secret::new("ApiKey").shared() has a single value for the entire application. Any service can declare it, and Encore grants access to each service that reads it.
  • Secret::new("ApiKey").global() has a single value for the entire application and is available to every service without per-service grants.

Because Encore parses both the name and scope statically from source code, write them directly in the declaration.

§Values

Secret::value returns a Value, a lightweight handle that dereferences to the underlying secret value and is cheap to clone. Each secret is read once per process and does not change while the process runs; updated values take effect on restart.

Locally (under encore run and encore test), an unset secret evaluates to the type’s default value (""), the same as an empty string. This lets you check if API_KEY.value().is_empty() to skip optional integrations that are not configured locally.

In all other environments, reading an unset secret panics — as does reading a secret whose value cannot be loaded or is not valid UTF-8. Because the panic occurs on read, only the request or task that accesses the secret fails. The panic message includes the secret’s name, never its value.

Currently, String is the only supported secret value type.

§In a config

A config struct can include a secret field by annotating it with the secret name: #[config(secret = "StripeKey")] api_key: Secret. The secret inherits the config’s scope and is declared in code like any other secret. The config value itself never contains the secret; calling Secret::value on the field reads the secret at runtime.

§Tests

Under encore test, a test can override a secret’s value for itself without affecting other tests using testing::set_secret.

Structs§

Secret
An application secret declared as a module-level static.
Value
A handle to a secret’s value.

Traits§

SecretValue
A type that a secret value can be decoded into.