Skip to Content
TryItOn
DocsAPI ReferenceSDKsResources

Virtual Try-On SDK for Node.js

Reference for the tryiton npm package: client options, methods, wait helpers, TryItOnError handling, live sessions and test stubs for Node.js and TypeScript.

The tryiton package is the official Node.js and TypeScript client for the virtual try-on API. It wraps every server endpoint of https://tryiton.now/api/v1, throws one error class, and polls jobs for you. New to the API? Run your first try-on with the Quickstart.

npm install tryiton

It needs Node.js 18 or later (it uses the global fetch) and ships TypeScript types, an ES module build and a CommonJS build (const { TryItOn } = require("tryiton");). The samples use import and top-level await, so save them as .mjs or set "type": "module" in package.json.

Configure the client

Retry GET requests only

A retried POST /tryon/* can create a second job and hold credits twice. The client below retries GET requests on 502, 503 and 504, and leaves every POST alone.

client.mjs
import { TryItOn } from "tryiton";

// Retry GETs (status, credits, sessions) on gateway errors. Never retry a POST:
// a retried submit can create a second job.
async function fetchWithRetry(url, init = {}) {
  for (let attempt = 1; ; attempt++) {
    const res = await fetch(url, init);
    const isRetryable = (init.method ?? "GET") === "GET" && [502, 503, 504].includes(res.status);
    if (!isRetryable || attempt === 3) return res;
    await res.body?.cancel(); // free the connection before the next attempt
    await new Promise((resolve) => setTimeout(resolve, attempt * 1000));
  }
}

const client = new TryItOn({
  apiKey: process.env.TRYITON_API_KEY,
  timeoutMs: 30_000,
  fetch: fetchWithRetry,
});

console.log(await client.getCredits());
OptionTypeDefaultDescription
apiKeystringrequiredYour API key. A missing key throws TryItOnError with errorName: "ConfigError".
baseUrlstringhttps://tryiton.now/api/v1API base URL. A trailing slash is removed.
timeoutMsnumber60000Timeout for each HTTP request, in milliseconds. A wait has its own timeout.
fetch(url, init) => Promise<Response>globalThis.fetchYour own fetch, for retries, logging, a proxy or a test stub.

Methods

Every method is async. Parameters are one object with camelCase keys; unset keys are left out of the request, so the API defaults apply.

MethodEndpointResolves to
tryOnFashion(params)POST /tryon/fashionjob id (string)
tryOnHairstyle(params)POST /tryon/hairstylejob id (string)
tryOnTattoo(params)POST /tryon/tattoojob id (string)
getStatus(jobId)GET /status/{id}StatusResponse (status, output, error)
waitForResult(jobId, opts)polls GET /status/{id}result URLs (string[])
getCredits()GET /creditsCredits
getLiveConfig()GET /live/configLiveConfig
prepareLiveGarment(params)POST /live/garmentsLiveGarment
prepareLiveOutfit(params)POST /live/outfitsLiveGarment
startLiveSession(params)POST /live/sessionsLiveSessionStart
listLiveSessions(params)GET /live/sessionsLiveSessionPage (sessions, nextCursor)
getLiveSession(sessionId)GET /live/sessions/{id}LiveSession
stopLiveSession(sessionId)POST /live/sessions/{id}/stopLiveSession

The package also exports HAIRCUTS (the 42 accepted haircut values), VERSION, and a type for every parameter object and response. Images are public URLs or base64 data URLs. The snippets below reuse the client from above.

const fashionJobId = await client.tryOnFashion({
  modelImage: "https://example.com/model.jpg",
  garmentImage: "https://example.com/tshirt.jpg",
  category: "clothing",
  subcategory: "tops",
});

const hairJobId = await client.tryOnHairstyle({
  faceImage: "https://example.com/face.jpg",
  haircut: "PixieCut",
  hairColor: "copper red",
});

const tattooJobId = await client.tryOnTattoo({
  bodyImage: "https://example.com/forearm.jpg",
  designImage: "https://example.com/rose.png",
  region: { x: 0.32, y: 0.18, w: 0.28, h: 0.34 },
});

Wait for results

waitForResult(jobId, { pollIntervalMs, timeoutMs, signal }) polls every 2000 ms and gives up after 120000 ms. It resolves with the result URLs, or throws ProcessingError (the job failed), Timeout or Aborted (the signal fired). Every job has a final status within 4 minutes, so a 4-minute wait never gives up early:

const urls = await client.waitForResult(fashionJobId, { timeoutMs: 240_000 });

Timeout and Aborted only stop the wait. The job keeps running, so poll it later instead of resubmitting. To check a stored job id from a worker, call getStatus yourself:

const job = await client.getStatus(fashionJobId);
if (job.status === "completed") console.log(job.output);
else if (job.status === "failed") console.error(job.error);

error is the failure reason as a string, or null. See Jobs, Polling & Retries for job lifetimes.

Errors

Every API error and failed job throws TryItOnError. Branch on errorName, not on the message.

FieldTypeDescription
statusnumber or nullHTTP status. null for errors raised by the SDK.
errorNamestring or nullThe API error name, such as OutOfCredits, or an SDK name below. null for a non-JSON error page.
messagestringHuman-readable text. For ProcessingError, the job's failure reason.
import { TryItOnError } from "tryiton";

try {
  const urls = await client.waitForResult(fashionJobId, { timeoutMs: 240_000 });
  console.log(urls[0]);
} catch (err) {
  if (!(err instanceof TryItOnError)) throw err;
  if (err.errorName === "ProcessingError") console.error("Failed, not charged:", err.message);
  else if (err.errorName === "Timeout") console.error("Still running. Poll it later.");
  else console.error(`${err.status} ${err.errorName}: ${err.message}`);
}

The SDK adds these names, all with status: null: ProcessingError, Timeout (the wait gave up, or one request hit timeoutMs), Aborted, NetworkError (no response) and ConfigError. RateLimitExceeded, ConcurrencyLimitExceeded, 500 and 503 are worth retrying with backoff. OutOfCredits, 400, 403, 404 and 413 are not. See when to retry and the full list of error codes.

Verify webhooks

verifyWebhook (SDK 2.5 or later) checks that a webhook request came from TryItOn and returns the event. Pass the raw body exactly as it arrived.

import express from "express";
import { verifyWebhook, TryItOnError } from "tryiton";

const app = express();

// express.raw keeps the exact bytes that were signed.
app.post("/webhooks/tryiton", express.raw({ type: "application/json" }), async (req, res) => {
  let event;
  try {
    event = await verifyWebhook(req.body, req.headers, process.env.TRYITON_WEBHOOK_SECRET);
  } catch (err) {
    if (err instanceof TryItOnError) return res.sendStatus(400);
    throw err;
  }
  res.sendStatus(200);
  if (event.type === "tryon.completed") console.log(event.data.jobId, event.data.output);
});

verifyWebhook(payload, headers, secret, { toleranceSeconds, now }) is async. payload is a string, Buffer or Uint8Array; headers is req.headers or a Headers object. It throws TryItOnError with errorName: "WebhookVerificationFailed" and status: null. It uses Web Crypto, so it also runs on edge runtimes, Deno and Bun.

Live try-on from your server

Your server prepares garments and starts sessions with the API key. The shopper's browser streams with the tryiton-live package and never sees the key.

server.mjs
import express from "express";
import { TryItOn, TryItOnError } from "tryiton";

const client = new TryItOn({ apiKey: process.env.TRYITON_API_KEY });

// Once per product, for example at catalog sync. Store garment.id.
const garment = await client.prepareLiveGarment({
  garmentImage: "https://example.com/tshirt.jpg",
  category: "clothing",
  subcategory: "tops",
});

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

// The browser POSTs { garmentId } and passes the response to connectLiveTryOn.
app.post("/live-session", async (req, res) => {
  try {
    const start = await client.startLiveSession({
      garmentId: req.body.garmentId,
      endUserId: "shopper-42", // your signed-in shopper's id, from your session
      allowedOrigin: "https://shop.example.com",
    });
    res.json(start); // unchanged
  } catch (err) {
    const status = err instanceof TryItOnError && err.status ? err.status : 502;
    res.status(status).json({ ok: false, error: { name: err.errorName, message: err.message } });
  }
});

app.listen(3000);

endUserId gives each shopper one stream: starting again ends the previous one. allowedOrigin locks the media token to your site. Sessions start on the primary stream and switch to the backup stream if it fails to connect. prepareLiveOutfit({ garmentIds }) combines 2 or 3 prepared garments, and its id works like a garment id. The browser side is in the Real-Time Virtual Try-On Quickstart, and billing in Live Try-On Billing.

Testing

Pass a stub fetch to test your code without network calls or credits:

client.test.mjs
import assert from "node:assert";
import { TryItOn } from "tryiton";

const calls = [];
const client = new TryItOn({
  apiKey: "YOUR_API_KEY",
  fetch: async (url, init) => {
    calls.push({ url, method: init.method, body: JSON.parse(init.body) });
    return new Response(JSON.stringify({ ok: true, jobId: "job_123" }), { status: 201 });
  },
});

const jobId = await client.tryOnFashion({
  modelImage: "https://example.com/model.jpg",
  garmentImage: "https://example.com/tshirt.jpg",
});

assert.equal(jobId, "job_123");
assert.equal(calls[0].url, "https://tryiton.now/api/v1/tryon/fashion");
assert.equal(calls[0].body.model_image, "https://example.com/model.jpg");

Return { ok: false, error: { name, message } } with a 4xx status to test your error handling.

On this page