How do I use the OpenAI SDK in Node.js with a compatible API (base URL + key)?

Install the official openai package and create the client with baseURL pointing to your provider and apiKey with its key; the rest of your Node.js code, including streaming and error handling, stays the same.

To use the OpenAI SDK in Node.js with a compatible API, install the official openai package and create the client with two parameters: baseURL, pointing to your provider's base URL, and apiKey, holding the key that provider gives you. The rest of the code stays the same: chat completions, streaming and error handling.

In this recipe we use Dongee AI Router, Dongee's OpenAI-compatible API for several AI models, as the example. The pattern works with any API compatible with the OpenAI standard.

What you need before you start

  • Node.js 20 or later and npm.
  • A project using ESM modules. Use .mjs files or set "type": "module" in your package.json.
  • An API compatible with the OpenAI standard. You need its base URL, a key and the exact model name.

Dongee AI Router is a unified API that gives you access to several AI models with a single key. It prioritizes fast models hosted in Dongee's data center in Canada. It works on prepaid credit from 3 USD, with no monthly fee. To move your code to AI Router, you only change the base URL and the key.

Step by step with Dongee AI Router

  1. Activate AI Router and add credit. It's activated from your client area, so you need to be a Dongee customer. New accounts get a welcome credit. If your balance runs out, requests stop and no debt is generated.
  2. Create a key. You can create as many keys as you want per account. We recommend limiting each one to the models you actually use. The details are in the guide to limit an API key to specific AI models.
  3. Copy the base URL and the model name. Both appear in your client area. Copy the model name exactly as it appears in the list: if it differs by a single letter, the request will fail.
  4. Set the environment variables on the server. In this guide we use AI_ROUTER_BASE_URL, AI_ROUTER_API_KEY and AI_MODEL. They're example names and you can change them.
  5. Write the code (you'll see it in the next section).
  6. Test and check usage. In the client area you can see usage per model, per key and the details of each request.

Code recipe in Node.js (ESM)

1. Install the package

npm install openai

2. Environment variables (local .env file, never in the repo)

AI_ROUTER_BASE_URL="<base URL from your client area>"
AI_ROUTER_API_KEY="<your key>"
AI_MODEL="<model from the list>"

On Node 20 or later you can load the file without extra libraries using node --env-file=.env app.mjs.

3. Client and a regular request

// app.mjs
import OpenAI from "openai";

const client = new OpenAI({
  baseURL: process.env.AI_ROUTER_BASE_URL,
  apiKey: process.env.AI_ROUTER_API_KEY,
});

const model = process.env.AI_MODEL;

try {
  const res = await client.chat.completions.create({
    model,
    messages: [
      { role: "system", content: "Reply in English, briefly." },
      { role: "user", content: "What is a base URL?" },
    ],
  });
  console.log(res.choices[0].message.content);
} catch (err) {
  if (err instanceof OpenAI.APIError) {
    console.error("API error:", err.status, err.message);
  } else {
    console.error("Network or code error:", err);
  }
}

4. Streaming request

AI Router supports streaming. Add stream: true and iterate over the response with for await:

try {
  const stream = await client.chat.completions.create({
    model,
    messages: [{ role: "user", content: "Write three name ideas for a blog." }],
    stream: true,
  });
  for await (const chunk of stream) {
    process.stdout.write(chunk.choices[0]?.delta?.content ?? "");
  }
} catch (err) {
  console.error("Stream failed:", err.message);
}

The try/catch keeps your app from crashing and lets it show a useful message. Log the status and message the API returns so you can diagnose issues. Don't write logic that depends on specific error codes without checking them first in your own tests.

Security: where the key goes

  • Never in the browser. If the key reaches the frontend, anyone can see it and spend your balance. The browser should call your backend, and your backend calls the API.
  • Never in the repository. Add .env to .gitignore before your first commit. This also applies if you generate the project with Lovable, Bolt, v0, Cursor, Claude Code or Codex and push it to GitHub.
  • One key per app or environment. Since there's no limit on keys, you can separate development and production. That way you see each one's usage separately.

AI Router doesn't store your conversations. It only records the billing data for each request, never the content.

If you publish the app on Dongee Live

Dongee Live, Dongee's service for publishing apps built with AI, doesn't publish or deploy AI models: your Node.js app runs on Live and calls the model through AI Router. Live supports Node.js 20, 22 and 24 and has its own environment variables, on Live Free too (0 USD, 1 app). That's where you store AI_ROUTER_BASE_URL, AI_ROUTER_API_KEY and AI_MODEL without touching the code. If your app also uses a database, see how to publish a Node.js app with MySQL from Claude Code or Cursor.

Honest comparison: unified API or calling each provider directly?

CriterionUnified compatible API (e.g., AI Router)Directly to each provider
CodeA single SDK and a single base URLA different SDK or configuration per provider
KeysOne key for several modelsOne key per provider
Switching modelsYou change AI_MODELMay require code changes
Provider-exclusive featuresOnly what the OpenAI standard coversFull access to everything proprietary
Fallback between modelsYou program it (AI Router doesn't do its own fallback)You program it too

When Dongee AI Router is NOT the right fit: if you depend on features only one provider offers that aren't part of the OpenAI standard, if you need a model that isn't on the list, or if you want the service to handle automatic fallback for you. In those cases, calling that provider directly is the simplest option. If your goal is to spend less, read how to optimize token usage with AI routers. To split requests across models, see smart routing between language models.

Frequently asked questions

Does it work with LangChain or other libraries?

If the library lets you change the base URL and key of its OpenAI-compatible client, the pattern is the same. Test it in your project before taking it to production.

Can I use it behind a gateway like LiteLLM?

Yes. You can put AI Router behind your own gateway, such as LiteLLM, and configure it with the base URL and the key.

Where do I find the base URL and model names?

In your client area, once you activate AI Router. Copy the model name exactly as it appears in the list.

What happens if my balance runs out?

Requests stop and no debt is generated. Your code should catch that error with try/catch to notify the user without the app crashing.

Can I call the API directly from React or the browser?

It's not recommended: the key would be exposed and anyone could use your balance. Create an endpoint on your Node.js server and call the API from there.

In summary

With the official openai SDK, connecting to a compatible API comes down to setting baseURL and apiKey from environment variables and choosing the model by its exact name. Keep the key on the server, check usage in your client area and switch models when you need to without rewriting your app.

Comenta lo que quieras

Unete a la charla
Solo ingresa tu email