Call the OpenAI API from Node.js: SDK and fetch Examples (2026)
Calling an LLM API from Node.js is not complicated. Install the openai package, put your API key in an environment variable, and call chat.completions.create once to get a reply. If you would rather not add a dependency, a single POST request with Node's built-in fetch does the same job. The one rule you must keep: the key stays on the server and never goes into code that is sent to a browser.
This article is the minimal path for calling the OpenAI API from Node.js, in order: setup, the SDK version, the fetch version, why you can't call the API from the frontend, and how to debug errors. Model names in the examples are placeholders. Replace them with a model your account can actually use, and check the official docs.
What do you need before you start?
- A recent version of Node.js. The official SDK has a minimum Node version, so check the
openaipackage README; nativefetchis built into newer Node versions. - An API key. The API is billed by usage and is a separate account system from a ChatGPT subscription.
- A terminal and an empty folder.
If you have never sent an API request before, read Your first AI API call: send a request with curl or Your first LLM request with curl: every parameter explained first. Once you understand the shape of a request, the Node code goes much more smoothly.
How do you send your first request with the official SDK?
Initialize the project and install the dependency:
mkdir llm-demo && cd llm-demo
npm init -y
npm install openai
Add "type": "module" to package.json so you can use import directly. Then set the environment variable in your terminal (macOS / Linux):
export OPENAI_API_KEY="sk-你的key"
In Windows PowerShell, use $env:OPENAI_API_KEY="sk-你的key". Create sdk.mjs:
import OpenAI from "openai";
// If you don't pass apiKey, the SDK reads the OPENAI_API_KEY environment variable
const client = new OpenAI();
const res = await client.chat.completions.create({
model: "你的模型名",
messages: [
{ role: "system", content: "你是一个简洁的助手。" },
{ role: "user", content: "用一句话解释什么是 DNS。" },
],
});
console.log(res.choices[0].message.content);
Run node sdk.mjs. If the terminal prints a reply, it worked. (In the code above, the key placeholder, the model name placeholder, and the prompt strings are left in their original form: "你的key" means "your key", "你的模型名" means "your model name", the system prompt is "You are a concise assistant.", and the user prompt is "Explain what DNS is in one sentence.") OpenAI has also offered a Responses API in recent years. Its call style and response shape are different, so check the official docs to decide which one a new project should use. This article uses chat completions because most compatible APIs from other providers support that one.
How do you write it with native fetch, without the SDK?
The SDK is essentially a wrapper around the HTTP request below. Create fetch.mjs:
const res = await fetch("https://api.openai.com/v1/chat/completions", {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${process.env.OPENAI_API_KEY}`,
},
body: JSON.stringify({
model: "你的模型名",
messages: [{ role: "user", content: "用一句话解释什么是 DNS。" }],
}),
});
if (!res.ok) {
// On errors, look at the status code and response body first, before changing code
console.error(res.status, await res.text());
process.exit(1);
}
const data = await res.json();
console.log(data.choices[0].message.content);
Note that fetch does not throw on 4xx or 5xx responses, so you have to check res.ok yourself. The SDK throws an error carrying the status code in those cases, which is one of the most practical differences between the two approaches. Native fetch also has no built-in retries or timeout handling. For the SDK's defaults and production recommendations, see Configuring OpenAI SDK timeouts and retries.
Why can't you put the key in browser code?
Frontend code is ultimately delivered to the user's browser. Anyone can open the Network panel in developer tools and see the Authorization header on the request. Putting the key in the frontend is the same as publishing it. You pay per use, so if someone takes the key and runs up calls, the bill is yours. In a browser environment the official SDK also refuses to run by default, and you have to explicitly enable an option with "dangerous" in its name. That is a warning not to do this.
The right structure is to add a backend of your own:
- The browser sends the user's input to an endpoint on your server (for example
/api/chat). - The server reads the key from an environment variable and calls the model API.
- The server returns the result to the browser, and this layer is where you enforce login checks, rate limits, and length limits.
Below is a minimal forwarding example using only the Node standard library (plus the SDK). It only illustrates the structure and has no authentication, which you must add before going live:
import http from "node:http";
import OpenAI from "openai";
const client = new OpenAI();
http.createServer(async (req, res) => {
if (req.method !== "POST" || req.url !== "/api/chat") {
res.writeHead(404).end();
return;
}
let body = "";
for await (const chunk of req) body += chunk;
const { prompt } = JSON.parse(body || "{}");
const r = await client.chat.completions.create({
model: "你的模型名",
messages: [{ role: "user", content: String(prompt).slice(0, 2000) }],
});
res.setHeader("Content-Type", "application/json");
res.end(JSON.stringify({ text: r.choices[0].message.content }));
}).listen(3000);
If a key has already been committed to a public repository or sent to the frontend, see Your OpenAI API key leaked: revoke it, check usage, and prevent a repeat. We also recommend setting a spending limit on your account in the console; see How to set an OpenAI API spending limit and usage alerts.
How do you troubleshoot errors?
| Symptom | Common cause | What to check first |
|---|---|---|
| 401 | Wrong or revoked key, or the environment variable wasn't read | console.log(Boolean(process.env.OPENAI_API_KEY)) |
| 404 | Misspelled model name, or your account can't use that model | The official model list and your account permissions |
| 429 | Requests too fast, or insufficient quota | The specific reason in the response body, then decide between backoff-and-retry and adding credit |
| 5xx | Server-side outage | Check the OpenAI status page mirror and retry later |
| Timeouts, connection failures | Network path problems | See AI API latency from China, or test a connection from the cdnping home page |
The exact meaning of each error code is defined by the official docs. When debugging, follow one order: status code first, then the response body, and only then suspect your code logic.
What if you have no overseas credit card or your connection is unreliable?
The official API requires top-ups through overseas payment channels, and connections can be unstable on some networks (this is a common situation for developers in mainland China). In that case you can consider an aggregation gateway that is compatible with the OpenAI API format. In code you usually only change baseURL and the key:
const client = new OpenAI({
apiKey: process.env.GATEWAY_API_KEY,
baseURL: "网关提供的接口地址",
});
("网关提供的接口地址" is a placeholder for the endpoint URL your gateway provides.)
AGI Plan is cdnping's commercial partner. It is a multi-provider LLM aggregation gateway with monthly subscriptions, billed in RMB, with no overseas credit card needed. It is compatible with both the OpenAI and Anthropic API formats, so tools like Claude Code and Codex work by changing a single endpoint address. The service states plainly that it is not an officially authorized channel, and some models are marked "overseas only"; check agiplan.dev/models for what is actually available. Setup steps are at agiplan.dev/startup.
For how to change the endpoint address in various tools, see Custom API endpoints for Claude Code, Codex, and OpenCode. For help choosing between options, see How to choose an AI API access method.
What should you do next?
- Get the
sdk.mjsabove running and confirm you receive a reply. - Move the call into your own backend endpoint, so the browser only talks to your server.
- Set a spending limit in the console, and add a timeout and a limited number of retries to your requests.
- To compare with the Python version, see Calling the OpenAI API from Python: a beginner's guide.