Skip to content
4th April 2025: This is a preview, whilst production-ready, it means some APIs might change

Environment Variables & Secrets

When integrating with external services you typically store your credentials in environment variables. This is done to avoid hardcoding secrets into your codebase.

There are several environments that require different credentials, for example:

  • On your local machine: Development
  • Secrets on deployed Workers: Staging & Production

Development

Create a .env file in the root of your project.

.env
SECRET_KEY = "value";
API_TOKEN = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

Cloudflare uses .dev.vars, however, .env is the typical approach. Therefore, when you run pnpm dev, RedwoodSDK will automatically create a symlink from .env to .dev.vars.

Updating Types

After adding any environment variables, run:

Terminal window
npx wrangler types

This adds the environment variable and associated type to worker-configuration.d.ts and avoids unknown types when accessing env.

worker-configuration.d.ts
// Generated by Wrangler by running `wrangler types`
// Runtime types generated with ....
declare namespace Cloudflare {
interface Env {
SECRET_KEY: string;
API_TOKEN: string;
}
}

Production / Secrets on deployed Workers

To add a secret to a deployed worker, run:

Terminal window
npx wrangler secret put <KEY>

Then, the CLI will prompt you to enter the secret value.

These can also be added and managed via the Cloudflare dashboard.

  1. Expand the Computer (Workers) tab
  2. Click on Workers and Pages
  3. Click on the name of the worker
  4. Click on the “Settings” tab
  5. Click on the “Variables and Secrets” section

Using an Environment Variable

At the top of your file, import env:

import { env } from "cloudflare:workers";

Then, you can access the environment variables through the env object.

const rpID = env.WEBAUTHN_RP_ID ?? new URL(request.url).hostname;

Further Reading