# Grok API with TypeScript and Node.js

A server-side Grok 4.5 integration for TypeScript and Node.js using the OpenAI package. The examples use the Responses API, typed events, streaming, and explicit error handling.

## Install the TypeScript SDK

```bash
npm install openai
```

```bash
GROK_API_DEV_KEY=sk-lg-YOUR_API_KEY
```

## Send the first request

```typescript
import OpenAI from "openai";

const client = new OpenAI({
  apiKey: process.env.GROK_API_DEV_KEY,
  baseURL: "https://api.llm-gate.tech/v1",
  timeout: 3_600_000,
  maxRetries: 2,
});

const response = await client.responses.create({
  model: "grok-4.5",
  input: "Explain the event loop in two sentences.",
});

console.log(response.output_text);
console.log(response.usage);
```

## Keep the key on the server

```typescript
// app/api/grok/route.ts
import OpenAI from "openai";

const client = new OpenAI({
  apiKey: process.env.GROK_API_DEV_KEY,
  baseURL: "https://api.llm-gate.tech/v1",
});

export async function POST(request: Request) {
  const { input } = await request.json();
  const response = await client.responses.create({
    model: "grok-4.5",
    input,
  });

  return Response.json({ text: response.output_text });
}
```

## Stream output in Node.js

```typescript
const stream = await client.responses.create({
  model: "grok-4.5",
  input: "Write a short TypeScript example.",
  stream: true,
});

for await (const event of stream) {
  if (event.type === "response.output_text.delta") {
    process.stdout.write(event.delta);
  }
}
```

## Handle errors and retries

OpenAI.APIError exposes the HTTP status and error name. Retry 429 and temporary 5xx with a limit, but fix 400, 401, 403, or 404 before sending the request again.

```typescript
import OpenAI from "openai";

const client = new OpenAI({
  apiKey: process.env.GROK_API_DEV_KEY,
  baseURL: "https://api.llm-gate.tech/v1",
  maxRetries: 2,
  timeout: 3_600_000,
});
```

- Set a timeout that is shorter than the timeout of your reverse proxy.
- Limit simultaneous requests with a queue or semaphore.
- Do not log GROK_API_DEV_KEY or complete private input.
- Store the response ID when support needs to trace a failed request.

[Full API error reference](https://grok-api.dev/en/docs/errors)

## Related pages

- [Messages API](https://grok-api.dev/en/docs/messages)
- [Streaming API](https://grok-api.dev/en/docs/streaming)
- [Python](https://grok-api.dev/en/docs/python)
- [cURL](https://grok-api.dev/en/docs/curl)
