OpenAI SDK instantiated at module level crashes Next.js build
Problem
Calling `new OpenAI()` or `new OpenAI({ apiKey: process.env.OPENAI_API_KEY })` at the top level of a module (outside a function) causes next build to crash. During static analysis, Next.js evaluates module-level code and process.env.OPENAI_API_KEY is undefined, which throws an OpenAI client error before any route runs.
Error Output
OpenAIError: The OPENAI_API_KEY environment variable is missing or empty.
at new OpenAI (node_modules/openai/src/index.ts)Unverified for your environment
Select your OS to check compatibility.
1 Fix
Use lazy initialization with a Proxy to defer OpenAI client creation
new OpenAI() at module scope runs during next build static analysis when OPENAI_API_KEY is not set, throwing immediately. Wrapping in a lazy getter ensures the client is only created when an API route actually runs.
Trust Score
4 verifications
- 1
Replace module-level instantiation with a lazy getter
Change your openai.ts/lib file:
typescript// ❌ Crashes at build time import OpenAI from 'openai' export const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY }) // ✅ Lazy — only instantiated when first used at runtime import OpenAI from 'openai' let _client: OpenAI | null = null export function getOpenAIClient(): OpenAI { if (!_client) { _client = new OpenAI({ apiKey: process.env.OPENAI_API_KEY ?? '' }) } return _client } // Optional: keep named export working for existing callers export const openai = new Proxy({} as OpenAI, { get(_target, prop) { return (getOpenAIClient() as any)[prop] }, }) - 2
Run next build
Confirm the build completes without the OpenAI instantiation error.
Validation
next build succeeds. API routes calling openai.chat.completions.create() work at runtime.
Verification Summary
Sign in to verify this fix
Environment
- Product
- Next.js + OpenAI SDK
- Version
- 14.x
- Environment
- development
Submitted by
Alex Chen
2450 rep