Docs
SDKs

Node.js SDKs.

Typed, generated from the live OpenAPI specs, MIT-licensed, server-side.

Every product on the ProductCraft platform ships an official Node.js / TypeScript SDK published to npm. The SDKs are generated from the same OpenAPI specs the API reference docs render from — so the types you see in your editor always match the wire shape in production.


Install

Pick one product or grab the umbrella

Install the per-product package when you only need one surface. Install the umbrella when you call more than one from the same backend — it pulls each per-product package as a dependency.

install one product
npm install @productcraft/auth
# or
pnpm add @productcraft/mail
# or
yarn add @productcraft/waitlist
install the umbrella
npm install productcraft

Packages

What's on npm

All packages live under the @productcraft scope. The umbrella is the unscoped 'productcraft' package.

@productcraft/auth

Read more

@productcraft/mail

Read more

@productcraft/waitlist

Read more

@productcraft/social

Read more

@productcraft/trawl

Read more

@productcraft/flags

Read more

@productcraft/notify

Read more

@productcraft/platform-auth

Read more

@productcraft/auth-passport

Read more

productcraft

All-in-one umbrella package. One install, one auth credential, one class with every surface attached (`pc.auth`, `pc.mail`, `pc.waitlist`, …). Install this when you call more than one ProductCraft API from the same backend.

View on npm ↗

Read more

Configuration

Credentials from the environment

On the server, omit auth and every client reads your workspace API key from PRODUCTCRAFT_API_KEY. An explicit auth always wins. Hosts are never read from the environment: override them in code with baseUrl.

auth.consumer() takes its app slug from PRODUCTCRAFT_AUTH_APP when you omit it, and never reads a credential from the environment. Routes that need an app key (PAK) on the consumer side take an explicit auth.

This is a server-only fallback. Never put a key in a NEXT_PUBLIC_* variable or anything else your bundler inlines into browser code.

.env
PRODUCTCRAFT_API_KEY=pcft_live_...   # workspace API key
PRODUCTCRAFT_AUTH_APP=my-app-slug    # default slug for auth.consumer()

Runtime

What every generated client does

Every package is generated from its API's spec onto the same runtime, so each client below behaves the same way. Node 20.3 or later (also Bun, Deno and edge runtimes), ESM and CommonJS.

Typed errors

Every failure is a class you can catch: one per status (BadRequestError, AuthenticationError, PermissionDeniedError, NotFoundError, ConflictError, RateLimitError, InternalServerError, …) under APIError, plus APIConnectionError and APITimeoutError for the network. Each carries status, code, errors[], requestId and docUrl, a link into the error code catalogue.

errors.ts
import { Trawl, APIError, RateLimitError } from "@productcraft/trawl";

const trawl = new Trawl();

try {
  await trawl.jobs.retrieve("3f0c1a2b-4c5d-4e6f-8a9b-0c1d2e3f4a5b");
} catch (err) {
  if (err instanceof RateLimitError) {
    console.log("retry in", err.retryAfter, "s");
  } else if (err instanceof APIError) {
    // Every API error: status, code, request_id and a link to /docs/errors
    console.log(err.status, err.code, err.requestId, err.docUrl);
  } else {
    throw err;
  }
}

Retries and timeouts

Network errors, 408, 429, 5xx and 409 IDEMPOTENCY_IN_PROGRESS are retried twice by default with exponential backoff and jitter, honouring Retry-After up to 60 seconds. A POST or PATCH without an idempotency key is never retried. Each attempt times out after 60 seconds; pass an AbortSignal for an overall deadline.

retries.ts
import { Trawl } from "@productcraft/trawl";

// Client-wide: 3 retries, 20 s per attempt
const trawl = new Trawl({ maxRetries: 3, timeout: 20_000 });

// Per request: no retries, 5 s overall deadline
await trawl.jobs.list({}, { maxRetries: 0, signal: AbortSignal.timeout(5_000) });

Idempotency

Every operation that accepts an Idempotency-Key gets one automatically, reused on every retry, so a retried create never runs twice. Pass your own key to make a retry from another process or a queue safe as well.

idempotency.ts
import { Trawl } from "@productcraft/trawl";

const trawl = new Trawl();

// A key is generated for every create and reused on each retry.
// Pass your own to make a retry from another process safe too.
const job = await trawl.jobs.create(
  {
    description: "Extract the product title.",
    json_schema: { type: "object", required: ["title"] },
  },
  { idempotencyKey: "order-1234-extract" },
);
pagination.ts
import { Trawl } from "@productcraft/trawl";

const trawl = new Trawl();

// Every item across every page
for await (const job of trawl.jobs.list({ limit: 50 })) console.log(job.id);

// One page at a time
const page = await trawl.jobs.list();
if (page.hasNextPage()) await page.getNextPage();

// Collect, with a ceiling
const all = await trawl.jobs.list().toArray({ maxItems: 500 });

Polling

Long-running resources get poll() and createAndPoll(): they retrieve until the status is terminal, honour Retry-After, and throw APITimeoutError after timeoutMs.

polling.ts
import { Trawl } from "@productcraft/trawl";

const trawl = new Trawl();

type Product = { title: string };
const done = await trawl.jobs.createAndPoll<Product>(
  {
    description: "Extract the product title.",
    json_schema: { type: "object", required: ["title"] },
  },
  { intervalMs: 2_000, timeoutMs: 600_000 },
);
console.log(done.status, done.result?.title);

Webhooks

webhooks.unwrap() verifies the Standard Webhooks signature and returns a typed event. It needs the raw request body: a body your framework has already parsed as JSON no longer matches the signature. The secret comes from { secret }, the client's webhookSecret, or PRODUCTCRAFT_<PRODUCT>_WEBHOOK_SECRET.

app/webhooks/route.ts (Next.js)
import { Trawl } from "@productcraft/trawl";

// Secret from PRODUCTCRAFT_TRAWL_WEBHOOK_SECRET
const trawl = new Trawl();

export async function POST(req: Request) {
  // Verify against the RAW body: never JSON.parse it first.
  const event = await trawl.webhooks.unwrap({
    payload: await req.text(),
    headers: req.headers,
  });
  switch (event.type) {
    case "job.succeeded":
      console.log(event.data.job.id, event.data.job.result);
      break;
    case "job.failed":
      console.log(event.data.job.id, event.data.job.error);
      break;
    default:
      break; // credits.low and types added later
  }
  return new Response(null, { status: 204 });
}
server.ts (Express)
import express from "express";
import { Trawl } from "@productcraft/trawl";

const trawl = new Trawl(); // secret from PRODUCTCRAFT_TRAWL_WEBHOOK_SECRET
const app = express();

// express.raw keeps the body as bytes: a parsed body fails verification
app.post("/webhooks", express.raw({ type: "application/json" }), async (req, res) => {
  const event = await trawl.webhooks.unwrap({ payload: req.body, headers: req.headers });
  console.log(event.type);
  res.sendStatus(204);
});
server.ts (Hono)
import { Hono } from "hono";
import { Trawl } from "@productcraft/trawl";

const trawl = new Trawl();
const app = new Hono();

app.post("/webhooks", async (c) => {
  const event = await trawl.webhooks.unwrap({
    payload: await c.req.text(),
    headers: c.req.raw.headers,
  });
  console.log(event.type);
  return c.body(null, 204);
});

Raw responses

Every returned object has a non-enumerable lastResponse (requestId, status, headers). .withResponse() adds the Response and the parsed rate-limit headers.

raw-response.ts
import { Trawl } from "@productcraft/trawl";

const trawl = new Trawl();
const id = "3f0c1a2b-4c5d-4e6f-8a9b-0c1d2e3f4a5b";

const job = await trawl.jobs.retrieve(id);
console.log(job.lastResponse.requestId);

const { data, response, requestId, rateLimit } = await trawl.jobs
  .retrieve(id)
  .withResponse();
console.log(data.status, response.status, requestId, rateLimit?.remaining);

The .client escape hatch

.client stays on every package: the typed openapi-fetch client over the same credential and base URL, without retries. Use it for anything the resource methods do not cover. Code written against it before the generated methods keeps working.

client.ts
import { Trawl } from "@productcraft/trawl";

const trawl = new Trawl();

// .client: the typed openapi-fetch client, same key and base URL,
// no retries. For anything the resource methods do not cover.
const { data, error } = await trawl.client.GET(
  "/v1/workspaces/{workspace_id}/credits",
  { params: { path: { workspace_id: "9b2f6c1e-0d6a-4a63-9a43-2f1c3e4d5a6b" } } },
);
console.log(data, error);

Testing

@productcraft/<product>/testing exports createMockFetch(), a fetch that answers every operation with its spec example. See Testing without side effects.


Quickstart

Hello, Auth

A minimum viable Auth integration through the BFF pattern. End-user routes on auth.consumer(slug) need no key; admin routes send your workspace API key, so keep that server-side and never embed it in a browser bundle.

server.ts
import { Auth } from "@productcraft/auth";

declare const identityTokenFromAppleSdk: string;
declare const rawNonceClientGenerated: string;

// Consumer routes need no key (default slug: PRODUCTCRAFT_AUTH_APP)
const auth = new Auth();
const consumer = auth.consumer("my-app-slug");

// Email + password sign-in, discriminated on `result`
const signin = await consumer.signin({
  identifier: "alice@example.com",
  password: "...",
});
if (signin.result === "session") console.log(signin.access_token);

// Sign in with Apple (native iOS flow)
await consumer.signinWithProvider("apple", {
  id_token: identityTokenFromAppleSdk,
  nonce: rawNonceClientGenerated,
});

// Verify a token your client sent you
declare const bearer: string;
const claims = await auth.verifyToken(bearer, { app: "my-app-slug" });

Umbrella

Hello, ProductCraft

Install productcraft when you call more than one ProductCraft API from the same backend. One auth credential is shared across all surfaces; per-surfacebaseUrl overrides are available for staging environments.

server.ts
import { ProductCraft } from "productcraft";

// Reads PRODUCTCRAFT_API_KEY from the environment
// (Mail uses it; Auth's end-user sign-in never sends it)
const pc = new ProductCraft();

// Auth: sign in an end user
await pc.auth.consumer("my-app").signin({
  identifier: "alice@example.com",
  password: "...",
});

// Mail: send a template from the same backend. An Idempotency-Key
// is generated for you, so a retried send never mails twice.
await pc.mail.templates.send("welcome", {
  from: "hello@yourbrand.com",
  to: "alice@example.com",
  data: { name: "Alice" },
});

How they're built

Spec-driven, low maintenance

Every per-surface SDK regenerates from the live /docs-json OpenAPI spec of its API. A nightly CI job in clauderanelagh/productcraft-node refreshes the specs, regenerates the typed clients, and opens a PR with the diff. Merging triggers a Changesets release that publishes the affected packages to npm with provenance attestations.

What that means for you: the types in your editor always match what production accepts. New endpoints land in the SDK without you (or us) hand-rolling another binding.