Skip to content

Secrets

Background

Secrets are a type of binding that allow you to attach encrypted text values to your Worker. Secrets are used for storing sensitive information like API keys and auth tokens.

You can access secrets in your Worker code through:

Access your secrets with Workers

Secrets can be accessed from Workers as you would any other environment variables. For instance, given a DB_CONNECTION_STRING secret, you can access it in your Worker code through the env parameter:

index.jsjs
import postgres from "postgres";

export default {
	async fetch(request, env, ctx) {
		const sql = postgres(env.DB_CONNECTION_STRING);

		const result = await sql`SELECT * FROM products;`;

		return new Response(JSON.stringify(result), {
			headers: { "Content-Type": "application/json" },
		});
	},
};

You can also import env from cloudflare:workers to access secrets from anywhere in your code, including outside of request handlers:

import { env } from "cloudflare:workers";
import postgres from "postgres";

// Initialize the database client at the top level using a secret
const sql = postgres(env.DB_CONNECTION_STRING);

export default {
	async fetch(request) {
		const result = await sql`SELECT * FROM products;`;

		return new Response(JSON.stringify(result), {
			headers: { "Content-Type": "application/json" },
		});
	},
};
import { env } from "cloudflare:workers";
import postgres from "postgres";

// Initialize the database client at the top level using a secret
const sql = postgres(env.DB_CONNECTION_STRING);

export default {
	async fetch(request: Request): Promise<Response> {
		const result = await sql`SELECT * FROM products;`;

		return new Response(JSON.stringify(result), {
			headers: { "Content-Type": "application/json" },
		});
	},
};

For more details on accessing env globally, refer to Importing env as a global.

Local Development with Secrets

Put secrets for use in local development in either a .dev.vars file or a .env file, in the same directory as the Wrangler configuration file.

These files should be formatted using the dotenv ↗︎ syntax. For example:

.dev.vars / .envbash
SECRET_KEY="value"
API_TOKEN="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9"

When secrets.required is configured alongside vars, local files can supply both declared secrets and overrides for configured vars, while unrelated keys are ignored:

{
	"vars": {
		"LOG_LEVEL": "info",
	},
	"secrets": {
		"required": ["API_TOKEN"],
	},
}
[vars]
LOG_LEVEL = "info"

[secrets]
required = [ "API_TOKEN" ]
.env / .dev.varsbash
API_TOKEN="local-token"     # Loaded (declared in secrets.required)
LOG_LEVEL="debug"           # Loaded (overrides configured vars.LOG_LEVEL)
UNDECLARED_KEY="ignored"    # Excluded (not in secrets.required or vars)

To set different secrets for each Cloudflare environment, create files named .dev.vars.<environment-name> or .env.<environment-name>.

When you select a Cloudflare environment in your local development, the corresponding environment-specific file will be loaded ahead of the generic .dev.vars (or .env) file.

  • When using .dev.vars.<environment-name> files, all secrets must be defined per environment. If .dev.vars.<environment-name> exists then only this will be loaded; the .dev.vars file will not be loaded.
  • In contrast, all matching .env files are loaded and the values are merged. For default file selection, each key takes the value from the highest-precedence file that defines it, in the following order (highest to lowest):
    • .env.<environment-name>.local (most specific)
    • .env.<environment-name>
    • .env.local
    • .env (least specific)

Secrets on deployed Workers

Move a value between a variable and a secret

Variables and secrets use the same set of binding names. A Worker version cannot define both a variable and a secret with the same name. Adding a secret while a variable still uses that name fails with a binding-name conflict.

Deploying a variable with the same name as an existing secret does not fail. The variable replaces the secret, and the secret is deleted.

Renaming a binding also changes its env property. Code that still reads the old name receives undefined once that binding is removed.

To change a variable to a secret, or a secret to a variable:

  1. Create the new binding under a new name. For example, create an API_TOKEN_SECRET secret to replace an API_TOKEN variable. Only use a plaintext variable for values that are safe to expose in configuration. If you use secrets.required, add the new secret name to that list.
  2. Update your code, such as env.API_TOKEN → env.API_TOKEN_SECRET, and deploy.
  3. Remove the old binding after the new version works. If it was a secret, remove its name from secrets.required too.

Update your local secrets to use the new name too.

Validate secrets before deploy

You can declare the secret names your Worker requires using the secrets configuration property in your Wrangler configuration. When defined, wrangler deploy and wrangler versions upload will fail with a clear error if any required secrets are not configured on the Worker.

Add TypeScript types for optional secrets

secrets.required validates presence at deployment. Do not add an optional secret to that list just to generate its type.

Declare optional secrets in your own interface that extends your generated Env:

interface AppEnv extends Env {
  OPTIONAL_API_TOKEN?: string;
}

Use AppEnv in your handler and check for undefined before using the value. This type does not create or load the secret.

If secrets.required is set, undeclared keys in .dev.vars and .env are excluded unless they override an existing key in vars. Optional secrets outside secrets.required (and not configured in vars) are not loaded from local files. To test those secrets with local files, use a local-only configuration without secrets.required. Refer to Local Development with Secrets.

Adding secrets to your project

Via Wrangler

Secrets can be added through wrangler secret put or wrangler versions secret put commands.

wrangler secret put creates a new version of the Worker and deploys it immediately.

npx wrangler secret put <KEY>

If using gradual deployments, instead use the wrangler versions secret put command. This will only create a new version of the Worker, that can then be deployed using wrangler versions deploy.

npx wrangler versions secret put <KEY>

Via the dashboard

To add a secret via the dashboard:

  1. In the Cloudflare dashboard, go to the Workers & Pages page.

    Go to Workers & Pages ↗
  2. In Overview, select your Worker > Settings.

  3. Under Variables and Secrets, select Add.

  4. Select the type Secret, input a Variable name, and input its Value. This secret will be made available to your Worker but the value will be hidden in Wrangler and the dashboard.

  5. (Optional) To add more secrets, select Add variable.

  6. Select Deploy to implement your changes.

Upload secrets alongside code

You can upload secrets at the same time as your Worker code using the --secrets-file flag on wrangler deploy or wrangler versions upload. This accepts a path to a JSON or .env file — the same formats accepted by wrangler secret bulk. You can upload up to 100 secrets per bulk request for a single version.

npx wrangler deploy --secrets-file .env.production
npx wrangler versions upload --secrets-file secrets.json

Secrets not included in the file are preserved from the previous version. This is useful in CI/CD pipelines where you want to deploy code and update secrets in a single operation.

Delete secrets from your project

Via Wrangler

Secrets can be deleted through wrangler secret delete or wrangler versions secret delete commands.

wrangler secret delete creates a new version of the Worker and deploys it immediately.

npx wrangler secret delete <KEY>

If using gradual deployments, instead use the wrangler versions secret delete command. This will only create a new version of the Worker, that can then be deployed using wrangler versions deploy.

npx wrangler versions secret delete <KEY>

Via the dashboard

To delete a secret from your Worker project via the dashboard:

  1. In the Cloudflare dashboard, go to the Workers & Pages page.

    Go to Workers & Pages ↗
  2. In Overview, select your Worker > Settings.

  3. Under Variables and Secrets, select Edit.

  4. In the Edit drawer, select X next to the secret you want to delete.

  5. Select Deploy to implement your changes.

  6. (Optional) Instead of using the edit drawer, you can click the delete icon next to the secret.

Compare secrets and environment variables

Secrets are environment variables. The difference is secret values are not visible within Wrangler or Cloudflare dashboard after you define them. This means that sensitive data, including passwords or API tokens, should always be encrypted to prevent data leaks. To your Worker, there is no difference between an environment variable and a secret. The secret's value is passed through as defined.

  • Wrangler secret commands - Review the Wrangler commands to create, delete and list secrets.
  • secrets configuration property - Declare required secret names in your Wrangler configuration. Used for validation during local development and deploy, and as the source of truth for type generation.
  • Cloudflare Secrets Store - Encrypt and store sensitive information as secrets that are securely reusable across your account.

Was this helpful?