Workers not getting access to the env object

I created a cloudflare worker, added my openai secret key with npx wrangler secret put OPENAI_API_KEY then input the value. Deployed. Started the local devserver but i keep getting this error you can see in the screenshot. I verified on my cloudflare dashboard that the environment variable existed. Even deleted it, revoked that openai key and added a new one just to ensure it wasnt the value that was wrong and i still cant get it to run. I tried throwing in a console.log and it seems that it cannot access the environment. In the meantime ive created a .dev.vars file and included my OPENAI_API_KEY = myvalue in there and its working now for development but im worried about production. so connectingh to openai with that key , just from .dev.vars instead of the env object. one other question is where can i find the worker url endpoint for the deployed/live version? its only giving me the url of localhost at port 8787 Why isnt it loading my environment variables when cloudflare dashboard recognizes that its been set? Here is my code
import OpenAI from 'openai';

export default {
async fetch(request, env, ctx) {
const openai = new OpenAI({
apiKey: env.OPENAI_API_KEY
})
console.log("secret key: ", env.OPENAI_API_KEY)

try {
const chatCompletion = await openai.chat.completions.create({
model: 'gpt-4o-mini',
messages: [{ role: 'user', content: 'Give me one fact about chow chow dogs.'}],
temperature: 1.1,
presence_penalty: 0,
frequency_penalty: 0
})

const response = chatCompletion.choices[0].message;
return new Response(JSON.stringify(response));
} catch(e) {
return new Response(e)
}
},
};
import OpenAI from 'openai';

export default {
async fetch(request, env, ctx) {
const openai = new OpenAI({
apiKey: env.OPENAI_API_KEY
})
console.log("secret key: ", env.OPENAI_API_KEY)

try {
const chatCompletion = await openai.chat.completions.create({
model: 'gpt-4o-mini',
messages: [{ role: 'user', content: 'Give me one fact about chow chow dogs.'}],
temperature: 1.1,
presence_penalty: 0,
frequency_penalty: 0
})

const response = chatCompletion.choices[0].message;
return new Response(JSON.stringify(response));
} catch(e) {
return new Response(e)
}
},
};
No description
No description
3 Replies
Cyb3r-Jak3
Cyb3r-Jak34mo ago
Your local worker doesn’t load your deployed environment variables by design. You can see the endpoints in the dashboard under the triggers section
clevermissfox
clevermissfoxOP4mo ago
So for local testing is there another approach to make sure it’s using the env vars ? Or should I just keep using .dev.vars for development and know that when it’s deployed and it’s the production server , it will load the env variables that are set
Cyb3r-Jak3
Cyb3r-Jak34mo ago
Use the .dev.vars. When you run dev it will tell you what variables are set
Want results from more Discord servers?
Add your server