H
Hono3mo ago
Chicha

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 ?
No description
8 Replies
terenced
terenced3mo ago
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.
Nico
Nico3mo ago
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
terenced
terenced3mo ago
ah interesting, I didn't know that! Thank you @Nico 😄
Chicha
Chicha3mo ago
@Nico this is how i fix it
Chicha
Chicha3mo ago
No description
Nico
Nico3mo ago
That looks good, use await next instead of return next in your middleware. Middleware don’t need returns
Chicha
Chicha3mo ago
ok thanks
predaytor
predaytor3mo ago
for type infer use:
export type ContextEnv = {
Bindings: Required<Env>;
Variables: {
user: User | null;
session: Session | null;
};
};

const app = new Hono<ContextEnv>();
export type ContextEnv = {
Bindings: Required<Env>;
Variables: {
user: User | null;
session: Session | null;
};
};

const app = new Hono<ContextEnv>();