1 | initial version |
To add the OpenAI API key into a .env file for a React application, follow these steps:
Create a new file called .env
in the root directory of your React application.
Open the .env
file and add the following line:
REACT_APP_OPENAI_API_KEY=your_api_key_here
Replace your_api_key_here
with your actual API key.
Save the .env
file.
In your React application code, use the API key by referencing the process.env.REACT_APP_OPENAI_API_KEY
variable.
For example, in a component that uses the OpenAI API, you could do something like this:
const response = await fetch('https://api.openai.com/v1/engines/davinci-codex/completions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${process.env.REACT_APP_OPENAI_API_KEY}`,
},
body: JSON.stringify({
prompt: '...',
temperature: 0.5,
max_tokens: 50,
n: 1,
}),
});
This will use the API key stored in the .env
file to authenticate with the OpenAI API.