> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://developers.meshapi.ai/docs/sd-ks/llms.txt.
> For full documentation content, see https://developers.meshapi.ai/docs/sd-ks/llms-full.txt.

# Node.js SDK

> Getting started with the MeshAPI TypeScript / Node.js SDK.

# Node.js SDK

The MeshAPI Node.js SDK provides a robust, native-fetch TypeScript client. It includes strict-mode typings, `AsyncIterable` streaming support, and comprehensive error handling.

## Requirements

* Node.js ≥ 18
* Zero runtime dependencies

## Installation

<Tabs>
  <Tab title="npm">
    ```bash
    npm install meshapi-node-sdk
    ```
  </Tab>

  <Tab title="yarn">
    ```bash
    yarn add meshapi-node-sdk
    ```
  </Tab>

  <Tab title="pnpm">
    ```bash
    pnpm add meshapi-node-sdk
    ```
  </Tab>
</Tabs>

## Quick Start

Initialize `MeshAPI` providing your Base URL and Data-Plane token.

### Standard Chat Completion

```ts
import { MeshAPI } from "meshapi-node-sdk";

const client = new MeshAPI({
  baseUrl: "https://api.meshapi.ai",
  token: "rsk_...",
});

const response = await client.chat.completions.create({
  model: "openai/gpt-4o-mini",
  messages: [
    { role: "system", content: "You are a helpful assistant." },
    { role: "user", content: "What is the capital of France?" },
  ],
  temperature: 0.7,
});

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

### Streaming Chat Completion

Streaming utilizes native JavaScript async iterators (`for await`).

```ts
const stream = client.chat.completions.create({
  model: "openai/gpt-4o-mini",
  messages: [{ role: "user", content: "Write a short poem." }],
  stream: true,
});

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

## Error Handling

All API errors throw a `MeshAPIApiError` with structured fields for deterministic failure handling. Mid-stream errors (e.g., interrupted stream before `[DONE]`) are also reliably caught and bubbled up as `MeshAPIApiError`s.

```ts
import { MeshAPIApiError } from "meshapi-node-sdk";

try {
  const response = await client.chat.completions.create({ /* ... */ });
} catch (err) {
  if (err instanceof MeshAPIApiError) {
    console.error(`Status [${err.status}] -  ${err.errorCode}: ${err.message}`);
    
    if (err.errorCode === "rate_limit_exceeded") {
       console.log(`Retry after ${err.retryAfterSeconds}s`);
    } else if (err.errorCode === "spend_limit_exceeded") {
       console.log("Spend limit exceeded.");
    }
  }
}
```

## Prompt Templates

You can pass a Template ID instead of messages directly to utilize saved prompt templates.

```ts
const response = await client.chat.completions.create({
  messages: [{ role: "user", content: "How do I reset my password?" }],
  template: "support-agent",
  variables: { company: "Acme Corp" },
});
```