From f00679e5c2ba52ec9f53a5137c7a0c879cd7a27a Mon Sep 17 00:00:00 2001 From: kathmbeck Date: Thu, 20 Nov 2025 17:17:09 -0500 Subject: [PATCH] feat: inject placeholder AI Gateway env vars during bundling Injects placeholder environment variables (OPENAI_API_KEY, OPENAI_BASE_URL, etc.) during bundling to enable top-level AI SDK initialization. During local 'netlify deploy', the bundler executes edge function code for: 1. Creating ESZIP bundles 2. Extracting function configs Without these placeholders, SDKs like OpenAI throw errors when initialized at top-level scope (e.g., 'const client = new OpenAI()'). Real AI Gateway credentials (JWT tokens + BASE_URLs) are injected at runtime by Stargate (hosted) or Bootstrap (self-hosted). Only injects if user hasn't set their own values, preserving user-defined keys. --- packages/edge-bundler/node/bridge.ts | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/packages/edge-bundler/node/bridge.ts b/packages/edge-bundler/node/bridge.ts index 8c3f313e18..c082bde339 100644 --- a/packages/edge-bundler/node/bridge.ts +++ b/packages/edge-bundler/node/bridge.ts @@ -256,6 +256,25 @@ To install Deno manually: https://ntl.fyi/install-deno`, // Ensure PATH is always set as otherwise we are not able to find the global deno binary env[pathKey()] = inputEnv[pathKey({ env: inputEnv })] || process.env[pathKey()] + // Inject placeholder AI Gateway env vars for bundling to prevent SDK initialization errors + // These allow SDKs to be initialized at top-level during bundling without throwing + // Real AI Gateway credentials will be injected at runtime by the platform + const aiGatewayProviders = [ + { key: 'OPENAI_API_KEY', url: 'OPENAI_BASE_URL' }, + { key: 'ANTHROPIC_API_KEY', url: 'ANTHROPIC_BASE_URL' }, + { key: 'GEMINI_API_KEY', url: 'GOOGLE_GEMINI_BASE_URL' }, + ] + + for (const { key, url } of aiGatewayProviders) { + // Only inject if user hasn't set their own values + if (!env[key]) { + env[key] = 'placeholder-for-bundling' + } + if (!env[url]) { + env[url] = 'http://localhost/.netlify/ai' + } + } + return env }