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
In React you have to define your api key with prefix
REACT_APP
In your
.env
file change your environment variable name asREACT_APP_OPENAI_API_KEY="Your_api_key"
and use it in your react file asconst apiKey = process.env.OPENAI_API_KEY;
Make sure to add double quotes "YOUR_API_KEY". And use REACT_APP_ before your varialbe.