import dotenv from "dotenv";
dotenv.config();
console.log("OPENAI_API_KEY:", process.env.OPENAI_API_KEY); // this line to debug
import openaiPkg from "openai";
const openaiApiKey = process.env.OPENAI_API_KEY; //
const { Configuration, OpenAIApi } = openaiPkg;
if (!openaiApiKey) {
console.error('OPENAI_API_KEY is not set');
// closes backend if key is not set
process.exit(1);
}
const openai = new openaiPkg({
apiKey: openaiApiKey,
});
export default openai;`
I recently built a website that uses an environment variable for my openai API key. The website was working in VS code, then I uploaded it to a github repo and upload the github repo to Vercel. The website was working the first Now, some days later. I get this 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' }).
My .env file looks like this: OPENAI_API_KEY=sk-my-key
I have no idea why this is happening, because my .env file is populated and it was working seamlessly a few days prior. The application still works when I run it with the key in the terminal, but VS Code just cannot detect the key in the .env file.
I've tried moving the .env file to different folders, deleting the .env file and making a new one, making a copy of the entire code directory, and more. All yield the same error. I have dotenv configured in all of the backend files.