Skip to content
GitHubXDiscordRSS

Secret

Learn how to add individual secrets to Cloudflare Secrets Store for fine-grained secret management.

A Cloudflare Secret creates an individual secret stored in a Secrets Store. If you want to reference an existing Secrets Store secret that was not created using Alchemy, use SecretRef.

import { Secret } from "alchemy/cloudflare";
const mySecret = await Secret("my-secret", {
value: alchemy.secret(process.env.MY_SECRET),
});

Then bind the Secret to your Worker:

export const worker = await Worker("worker", {
bindings: {
MY_SECRET: mySecret,
},
});

And use it at runtime:

import type { worker } from "../alchemy.run.ts";
export default {
async fetch(request, env: typeof worker.Env) {
const secret = await env.MY_SECRET.get();
// ..
},
};

Referencing an Existing Secret (SecretRef)

Section titled “Referencing an Existing Secret (SecretRef)”

Use SecretRef to bind an existing secret by name without creating or updating its value.

import { SecretRef, Worker } from "alchemy/cloudflare";
const apiKeyRef = await SecretRef({ name: "API_KEY" });
const worker = await Worker("worker", {
bindings: {
API_KEY: apiKeyRef,
},
entrypoint: "./src/worker.ts",
url: true,
});

At runtime, it behaves the same:

export default {
async fetch(request, env) {
const key = await env.API_KEY.get();
return new Response(key ? "ok" : "missing");
}
};

By default, the default_secrets_store will be used, but you can also specify your own store.

import { Secret, SecretsStore } from "alchemy/cloudflare";
const store = await SecretsStore("my-store");
const mySecret = await Secret("my-secret", {
store,
value: alchemy.secret(process.env.MY_SECRET),
});

Or, if the secret already exists, reference it with SecretRef and pass the store explicitly:

import { SecretRef, SecretsStore, Worker } from "alchemy/cloudflare";
const store = await SecretsStore("my-store", {
name: "production-secrets",
adopt: true,
});
const apiKeyRef = await SecretRef({
name: "API_KEY",
store,
});