skip to Main Content

So I literally tried fetch and switch to axios to see what was wrong and still says my API key is undefined

`import axios from "axios";

const apiKey = process.env.OPENAI_API_KEY;

console.log(apiKey);

axios
  .post(
    "https://api.openai.com/v1/chat/completions",
    {
      model: "gpt-3.5-turbo",
      messages: [{ role: "user", content: "Say this is a test!" }],
      temperature: 0.7,
    },
    {
      headers: {
        "Content-Type": "application/json",
        Authorization: `Bearer ${apiKey}`,
      },
    }
  )
  .then((response) => {
    console.log(response.data.choices[0].message.content);
  })
  .catch((error) => {
    // console.log(error);
  });
`

I have my .env file on my root and I copied the API key into there

So it’s OPENAI_API_KEY=sk-wfwwfewfewf

But when I console log the api key it keeps saying undefined??

I have both axios and openai installed in my package.json so I don’t understand why it’s not reading my api key properly

I even tried pasting my code into chatgpt and says it sees no errors?

2

Answers


  1. In React you have to define your api key with prefix REACT_APP
    In your .env file change your environment variable name as REACT_APP_OPENAI_API_KEY="Your_api_key" and use it in your react file as const apiKey = process.env.OPENAI_API_KEY;

    make sure that your have created the .env file in the root of your react app

    Login or Signup to reply.
  2. Make sure to add double quotes "YOUR_API_KEY". And use REACT_APP_ before your varialbe.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search