I am trying to use OpenAI's API. My code works great when I tested my API key directly in my code, but when I tried moving it to a .env file, it stopped working. I've been trying to figure out what the issue is but cannot figure it out.
Here is my code:
import OpenAI from "openai";
const apiKey: string = process.env.OPENAI_API_KEY;
const assistantId: string = process.env.OPENAI_ASSISTANT_ID;
console.log(apiKey)
console.log(assistantId)
// Check if API key is provided
if (!apiKey) {
console.error("The OPENAI_API_KEY environment variable is missing or empty.");
}
const openai = new OpenAI({ apiKey: apiKey });
Here is the error I have been receiving: Error: The OPENAI_API_KEY environment variable is missing or empty; either provide it, or instantiate the OpenAI client with an apiKey option, like new OpenAI({ apiKey: 'My API Key' }).
But when I console.log my apiKey, I see it in my server console.
I am using Next.js, and have read that Next has built in .env support so I don't need to npm install dotenv. I've tried using .env.local instead of standard .env and still having issues.
I'm also worried that my helper function is being client side rendered which is why my API key could be coming back as undefined.
I don't want my API key to be displayed publically with NEXT_PUBLIC_.
Is there another way to get this working?
Any ideas on what I could be missing?
NEXT_PUBLIC_. Make sure this helper function lives only on the server, and you can expose it through a route or something.