Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

local development with secrets

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!

like image 580
Justin Beckwith Avatar asked Mar 09 '26 22:03

Justin Beckwith


1 Answers

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:

  1. put the secret in .dev.vars files
API_KEY_0 = "YOU_SECRET_0"
API_KEY_1 = "YOU_SECRET_1"
  1. run the command below and you can see this in terminal.
$ wrangler dev

...

Your worker has access to the following bindings:
- Vars:
  - API_KEY_0: "(hidden)"
  - API_KEY_1: "(hidden)"

...
  1. you code in .ts or .js
interface 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

like image 180
Tom Avatar answered Mar 14 '26 21:03

Tom



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!