I am following this guide to get secrets added to my prod environment with cloudflare workers:
https://developers.cloudflare.com/workers/platform/environment-variables/#comparing-secrets-and-environment-variables
I am able to add new secrets via wrangler secret put, and I see them in the dashboard. When I run my code locally with wrangler, it doesn't look like the variables are injected. I'm getting an error like this:
Uncaught ReferenceError: TOKEN is not defined
at line 0
at throwFetchError (/Users/justin.beckwith/.nvm/versions/node/v16.14.0/lib/node_modules/wrangler/wrangler-dist/cli.js:134316:17)
at fetchResult (/Users/justin.beckwith/.nvm/versions/node/v16.14.0/lib/node_modules/wrangler/wrangler-dist/cli.js:134287:5)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async previewToken (/Users/justin.beckwith/.nvm/versions/node/v16.14.0/lib/node_modules/wrangler/wrangler-dist/cli.js:134658:29)
at async createWorker (/Users/justin.beckwith/.nvm/versions/node/v16.14.0/lib/node_modules/wrangler/wrangler-dist/cli.js:134675:17)
at async start (/Users/justin.beckwith/.nvm/versions/node/v16.14.0/lib/node_modules/wrangler/wrangler-dist/cli.js:136075:16) {
I know the secret is set, and from what I can tell the values should be auto-injected. Any ideas on what I'm missing here? Thank you!
I got the answer from here. You can create the file named .dev.vars, and put the secrets in file. Wrangler 2 will auto binding when you use the command $ wrangler dev
example:
.dev.vars filesAPI_KEY_0 = "YOU_SECRET_0"
API_KEY_1 = "YOU_SECRET_1"
$ wrangler dev
...
Your worker has access to the following bindings:
- Vars:
- API_KEY_0: "(hidden)"
- API_KEY_1: "(hidden)"
...
.ts or .jsinterface Env {
API_KEY_0: string
API_KEY_1: string
}
export default {
async fetch(request: Request, env: Env, context: ExecutionContext): Promise<Response> {
console.log(env.API_KEY_0, env.API_KEY_1)
}
}
export default {
async fetch(request, env, context) {
console.log(env.API_KEY_0, env.API_KEY_1)
}
}
for your reference
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With