Reputation: 1
I have a page in a react.js app calling the api of openai and it works locally when I have the actual apikey in the page but I have been trying to create the .env and I have not figure it out. This is what I have
import React from "react";
import { Component } from "react";
import { Container, Form, Button, Card } from "react-bootstrap";
const {Configuration, OpenAIApi } = require ('openai');
const configuration = new Configuration({
apikey: process.env.REACT_APP_OPENAI_API_KEY
});
const openai= new OpenAIApi(configuration)
.....
If I have the actual apikey instead of 'process.env.REACT_APP_OPENAI_API_KEY' it works. I created a .env file with REACT_APP_OPENAI_API_KEY= 'the actual key' no luck,
Any suggestions, thank you, Marlon
Upvotes: 0
Views: 1777
Reputation: 994
As a suggestion dotenv is not a preferred method of managing environment in production applications, you might consider having a session stored in a user secure session (maybe with redis) depending on your backend.
If you're not concerned about the key being secure, an alternative to .env is leveraging the /public directory of the react app. The following is a pattern I have used
Given the following directory structure
project-root
/public/config.json
/src/App.js
/src/index.js
/src/providers/context/config.js
// /src/providers/context/config.js
import { createContext, Context } from "react";
const context = createContext({
config: undefined
});
export { context as configContext };
export default function ConfigProvider(props) {
const {
children,
config
} = props;
return (
<context.Provider value={{ config }}>
{children}
</context.Provider>
)
}
// index.js
import ConfigContext from './providers/ConfigContext';
// You can use fetch or any other http client.
import axios from 'axios';
import App from './App';
async function configure() {
try {
// You could store this in localStorage or indexeddb depending on your implantation
const { data: config } = await axios('./config.json');
root.render(<React.StrictMode>
<ConfigContext config={config} >
<App />
</ConfigContext>
</React.StrictMode>);
} catch (error) {
// handle your errors here
}
}
configure();
This provider pattern will allow you to pass configuration down to any child components, not limited to the key you're using.
Upvotes: 0
Reputation: 808
Make sure when you write in your env file with no space and quote"" like this:
REACT_APP_OPENAI_API_KEY=youropenaiapikeyhere
and restart your app.
Upvotes: 0
Reputation: 559
Make sure the .env file is in your root directory. Also, you must restart the server after you create or change the .env.
Upvotes: 0