← Blog

Claude API TypeScript Express Server Setup

2026-11-16 · 4 min read · SubToAPI Team

Setting up a TypeScript Express server to work with the Claude API means wiring three things correctly: a typed HTTP server, a backend-only API key, and a request/response shape that matches Claude's Messages API. This guide walks through the full setup — project scaffolding, environment config, the Express route that calls Claude, and streaming responses back to a client — so you end up with a working server, not just a snippet.

The short version: install express, typescript, ts-node-dev, and either @anthropic-ai/sdk or a plain fetch call; keep your API key server-side in .env; expose a /api/chat route that forwards messages to Claude and returns the result as JSON or a stream. Below is the detailed walkthrough, including the parts people usually get wrong (CORS, streaming headers, and error handling).

Project Setup

Start with a clean TypeScript project:

mkdir claude-express-server && cd claude-express-server
npm init -y
npm install express dotenv cors
npm install -D typescript ts-node-dev @types/express @types/node @types/cors
npx tsc --init

In tsconfig.json, make sure you have at least:

{
  "compilerOptions": {
    "target": "ES2020",
    "module": "commonjs",
    "outDir": "dist",
    "rootDir": "src",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true
  }
}

Create a .env file for your key — never hardcode it, never commit it:

CLAUDE_API_KEY=your_key_here
PORT=3001

Basic Express Server

Create src/server.ts:

import express, { Request, Response } from "express";
import cors from "cors";
import dotenv from "dotenv";

dotenv.config();

const app = express();
app.use(cors());
app.use(express.json());

app.get("/health", (_req: Request, res: Response) => {
  res.json({ status: "ok" });
});

const port = process.env.PORT || 3001;
app.listen(port, () => console.log(`Server running on port ${port}`));

Run it with npx ts-node-dev src/server.ts and confirm /health returns a 200.

Adding the Claude Call

You can call Claude directly with fetch, no SDK required:

interface ChatRequestBody {
  message: string;
}

app.post("/api/chat", async (req: Request<{}, {}, ChatRequestBody>, res: Response) => {
  const { message } = req.body;

  if (!message) {
    return res.status(400).json({ error: "message is required" });
  }

  try {
    const response = await fetch("https://api.anthropic.com/v1/messages", {
      method: "POST",
      headers: {
        "content-type": "application/json",
        "x-api-key": process.env.CLAUDE_API_KEY as string,
        "anthropic-version": "2023-06-01",
      },
      body: JSON.stringify({
        model: "claude-sonnet-4-20250514",
        max_tokens: 1024,
        messages: [{ role: "user", content: message }],
      }),
    });

    if (!response.ok) {
      const errText = await response.text();
      return res.status(response.status).json({ error: errText });
    }

    const data = await response.json();
    res.json(data);
  } catch (err) {
    console.error(err);
    res.status(500).json({ error: "internal server error" });
  }
});

This is a complete, working route. Add types for the Claude response shape if you want stricter typing downstream, but the raw JSON is fine to start with.

Streaming Responses to the Client

If your frontend needs tokens as they arrive, set stream: true on the Claude request and pipe the server-sent events through to your own client using text/event-stream:

app.post("/api/chat/stream", async (req: Request, res: Response) => {
  const { message } = req.body;

  res.setHeader("Content-Type", "text/event-stream");
  res.setHeader("Cache-Control", "no-cache");
  res.setHeader("Connection", "keep-alive");

  const upstream = await fetch("https://api.anthropic.com/v1/messages", {
    method: "POST",
    headers: {
      "content-type": "application/json",
      "x-api-key": process.env.CLAUDE_API_KEY as string,
      "anthropic-version": "2023-06-01",
    },
    body: JSON.stringify({
      model: "claude-sonnet-4-20250514",
      max_tokens: 1024,
      stream: true,
      messages: [{ role: "user", content: message }],
    }),
  });

  if (!upstream.body) {
    res.status(502).end();
    return;
  }

  const reader = upstream.body.getReader();
  const decoder = new TextDecoder();

  while (true) {
    const { done, value } = await reader.read();
    if (done) break;
    res.write(decoder.decode(value));
  }

  res.end();
});

The key detail most setups miss: disable response buffering on your reverse proxy (nginx's proxy_buffering off, or the equivalent on your host) or the stream will arrive in chunks on the client instead of token-by-token.

Why Developers Wrap This in Their Own API Layer

Once this server exists, teams usually want the same thing: issue separate keys per client or environment, cap usage, and see which route or app is consuming tokens — without building billing and key management themselves. That's the gap SubToAPI fills. It sits in front of your Claude access and gives you sub_live_... application keys, streaming, tool use, and per-key usage metadata through one dashboard, so your Express server (or any backend) talks to a single stable endpoint instead of managing raw provider keys across environments. The request/response shape in /docs/messages mirrors what's above, so swapping it in is mostly a base URL and header change. Streaming works the same way as the native API — see /docs/streaming for the exact event format.

Project Structure for a Real Server

For anything beyond a demo, split concerns:

src/
  server.ts
  routes/
    chat.ts
  services/
    claude.ts
  middleware/
    errorHandler.ts

Move the fetch call into services/claude.ts, return typed results, and keep routes/chat.ts thin. Add a centralized error-handling middleware instead of try/catch in every route — Express supports this natively with a four-argument error handler registered last with app.use().

Questions

Do I need the Anthropic SDK, or is fetch enough? fetch is enough for most Express setups and avoids an extra dependency. The SDK adds typed response objects and built-in retry logic, which is worth it if you're calling Claude from many routes.

How do I handle CORS for a frontend calling this server? Use the cors middleware and restrict origin to your frontend's domain in production. Never expose your Claude API key to the browser — all calls must go through your Express server.

Can I avoid managing the Claude API key myself? Yes — services like SubToAPI let you generate scoped application keys and route through a single endpoint with built-in usage tracking, so you don't have to build key rotation or per-client limits into your Express app. Get started at /signup or see /docs/quickstart.

Turn your Claude access into an HTTPS API

SubToAPI gives you application API keys, streaming, tool use and usage insights on top of your existing Claude access — set up in minutes.

Start free  Read the quickstart →