1
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.

2
  • I'm having the same issue. I've added the environment variable to my machine and my .env file. Even tried just adding it as a string directly to the opts parameter. Still saying it doesn't see it. Any luck? Commented Jan 8 at 20:50
  • I have the same issue. I think this is a VS Code bug as my other variables can be loaded just okay. I can easily change other environment variables. Commented Mar 27 at 14:05

1 Answer 1

-1
.env variable  initially we need to **RUN in terminal source file_name**

then this variable available in terminal . after starting app app will able to read .env variables actually vs code does not identify .env variables .

so firstly check your issue

The OPENAI_API_KEY environment variable is missing or empty;

RUN Enter printenv. check variable available in the terminal .then you will able to see that variable available or not

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.