TypeScript
Use the OpenAI JavaScript client with Router in a server-side application.
Install the client
pnpm add openaiKeep the API key in a server environment. Do not instantiate this client in browser code.
Create a client
import OpenAI from "openai";
const client = new OpenAI({ baseURL: process.env.ROUTER_BASE_URL, apiKey: process.env.ROUTER_API_KEY, timeout: 45_000, maxRetries: 0,});The base URL must include /v1. Setting maxRetries: 0 keeps retry decisions visible in your own application flow.
List model editions
const models = await client.models.list();
for (const model of models.data) { console.log(model.id);}Create a completion
const response = await client.chat.completions.create({ model: "gemma3:1b", messages: [ { role: "system", content: "Answer in plain language." }, { role: "user", content: "What is edge inference?" }, ], max_tokens: 160, temperature: 0.4,});
console.log(response.choices[0]?.message.content);console.log(response.usage);Stream output
const stream = await client.chat.completions.create({ model: "gemma3:1b", messages: [{ role: "user", content: "Write a two-line welcome." }], stream: true,});
let completed = false;
for await (const chunk of stream) { const choice = chunk.choices[0]; process.stdout.write(choice?.delta.content ?? ""); if (choice?.finish_reason) completed = true;}
if (!completed) throw new Error("The response stream ended before completion");Cancel from your application
The SDK accepts an abort signal in its request options.
const controller = new AbortController();
const request = client.chat.completions.create( { model: "gemma3:1b", messages: [{ role: "user", content: "Explain inference." }], }, { signal: controller.signal },);
// Call controller.abort() when the user stops the request.const response = await request;See errors for the status and code combinations your application should handle.