Browse documentation

TypeScript / Node.js SDK

The official nRouter Node.js and TypeScript SDK with automatic metadata parsing, SSE streaming, server prompt templates, and client conversation memory.

The official nRouter Node.js/TypeScript SDK (@nrouter_ai/sdk) delivers type-safe client bindings for the nRouter unified gateway (https://api.nrouter.ai/v1) across Node.js, Bun, Deno, and edge runtimes.

Configure your virtual key via NROUTER_API_KEY:

  • Complete type safety: Native TypeScript definitions for Chat Completions, Anthropic Messages, and gateway parameters.
  • Automatic metadata & FinOps: Response headers parsed into client.lastResponse with exact USD costs and trace IDs.

Installation

npm install @nrouter_ai/sdk

Setup & Chat Completion

Set your virtual API key in your environment:

export NROUTER_API_KEY="sk-nrouter-xxxxxxxxxxxx"

Initialize the client with automatic environment resolution:

import { nRouter } from "@nrouter_ai/sdk";

// Reads NROUTER_API_KEY and targets https://api.nrouter.ai/v1
const client = new nRouter();

const response = await client.chat.completions.create({
  model: "gpt-5.4-mini",
  messages: [{ role: "user", content: "Explain HTTP keepalive for LLM proxies." }],
});

console.log(response.choices[0].message.content);

Streaming Responses

Stream tokens via Server-Sent Events (SSE):

import { nRouter } from "@nrouter_ai/sdk";

const client = new nRouter();

const stream = await client.chat.completions.create({
  model: "claude-haiku-4-5-20251001",
  messages: [{ role: "user", content: "Write a poem about distributed systems." }],
  stream: true,
});

for await (const chunk of stream) {
  process.stdout.write(chunk.choices[0]?.delta?.content || "");
}
console.log();

Error Handling

Errors map to descriptive HTTP status codes documented in Errors & Rate Limits and unwrap to typed errors:

import { nRouter, APIError, nRouterGuardrailBlockedError } from "@nrouter_ai/sdk";

const client = new nRouter();

try {
  const res = await client.chat.completions.create({
    model: "gpt-5.4-mini",
    messages: [{ role: "user", content: "Run analysis" }],
  });
} catch (err) {
  if (err instanceof nRouterGuardrailBlockedError) {
    console.error(
      `Guardrail blocked request [${err.requestId}] (posture: ${err.guardrails}):`,
      err.message,
    );
  } else if (err instanceof APIError) {
    switch (err.status) {
      case 400:
        console.error("Bad request or guardrail rejection:", err.message);
        break;
      case 401:
        console.error("Authentication failed: Check NROUTER_API_KEY");
        break;
      case 402:
        console.error("Payment required: Organization balance exhausted");
        break;
      case 429:
        console.error("Rate limit reached. Backing off before retry.");
        break;
      default:
        console.error(`Gateway error [${err.status}]:`, err.message);
    }
  } else {
    console.error("Network or unexpected error:", err);
  }
}

SDK Examples

TopicExample FileDescription
Quickstartquickstart.tsFirst-run TypeScript starter
Complete Showcasenode.tsMulti-turn memory, prompt templates, conflict resolution
Vercel AI SDKvercel_ai.tsIntegration with Vercel AI SDK (@ai-sdk/openai)
E2E Suitedemo_e2e_suite.jsEnd-to-end multi-language test suite

Next Steps

Was this page helpful?