> ## Documentation Index
> Fetch the complete documentation index at: https://docs.portix.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Integrate Portrix into JavaScript and TypeScript Apps

> Integrate Portrix into Node.js and browser applications with the openai npm package. Includes TypeScript types, streaming, and async/await patterns.

You can integrate Portrix into JavaScript and TypeScript projects using the official `openai` npm package, the native Fetch API for lightweight scripts, or Axios for projects that already depend on it. All three approaches share the same base URL and Bearer token authentication pattern, and every method is fully compatible with TypeScript's type system.

## Installation

<CodeGroup>
  ```bash npm theme={null}
  npm install openai
  ```

  ```bash yarn theme={null}
  yarn add openai
  ```

  ```bash pnpm theme={null}
  pnpm add openai
  ```
</CodeGroup>

## Basic usage

Create an `OpenAI` client configured for Portrix and make a typed chat completion request:

```typescript theme={null}
import OpenAI from "openai";

const client = new OpenAI({
  apiKey: process.env.PORTRIX_API_KEY,
  baseURL: "https://api.portrix.ai/v1",
});

const response = await client.chat.completions.create({
  model: "anthropic/claude-3-5-sonnet",
  messages: [
    { role: "system", content: "You are a helpful assistant." },
    { role: "user", content: "Explain TypeScript generics in one paragraph." },
  ],
  temperature: 0.7,
  max_tokens: 512,
});

const message: string = response.choices[0].message.content ?? "";
console.log(message);
```

## Environment variables

Read your Portrix API key from `process.env` so it never appears in source code. In Node.js projects, load a `.env` file with a package like `dotenv`:

```typescript theme={null}
import "dotenv/config"; // npm install dotenv
import OpenAI from "openai";

const client = new OpenAI({
  apiKey: process.env.PORTRIX_API_KEY, // set in .env or your deployment environment
  baseURL: "https://api.portrix.ai/v1",
});
```

```bash theme={null}
# .env (add to .gitignore — never commit this file)
PORTRIX_API_KEY=your-portrix-api-key
```

<Warning>
  Never hardcode your API key in source files or commit it to version control. Treat it like a password: store it in environment variables, secrets managers, or your platform's secure configuration system.
</Warning>

## Browser usage

<Warning>
  Do not call Portrix directly from browser-side JavaScript. Doing so exposes your API key to anyone who inspects your page's network traffic. Instead, create a server-side proxy endpoint (e.g. a Next.js API route or an Express handler) that holds the key and forwards requests on behalf of the client.
</Warning>

See the [Next.js integration](#next-js-integration) section below for a complete server-side proxy example.

## Using the Fetch API

For environments without the SDK — such as Cloudflare Workers or lightweight scripts — use the Fetch API directly:

```typescript theme={null}
const response = await fetch("https://api.portrix.ai/v1/chat/completions", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.PORTRIX_API_KEY}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    model: "google/gemini-2.0-flash",
    messages: [{ role: "user", content: "What is the speed of light?" }],
  }),
});

if (!response.ok) {
  throw new Error(`Portrix API error: ${response.status} ${response.statusText}`);
}

const data = await response.json();
console.log(data.choices[0].message.content);
```

## Streaming in JavaScript

Use `stream: true` with the `openai` SDK and async iteration to print tokens as they arrive:

```typescript theme={null}
import OpenAI from "openai";

const client = new OpenAI({
  apiKey: process.env.PORTRIX_API_KEY,
  baseURL: "https://api.portrix.ai/v1",
});

const stream = await client.chat.completions.create({
  model: "openai/gpt-4o",
  messages: [{ role: "user", content: "Write a limerick about TypeScript." }],
  stream: true,
});

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

process.stdout.write("\n");
```

## Error handling

Catch typed errors from the `openai` package to handle rate limits, invalid requests, and network issues:

```typescript theme={null}
import OpenAI, { APIError, RateLimitError, APIStatusError } from "openai";

const client = new OpenAI({
  apiKey: process.env.PORTRIX_API_KEY,
  baseURL: "https://api.portrix.ai/v1",
});

try {
  const response = await client.chat.completions.create({
    model: "mistral/mistral-large",
    messages: [{ role: "user", content: "Hello!" }],
  });
  console.log(response.choices[0].message.content);
} catch (error) {
  if (error instanceof RateLimitError) {
    console.error("Rate limit hit — implement exponential backoff.");
  } else if (error instanceof APIStatusError) {
    console.error(`API status error ${error.status}: ${error.message}`);
  } else if (error instanceof APIError) {
    console.error(`API error: ${error.message}`);
  } else {
    throw error; // re-throw unexpected errors
  }
}
```

## Next.js integration

Create a server-side API route in Next.js to proxy Portrix requests. Your API key stays on the server and is never exposed to the browser:

```typescript theme={null}
// app/api/chat/route.ts  (Next.js App Router)
import OpenAI from "openai";
import { NextRequest, NextResponse } from "next/server";

const client = new OpenAI({
  apiKey: process.env.PORTRIX_API_KEY, // server-side only — not NEXT_PUBLIC_
  baseURL: "https://api.portrix.ai/v1",
});

export async function POST(req: NextRequest) {
  const { messages, model = "openai/gpt-4o" } = await req.json();

  const response = await client.chat.completions.create({
    model,
    messages,
  });

  return NextResponse.json(response);
}
```

Your client-side code then calls `/api/chat` — it never touches Portrix directly and never sees the API key.

<Tip>
  In Next.js, prefix environment variables with `NEXT_PUBLIC_` only when they must be readable in the browser. Keep `PORTRIX_API_KEY` unprefixed so Next.js automatically restricts it to server-side runtimes.
</Tip>
