How to call the OpenAI API with Next.js Frontend (DO NOT do it on the frontend!)
1 min readDec 22, 2022
- Server-side code (backend stuff!) for calling the OpenAI API. I learned the hard way that this shit can’t be called in the frontend. Annoying. But here’s an example:
Thank you Ember for pointing me to this! I spent ages trying to figure out why the API key would fuck up every once in a while, but here is the key.
import { Configuration, OpenAIApi } from "openai";
const configuration = new Configuration({
apiKey: process.env.OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);
export default async function (req: { body: { input: string; instruction:string; }; }, res: { status: (arg0: number) => { (): any; new(): any; json: { (arg0: { result: string | undefined; }): void; new(): any; }; }; }) {
const response = await openai.createEdit({
model: "text-davinci-edit-001",
input: req.body.input,
instruction: req.body.instruction,
});
res.status(200).json({ result: response.data.choices[0].text });
}
This is also the code that I put in the generate.ts file in /api/generate.ts.
Let’s fucking goooo!