OpenAI SDK v5 ignores NODE_EXTRA_CA_CERTS — custom CA certificates not working in enterprise environments
Confirm this is a feature request for the Node library and not the underlying OpenAI API.
- [x] This is a feature request for the Node library
Describe the feature or improvement you're requesting
Describe the issue
The OpenAI SDK v5 uses undici internally for HTTP requests. undici's fetch() does not respect NODE_EXTRA_CA_CERTS (nodejs/undici#2200), which means enterprise users behind corporate TLS inspection proxies or connecting to endpoints with private CA certificates cannot establish connections.
Setting NODE_TLS_REJECT_UNAUTHORIZED=0 works (confirming the endpoint is reachable), but this disables all TLS verification and is not acceptable for production.
Environment
- openai SDK version: 5.20.2
- Node.js version: 22.x
- Framework: Next.js 14.x (server-side)
- OS: Linux (also reproduced on Windows/WSL2)
Steps to reproduce
- Set
NODE_EXTRA_CA_CERTS=/path/to/corporate-ca-chain.pem - Create an OpenAI client pointing to an endpoint with a certificate signed by the corporate CA:
const openai = new OpenAI({
apiKey: "...",
baseURL: "https://internal-llm-endpoint.example.com/v1/",
});
await openai.chat.completions.create({ ... });
- The request fails with:
Error: Connection error.
cause: Error: unable to verify the first certificate
code: UNABLE_TO_VERIFY_LEAF_SIGNATURE
- Setting
NODE_TLS_REJECT_UNAUTHORIZED=0makes it work, confirming the issue is with CA certificate loading, not connectivity.
Root cause
The OpenAI SDK v5 uses undici for HTTP, and undici's fetch() does not honor NODE_EXTRA_CA_CERTS (see nodejs/undici#2200). The SDK's fetchOptions: { dispatcher } option also doesn't work in Next.js environments because Next.js patches globalThis.fetch, silently dropping the undici dispatcher option.
Workaround
The solution is to pass an explicit fetch function using undici.fetch directly (bypassing the patched global fetch) with a singleton dispatcher carrying the custom CA certificates:
import { OpenAI } from "openai";
import * as fs from "fs";
import * as tls from "tls";
// Load custom CA and combine with Node.js root certificates
const customCaPath = process.env.NODE_EXTRA_CA_CERTS;
const customCa = customCaPath ? fs.readFileSync(customCaPath) : undefined;
const combinedCa = customCa ? [...tls.rootCertificates, customCa] : undefined;
// Lazy-load undici to avoid "File is not defined" during Next.js build on Node.js 18
let _dispatcher: any;
let _fetch: any;
let _initialized = false;
function ensureUndici() {
if (_initialized) return;
_initialized = true;
if (!combinedCa) return;
const undici = require("undici");
_dispatcher = new undici.Agent({ connect: { ca: combinedCa } });
_fetch = undici.fetch;
}
// When creating the client:
ensureUndici();
const openai = new OpenAI({
apiKey: "...",
baseURL: "https://internal-llm-endpoint.example.com/v1/",
fetch: _dispatcher
? async (url, init) => {
return _fetch(url, { ...init, dispatcher: _dispatcher });
}
: undefined,
});
Key details for the workaround
-
Combine CAs: When providing
cato undici'sAgent, it replaces the default trust store. You must combine your custom CA withtls.rootCertificatesor public HTTPS endpoints will break. -
Singleton dispatcher: Create the
undici.Agentonce and reuse it. Creating a new one per request defeats connection pooling. -
Explicit undici fetch: Passing
fetchOptions: { dispatcher }does NOT work in Next.js because Next.js replacesglobalThis.fetch. You must pass a customfetchfunction that callsundici.fetchdirectly. -
Lazy-load undici:
undiciv7 referencesFileat the module level, which doesn't exist in Node.js 18. Userequire()inside a function instead of a top-levelimportto avoid build failures. -
Full CA chain: The PEM file must contain the full CA chain (intermediate + root CAs), not the server's leaf certificate.
Suggestion
It would be helpful if the OpenAI SDK could:
- Respect
NODE_EXTRA_CA_CERTSnatively by reading the env var and configuring its internal undici dispatcher automatically - Document the workaround for enterprise users who need custom CA certificates
- Ensure
fetchOptions: { dispatcher }works reliably regardless of framework-level fetch patching (e.g., by using undici's fetch internally rather thanglobalThis.fetch)
Related issues
- nodejs/undici#2200 —
fetch()ignores NODE_EXTRA_CA_CERTS - openai/openai-node#1555 — fetchOptions dispatcher type error (fixed in v5.8.2)
- cline/cline#8816 — Custom CA certs not respected for API connections
Additional context
No response
Si. Esto es un feature request del SDK de Node (openai-node) y no del OpenAI API subyacente.
El problema esta en la capa cliente: el SDK usa undici para HTTP, y hay un issue abierto donde se describe que fetch() puede no respetar NODE_EXTRA_CA_CERTS en este contexto. Ademas, ya existe un issue reciente en openai/openai-node con tu mismo planteo. ([GitHub]1)
Solucion practica
En Next.js 14 server-side + Node 22, la salida mas robusta no es fetchOptions: { dispatcher }, sino inyectar un fetch explicito basado en undici.fetch con un Agent singleton que lleve la CA corporativa.
Eso evita depender de globalThis.fetch parcheado por el framework y mantiene TLS valido. ([GitHub]2)
Implementacion recomendada
Crea, por ejemplo, lib/openai.ts:
import OpenAI from "openai";
import fs from "node:fs";
import tls from "node:tls";
let cachedFetch: typeof fetch | undefined;
let initialized = false;
function buildCustomFetch(): typeof fetch | undefined {
if (initialized) return cachedFetch;
initialized = true;
const caPath = process.env.NODE_EXTRA_CA_CERTS;
if (!caPath) return undefined;
const customCaPem = fs.readFileSync(caPath, "utf8");
// Importante:
// al pasar `ca` al Agent de undici, reemplazas el trust store por defecto.
// Por eso hay que combinar la CA corporativa con las root CAs de Node.
const combinedCa = [...tls.rootCertificates, customCaPem];
// Lazy require para evitar problemas de build en entornos donde undici
// pueda evaluarse antes de tiempo.
// En Node 22 esto suele estar bien, pero asi queda compatible.
// eslint-disable-next-line @typescript-eslint/no-var-requires
const undici = require("undici") as typeof import("undici");
const dispatcher = new undici.Agent({
connect: {
ca: combinedCa,
},
});
cachedFetch = ((url: RequestInfo | URL, init?: RequestInit) => {
return undici.fetch(url, {
...init,
dispatcher,
} as RequestInit & { dispatcher: unknown });
}) as typeof fetch;
return cachedFetch;
}
export const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY,
baseURL: process.env.OPENAI_BASE_URL, // ej: https://internal-llm-endpoint.example.com/v1/
fetch: buildCustomFetch(),
});
Uso
import { openai } from "@/lib/openai";
export async function testOpenAI() {
const res = await openai.chat.completions.create({
model: "gpt-4.1-mini",
messages: [{ role: "user", content: "ping" }],
});
return res;
}
Puntos criticos
1. No uses esto en produccion
NODE_TLS_REJECT_UNAUTHORIZED=0
Eso desactiva la verificacion TLS global y solo sirve para diagnostico. El hecho de que asi funcione confirma conectividad, pero no es una solucion segura. ([GitHub]3)
2. El PEM debe tener la cadena CA completa
Debe incluir intermediate + root CA, no el certificado leaf del servidor. Si no, seguiras viendo errores como UNABLE_TO_VERIFY_LEAF_SIGNATURE.
3. El dispatcher debe ser singleton
No crees un new Agent() por request. Si lo haces, pierdes pooling de conexiones y degradaras rendimiento. undici esta pensado para reutilizar dispatcher/agente. ([GitHub]4)
4. fetchOptions: { dispatcher } no es la via mas confiable en Next.js
Tu diagnostico es correcto: cuando el framework reemplaza globalThis.fetch, ciertas opciones especificas de undici pueden no propagarse como esperas. La forma mas estable es pasar fetch: custom directamente al cliente. Tu razonamiento coincide con la arquitectura documentada del SDK, que permite inyectar un fetch propio. ([GitHub]5)
Version pulida del feature request
Te dejo el texto listo para pegar en GitHub, mas compacto y tecnico:
Title
openai-node: respect NODE_EXTRA_CA_CERTS when using undici / provide first-class custom CA support
Body
## Confirm this is a feature request for the Node library and not the underlying OpenAI API
This is a feature request for the Node library.
## Describe the issue
The OpenAI Node SDK uses `undici` internally for HTTP requests. In enterprise environments behind TLS inspection proxies, or when connecting to OpenAI-compatible endpoints signed by a private CA, requests fail even when `NODE_EXTRA_CA_CERTS` is set.
Example error:
```txt
Error: Connection error.
cause: Error: unable to verify the first certificate
code: UNABLE_TO_VERIFY_LEAF_SIGNATURE
Setting NODE_TLS_REJECT_UNAUTHORIZED=0 makes the request succeed, which confirms the endpoint is reachable and the problem is CA trust loading, not connectivity.
Environment
- openai SDK version: 5.20.2
- Node.js version: 22.x
- Framework: Next.js 14.x (server-side)
- OS: Linux (also reproduced on Windows / WSL2)
Steps to reproduce
-
Set:
NODE_EXTRA_CA_CERTS=/path/to/corporate-ca-chain.pem
-
Create a client:
const openai = new OpenAI({ apiKey: "...", baseURL: "https://internal-llm-endpoint.example.com/v1/", }); -
Execute:
await openai.chat.completions.create({...});
Observed behavior
The request fails with:
UNABLE_TO_VERIFY_LEAF_SIGNATURE
Expected behavior
The SDK should honor NODE_EXTRA_CA_CERTS or otherwise provide a first-class documented mechanism for custom CA trust.
Root cause
undici-based fetch handling does not reliably honor NODE_EXTRA_CA_CERTS in this setup. Also, fetchOptions: { dispatcher } is not reliable in Next.js server environments because framework-patched fetch may ignore undici-specific options.
Current workaround
Passing an explicit custom fetch built on undici.fetch with a singleton undici.Agent({ connect: { ca } }), and combining the custom CA with tls.rootCertificates.
Why this matters
This affects enterprise users using:
- corporate TLS inspection proxies
- internal OpenAI-compatible gateways
- private PKI / custom root CAs
Suggested improvements
- Respect
NODE_EXTRA_CA_CERTSnatively in the SDK when using undici - Document a supported workaround for custom CA environments
- Ensure custom dispatcher / CA configuration works reliably even when frameworks patch
globalThis.fetch
Related issues
- nodejs/undici#2200
- openai/openai-node#1758
---
## Resumen ejecutivo
- **Si, es un problema del SDK Node, no del API.** :contentReference[oaicite:5]{index=5}
- **Tu workaround va bien encaminado.**
- La implementacion correcta en Next.js es **inyectar `fetch` custom con `undici.fetch` + `Agent` singleton + CA combinada con `tls.rootCertificates`**. :contentReference[oaicite:6]{index=6}
Si quieres, te lo dejo ahora mismo convertido a una version exacta para pegar en **GitHub issue**, o a un **helper production-ready para Next.js 14** con TypeScript estricto.
::contentReference[oaicite:7]{index=7}
A2ABench has an accepted answer for this imported thread.
- Thread: https://a2abench-api.web.app/q/cmmpna88400jb1401p88mte6m
- Accepted at: 2026-03-25T17:08:57.742Z
- Accepted answer agent:
ai village - Answer preview: "No matching threads were found for this query."
The SDK uses the runtime's fetch implementation, or an explicitly supplied custom fetch, and does not modify process-wide TLS trust or bypass a framework-provided fetch implementation. Configure NODE_EXTRA_CA_CERTS before starting Node, or provide a matching custom fetch and per-client dispatcher/Agent for custom trust roots. We are not planning to change global certificate trust or automatically replace framework fetch.