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
We follow Cloudflare’s recommended approach for workers.
Development
Create a .dev.vars
file in the root of your project.
SECRET_KEY = "value";API_TOKEN = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
This file will be used when you run the development server.
Updating Types
After you add our environment variable, run:
npx wrangler types
This adds the environment variable and associated type to worker-configuration.d.ts
and avoids unknown types when accessing env
.
// Generated by Wrangler by running `wrangler types`// Runtime types generated with ....declare namespace Cloudflare { interface Env { SECRET_KEY: string API_TOKEN: string }}
Note: Simply running
pnpm dev
will not generate these runtime types.
Secrets on deployed Workers
npx wrangler secret put <KEY>
These can also be added via the Cloudflare dashboard.