use Context to get vars from wrangler.toml
how can fix this code. i want to use my openaiApiKey from the wrangler.toml when i create an openai instance. but i cannot use the context . how can i fix it ?
8 Replies
Hey! I’m new to Hono, but think there might be some confusion around context and environment variables. Hono pass a context with each request and it should only contain info related to the request, like headers. In your wrangler.toml, you are setting environment variables, which are available wherever your code it running. Think of it like a global variable set by the environment. Have a look at https://developers.cloudflare.com/workers/configuration/environment-variables/ and https://hono.dev/api/context. I hope this helps (and that I am actually right 😊)
Cloudflare Docs
Environment variables · Cloudflare Workers docs
Attach text strings and JSON values as environment variables to your Worker.
You are right when it comes to working in Cloudflare, however, since we don't have access to that fetch request in Hono we can't access the env variables. That is why they are only available in the context.
In your case you would probbaly want to put this in a middleware for all routes
If you can give me an example of what you are tyring to do with it we can place it in the most optimal area
ah interesting, I didn't know that! Thank you @Nico 😄
@Nico this is how i fix it
That looks good, use await next instead of return next in your middleware. Middleware don’t need returns
ok thanks
for type infer use: