401 Authorisation error in production only

I have a Next.js app running perfectly fine locally. In production (AWS EC2) I get a 401 error Failed to load resource: the server responded with a status of 401 (Unauthorized).

  • NextJS 14.1.3
  • OpenAI ^4.28.4
  • Environment variables are in .env, and double checked that there are no typos/spaces etc.
  • I also use Clerk for auth, but I don’t think this has something to do with it?
const openai = new OpenAI({
  apiKey: process.env.OPENAI_API_KEY,

Any idea what could be causing the issue?

Indeed, it had to do with Clerk. In midleware.ts, I had to make the API routes publicRoutes as per here. Working again, but need to improve middleware.

1 Like