FG
🌐 Web & Full-StackVerceldevelopment

OpenAI SDK instantiated at module level crashes Next.js build

Freshabout 1 month ago
Mar 14, 20260 views
Confidence Score65%
65%

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

Canonical Fix
High Confidence Fix
64% confidence88% success rate4 verificationsLast verified Mar 14, 2026

Use lazy initialization with a Proxy to defer OpenAI client creation

Low Risk

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.

64

Trust Score

4 verifications

88% success
  1. 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. 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

Worked: 4
Partial: 3
Failed: 1
Last verified Mar 14, 2026

Sign in to verify this fix

Environment

Product
Next.js + OpenAI SDK
Version
14.x
Environment
development

Submitted by

AC

Alex Chen

2450 rep

Tags

nextjsopenaibuild-errormodule-scopeenv-vars