Documentation menu

Node.js

The TypeScript SDK for the management API, webhook verification and the gateway's helpers.

@hixel/sdk is the official JavaScript and TypeScript SDK. It covers the whole management API, verifies webhooks, and points the OpenAI and Anthropic SDKs you already use at the gateway.

  • No dependencies. It uses web standards only: fetch, crypto.subtle, AbortSignal.
  • The wire, typed. Requests and responses keep the API's snake_case names and its amounts as exact decimal strings. The types are generated from the API's OpenAPI document.
  • Safe retries. Every write carries an Idempotency-Key, so a retried call runs once.

Install#

npm install @hixel/sdk

It runs on Node 20 and later, Cloudflare Workers, Bun and Deno, as ESM or CommonJS, with type declarations.

RuntimeManagement APIWebhook verificationGateway helpers
Node 20+yesyesyes
Cloudflare Workersyesyesyes
Bun, Denoyesyesyes
Browsersno (keys are secret)yesyes

In a browser, use client tokens with the OpenAI or Anthropic SDK; never put a key in a page.

Create a client#

import { Hixel } from "@hixel/sdk";

// A key with the `management` scope. Falls back to HIXEL_API_KEY where `process.env` exists.
const hixel = new Hixel({
  apiKey: process.env.HIXEL_API_KEY,
  baseUrl: "https://api.hixel.dev",
});

const customer = await hixel.customers.upsert("org_42", { name: "Acme Inc." });
console.log(customer.id, customer.status);

The key alone works too, new Hixel(process.env.HIXEL_API_KEY), but such a client calls the production API unless HIXEL_BASE_URL names another.

On Cloudflare Workers there is no process.env: pass the key from the Worker's env.

import { Hixel } from "@hixel/sdk";

interface Env {
  HIXEL_API_KEY: string;
}

export default {
  async fetch(request: Request, env: Env): Promise<Response> {
    const hixel = new Hixel({ apiKey: env.HIXEL_API_KEY, baseUrl: "https://api.hixel.dev" });
    const wallet = await hixel.wallets.get("org_42");
    return Response.json({ balance: wallet.balance.total_micros });
  },
};
OptionDefaultMeaning
apiKeyHIXEL_API_KEYAn environment's key (hx_sk_…, hx_sk_test_…)
baseUrlHIXEL_BASE_URL, then the production APIThe API's origin, https://api.hixel.dev
environmentHIXEL_ENVIRONMENTWith a project key: the environment (env_…) environment calls act in
fetchthe global fetchThe fetch to call: a test double, a proxying fetch
webhookSecretHIXEL_WEBHOOK_SECRETThe signing secret hixel.webhooks.verify checks deliveries with
maxRetries2Retries of a failed call, when retrying is safe
timeout60000Milliseconds per attempt, the response body included

Each option left out is read from the environment where there is a process.env (Node, Bun, Deno): HIXEL_API_KEY, HIXEL_ENVIRONMENT, HIXEL_WEBHOOK_SECRET, and HIXEL_BASE_URL for the API's origin. Without baseUrl or HIXEL_BASE_URL, the client calls the production API, and only it: set one of them for any other host, such as a preview stage or a local stack. The samples on this site pass baseUrl explicitly so they say where they go. Set HIXEL_BASE_URL once in your deployment instead of passing it in code.

Every method also takes a last, optional argument of request options: idempotencyKey, signal, timeout, maxRetries and headers.

A key's scope decides what it can call: management for the management API, inference for models and clientTokens. If one service needs both, use one client per key.

The rest of this page uses hixel for a client created as above.

Resources#

Each namespace is a section of the API reference, and each method one of its operations, named after its operation id: customers.upsert is hixel.customers.upsert. Ids come first (path parameters, and the customer's external_id for customers.upsert), then the body or the query, then the request options. Path parameters are percent-encoded for you, so an external_id may hold /, ? or #.

// Customers and the provider keys they bring
await hixel.customers.upsert("org_42", { allowed_models: ["claude-sonnet-5-5"] });
await hixel.customers.block("org_42");
await hixel.customers.putProviderKey("org_42", "openai", { api_key: "sk-…" });

// The customer portal: a session for the signed-in member, then redirect to `url`
const session = await hixel.portalSessions.create("org_42", { member: "user_7", role: "admin" });
await hixel.customerPolicy.update("org_42", { team_budget_micros: "250000000" });
await hixel.members.put("org_42", "user_9", {
  budget: { type: "limit", limit_micros: "50000000" },
});
const effective = await hixel.members.effectivePolicy("org_42", "user_9");

// Wallets and credits
await hixel.wallets.grant("org_42", {
  amount_micros: "20000000",
  idempotency_key: "plan:org_42:2026-11",
  expires_at: "2026-12-01T00:00:00Z",
});
const wallet = await hixel.wallets.get("org_42");
await hixel.walletSettings.update({ low_balance_threshold_micros: "2000000" });

// Usage
const summary = await hixel.usage.series({
  from: "2026-11-01T00:00:00Z",
  to: "2026-12-01T00:00:00Z",
  bucket: "day",
  group_by: "customer",
});

// Keys: a key's secret is shown once
const { key, secret } = await hixel.keys.create({ name: "worker", scopes: ["inference"] });

// Webhook endpoints, top-ups, auto-refill, trace exports, gateway settings, the catalog
const endpoint = await hixel.webhookEndpoints.create({ url: "https://app.example.com/webhooks" });
const topUp = await hixel.topUps.create("org_42", {
  amount_micros: "25000000",
  success_url: "https://app.example.com/billing/paid",
  cancel_url: "https://app.example.com/billing",
});
const catalog = await hixel.catalog.listModels();

console.log(wallet.balance.total_micros, summary.series.length, key.id, secret);
console.log(endpoint.endpoint.id, topUp.checkout_url, catalog.models.length);
console.log(session.url, effective.models);
NamespaceCovers
hixel.keysKeys
hixel.customers, hixel.customerCountsCustomers, their provider keys and counts
hixel.customerPolicy, hixel.members, hixel.portalSessions, hixel.portalSettingsCustomer portal: team policies, members, portal sessions and the portal's brand
hixel.wallets, hixel.ledgerWallets, grants, credits, a customer's ledger and the environment's
hixel.walletSettingsWallet settings
hixel.usage, hixel.limitCrossingsUsage: records, summaries, analytics, limit crossings
hixel.webhookEndpointsWebhook endpoints
hixel.eventsEvents
hixel.traceExportDestinationsTrace export destinations
hixel.stripeConnectionStripe connection
hixel.topUpsTop-ups
hixel.paymentsPayments: summaries and reversals
hixel.autoRefills, hixel.autoRefillAttentionCountsAuto-refill
hixel.gateway, hixel.catalogGateway, Catalog, and the gateway helpers below
hixel.project, hixel.projectKeys, hixel.environments, hixel.auditLog, hixel.billingThe project's own sections, including Project billing: a project key
hixel.systemSystem: needs no key
hixel.models, hixel.clientTokensThe gateway's GET /v1/models and POST /v1/client_tokens (an inference key)
hixel.webhooksWebhook verification; needs no key

Responses are the API's JSON, untouched. Fields the SDK does not know yet are kept, and an enum value it does not know is passed through, never refused. Types are exported by name: Customer, Wallet, LedgerEntry, UsageRecord, HixelEvent, EventOf<"wallet.credited">, and the raw generated components and operations.

Project keys and environments#

A project key (hx_proj_…) manages the whole project. Give the client the key, then pick an environment for the environment's calls: either for the whole client, or per call site with hixel.environment(id), which returns a client for that environment sharing the same key and settings.

import { Hixel } from "@hixel/sdk";

const hixel = new Hixel({
  apiKey: process.env.HIXEL_PROJECT_KEY,
  baseUrl: "https://api.hixel.dev",
});

// The project's own calls need no environment.
const project = await hixel.project.get();
for await (const environment of hixel.environments.list()) {
  console.log(environment.id, environment.slug, environment.kind);
}

// An environment's calls go through a client for that environment (`x-hixel-environment`).
const staging = hixel.environment("env_k3j9x2m8q1w7e4r5t6y0u2i3");
await staging.gateway.update({ wallet: { enabled: true } });
const wallet = await staging.wallets.get("org_42");

// Or fix the environment for the whole client.
const production = new Hixel({
  apiKey: process.env.HIXEL_PROJECT_KEY,
  baseUrl: "https://api.hixel.dev",
  environment: "env_p0r1o2d3u4c5t6i7o8n9e0n1",
});
await production.customers.upsert("org_42", { name: "Acme Inc." });

console.log(project.name, wallet.balance.total_micros);

With an environment key, none of this is needed: the key is the environment. An environment call made with a project key and no environment fails with environment_required, and the project's own calls with an environment key fail with project_key_required. See Manage a project from code for the full walk-through.

Errors#

Every failure throws a HixelError. When the API answered, it carries the error envelope: status, type, code, message, param, and the response's requestId.

import { ConflictError, HixelError, NotFoundError } from "@hixel/sdk";

try {
  await hixel.wallets.grant("org_42", {
    amount_micros: "1000000",
    idempotency_key: "bonus:org_42",
  });
} catch (error) {
  if (error instanceof NotFoundError) {
    // No customer org_42 in this environment.
  } else if (error instanceof ConflictError && error.code === "credit_idempotency_key_reused") {
    // This body key already granted another amount: use a new key for a new grant.
  } else if (error instanceof HixelError) {
    console.error(error.status, error.type, error.code, error.param, error.requestId);
  }
  throw error;
}
ClasstypeStatus
InvalidRequestErrorinvalid_request400
AuthenticationErrorunauthenticated401
PaymentRequiredErrorpayment_required402
PermissionDeniedErrorpermission_denied403
NotFoundErrornot_found404
ConflictErrorconflict409
RateLimitErrorrate_limited429
UnavailableErrorunavailable503
InternalErrorinternal, any 5xx500
ConnectionErrorno response
TimeoutErrorno response in time

Branch on code, never on message. Your editor completes the codes the API documents, and code stays a string: new codes can appear.

Retries and idempotency#

A call is retried up to maxRetries times, with exponential backoff and jitter, after no response, a timeout, 408, 429, any 5xx, or 409 idempotency_key_in_use (the first attempt is still running). A retry-after of up to a minute is waited for exactly. Other errors are not retried: the request itself is wrong.

Retrying a write is safe because every write sends an Idempotency-Key, the same on every attempt of one call, so the API runs it once. By default each call gets a new random key. Pass your own to make a retry across calls, or across processes, safe for 24 hours:

const userId = "user_7";
await hixel.customers.upsert(
  "org_42",
  { name: "Acme Inc." },
  { idempotencyKey: `signup:${userId}` },
);

A replayed response never carries a secret: a replayed keys.create or webhookEndpoints.create answers secret: null, and a replayed portalSessions.create answers url: null.

Grants and credits have their own key. wallets.grant and wallets.credit require an idempotency_key in the body: the permanent, per-wallet key that guarantees a wallet is credited once, whoever retries and whenever. Choose it from what you are crediting for (a plan period, an invoice id). The SDK never derives the Idempotency-Key header from it: the header is scoped to the whole environment, where the same body key on two customers would collide. Reusing the body key with other values is credit_idempotency_key_reused; reusing the header's is idempotency_key_reused. See Grants and credits.

Pagination#

A list method returns its first page, which is also an async iterable over every item of every page, fetched as you go with the same filters:

for await (const record of hixel.usage.list({ customer: "org_42", limit: 100 })) {
  console.log(record.request_id, record.billed_micros);
}

const page = await hixel.usage.list({ limit: 100 });
console.log(page.data.length, page.next_cursor, page.hasMore);
const next = await page.nextPage(); // null after the last page
console.log(next?.data.length);

Keep next_cursor to resume later: pass it back as cursor. Every list of the management API pages the same way; the gateway's models.list is a single page.

Response metadata#

Every call has .withResponse(), for the HTTP response, the request id to quote to support, and whether the answer was replayed for a retried Idempotency-Key:

const { data, response, requestId, idempotentReplayed } = await hixel.customers
  .upsert("org_42", { name: "Acme Inc." })
  .withResponse();
console.log(data.id, response.status, requestId, idempotentReplayed);

requestId is the response's x-hixel-request-id, from the management API and the gateway alike.

Webhooks#

Verify a delivery before acting on it; no API key is needed. Give the client the endpoint's signing secret (webhookSecret, or HIXEL_WEBHOOK_SECRET from the environment) and pass it the web Request as it arrived: hixel.webhooks.verify reads the raw body and the hixel-signature header, checks the signature and its timestamp, and returns the event, typed by its type. It throws WebhookVerificationError for a delivery that is not genuine or not recent.

import { Hixel, WebhookVerificationError } from "@hixel/sdk";

const hixel = new Hixel({ webhookSecret: process.env.HIXEL_WEBHOOK_SECRET });

export async function POST(request: Request): Promise<Response> {
  let event;
  try {
    event = await hixel.webhooks.verify(request);
  } catch (error) {
    if (error instanceof WebhookVerificationError) return new Response(null, { status: 400 });
    throw error;
  }
  // Deduplicate on event.id: an event can arrive more than once.
  switch (event.type) {
    case "wallet.balance_low":
      console.log(event.data.customer, event.data.balance.total_micros);
      break;
    case "wallet.credited":
      console.log(event.data.kind, event.data.amount_micros);
      break;
    default:
      // An endpoint subscribed to `*` can receive types newer than this SDK: ignore them.
      break;
  }
  return new Response(null, { status: 204 });
}

Where there is no web Request (Express, AWS Lambda), pass the raw body and the headers: hixel.webhooks.verify({ body, headers }), with the body as the exact bytes or string that arrived (in Express, express.raw({ type: "application/json" }) on the route). Without a client, verifyWebhook(request, { secret }) does the same.

import { verifyWebhook } from "@hixel/sdk";

declare const rawBody: string; // the request's body, unparsed
declare const headers: Record<string, string>;

const event = await hixel.webhooks.verify({ body: rawBody, headers });
const sameEvent = await verifyWebhook(
  new Request("https://example.com", { method: "POST", body: rawBody, headers }),
  { secret: "whsec_…" },
);
console.log(event.id, sameEvent.id);

A failed check's reason says why (missing_header, malformed_header, signature_mismatch, timestamp_outside_tolerance, invalid_payload): answer 400 either way. The timestamp must be within five minutes of your clock ({ tolerance: seconds } changes it). While you rotate the secret on your side, give both, newest first: { secret: [newSecret, oldSecret] }. signWebhook makes a header for testing your handler.

The gateway#

The SDK does not wrap inference: keep the OpenAI or Anthropic SDK and point it at the gateway with hixel.gateway.baseUrl, naming the customer and member with hixel.gateway.headers. The gateway takes a key with the inference scope.

import Anthropic from "@anthropic-ai/sdk";
import OpenAI from "openai";
import { Hixel } from "@hixel/sdk";

const hixel = new Hixel({ apiKey: process.env.HIXEL_API_KEY, baseUrl: "https://api.hixel.dev" });

const openai = new OpenAI({
  apiKey: process.env.HIXEL_API_KEY,
  baseURL: hixel.gateway.baseUrl.openai, // https://api.hixel.dev/v1
});
const response = await openai.responses.create(
  { model: "gpt-6.2-sol", input: "Summarise this ticket in one line." },
  {
    headers: hixel.gateway.headers({
      customer: "org_42",
      member: "user_7",
      tags: ["feature:summarise"],
    }),
  },
);

const anthropic = new Anthropic({
  apiKey: process.env.HIXEL_API_KEY,
  baseURL: hixel.gateway.baseUrl.anthropic, // https://api.hixel.dev
});
const message = await anthropic.messages.create(
  { model: "claude-sonnet-5-5", max_tokens: 1024, messages: [{ role: "user", content: "Hi" }] },
  { headers: hixel.gateway.headers({ customer: "org_42" }) },
);

gateway.headers (also exported as gatewayHeaders) builds x-hixel-customer, x-hixel-member and x-hixel-tags, and throws a TypeError for a value the gateway would refuse, before anything is sent or charged. Read x-hixel-request-id from the OpenAI or Anthropic SDK's own response object.

The models a key may call, and a client token for a browser or app:

for await (const model of hixel.models.list({ customer: "org_42" })) console.log(model.id);

const { token, expires_at } = await hixel.clientTokens.create({
  customer: "org_42",
  member: "user_7",
  expires_in: 600,
  allowed_origins: ["https://app.example.com"],
});
console.log(token, expires_at);

Money#

Amounts are micro-USD as decimal strings (Amounts). Never turn one into a number: do arithmetic on bigints and send strings.

import { formatUsd, parseMicros, stringifyMicros, usdToMicros } from "@hixel/sdk";

parseMicros("1500000"); // 1500000n
stringifyMicros(1500000n); // "1500000"
usdToMicros("12.50"); // 12500000n
formatUsd("1500000"); // "$1.50"
formatUsd("1234567"); // "$1.234567": exact, never rounded

const total = parseMicros("1500000") + usdToMicros("12.50");
await hixel.wallets.credit("org_42", {
  kind: "adjustment",
  amount_micros: stringifyMicros(total),
  idempotency_key: "adjustment:org_42:2026-11-25",
});