`Reflect.get called on non-object` error when using OpenAI library in NextJS

I'm having issues in getting OpenAI library to work in NextJS project on Cloudflare Pages.
I got the following error in workers log stream when calling the API endpoint on NextJS app:
{
  "message": [
    "TypeError: Reflect.get called on non-object"
  ],
  "level": "error",
  "timestamp": 1695279765223
}


Below is the minimal code that reproduce the issue:
import { OpenAI } from "openai";

export async function POST(requestContext: Request) {
  const gptClient = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });

  const requestBody = await requestContext.json();
  const gptRes = await gptClient.chat.completions.create({
    model: "gpt-4",
    messages: [{ role: "system", content: requestBody.systemPrompt }],
  });

  return new Response(JSON.stringify(gptRes), {
    headers: { "Content-Type": "application/json" },
  });
}

/// Route Segment Config
export const runtime = "edge";


I tried searching around on the internet to see if anyone encounter the same issues and possible solution but I couldn't found any. Interestingly, the example from Cloudflare Docs Stream OpenAI API Responses seems to be working when I tried it.
Documentation for Cloudflare Workers, a serverless execution environment that allows you to create entirely new applications or augment existing ones
Was this page helpful?