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)
        }
    },
};
Screenshot_2024-08-19_at_8.52.01_PM.webp
Screenshot_2024-08-19_at_8.49.26_PM.webp
Was this page helpful?