Skip to content

About

Official Node.js & TypeScript SDK for the TryItOn AI virtual try-on API (clothing, accessories, hairstyle, tattoo).

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Repository files navigation

TryItOn Node.js SDK — AI Virtual Try-On API for JavaScript & TypeScript

Official Node.js and TypeScript client for the TryItOn virtual try-on API. Add photoreal AI virtual try-on for clothing, accessories, hairstyles, and tattoos to your JavaScript or TypeScript application with a few lines of code.

Virtual try-on API: a shopper photo plus a product image returns a photo of the shopper wearing the product

  • Virtual clothing try-on and accessory try-on (eyewear, footwear, headwear, jewelry)
  • Hairstyle and tattoo try-on
  • Fully typed, zero runtime dependencies (uses the native fetch API)
  • Built-in job polling helper

Full API reference: docs.tryiton.now · Get an API key: tryiton.now/app/developer

Installation

npm install tryiton

Requires Node.js 18 or later (or any runtime with a global fetch, such as Bun, Deno, or modern browsers). TypeScript types are bundled.

Quickstart: run a virtual try-on

Submit a garment and a model photo, then wait for the generated result image.

import { TryItOn } from "tryiton";

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

// Submit a clothing try-on
const jobId = await client.tryOnFashion({
  modelImage: "https://example.com/model.jpg",
  garmentImage: "https://example.com/tshirt.jpg",
  category: "clothing",
  subcategory: "tops",
});

// Poll until the job completes and return the output image URL(s)
const [resultUrl] = await client.waitForResult(jobId);
console.log(resultUrl); // CDN URL, available for 72 hours

Image inputs accept a public URL or a base64 data URL (data:image/png;base64,...).

Photo job lifecycle. POST /tryon/* returns 201 with a job id, and the job's credits are held. The job is then processing: poll GET /status/{id} every 2 seconds; most jobs finish within a minute. It ends as completed, with the result image URLs in output and the credits charged, or as failed, with the reason in error and the held credits released.

A job is processing until it ends as completed or failed. Only completed jobs are charged.

Core parameters

tryOnFashion covers clothing and accessory try-on. The most important parameters:

Parameter Type Required Description
modelImage string Yes URL or base64 data URL of the person.
garmentImage string Yes URL or base64 data URL of the garment or accessory.
category string No Item type: auto, clothing, eyewear, footwear, headwear, jewelry, accessories, or others. auto detects it for you.
subcategory string No Required for clothing (tops, bottoms, dresses), jewelry, and accessories.

Additional options (mode and moderationLevel for clothing; numSamples 1–4 and outputFormat png/jpeg for every try-on, including hairstyle and tattoo) are documented in the API reference.

Other endpoints

// Hairstyle try-on (see the HAIRCUTS export for all supported values)
await client.tryOnHairstyle({ faceImage, haircut: "BuzzCut", hairColor: "ash blonde" });

// Tattoo try-on — place it with free text...
await client.tryOnTattoo({ bodyImage, designImage, placement: "on the right forearm, small" });
// ...or pin the exact spot with a region box (normalized 0–1, from the image's top-left)
await client.tryOnTattoo({ bodyImage, designImage, region: { x: 0.32, y: 0.18, w: 0.28, h: 0.34 } });

// Poll a job manually, or check your credit balance
const status = await client.getStatus(jobId);   // { status, output, error }
const credits = await client.getCredits();        // { on_demand, subscription, purchased, reserved }

Live try-on (real-time webcam)

Live virtual try-on: outfits swap on a moving shopper in real time

Your server prepares garments and starts sessions with the API key. The shopper's browser streams with the tryiton-live package, using only the session-scoped response.

Live try-on architecture. Your server keeps the API key and uses it to prepare garments and start sessions on the TryItOn API. It passes the start response, which holds no API key, to the shopper's browser. In the browser, tryiton-live opens the camera and streams the video over WebRTC to the media network, which returns the try-on video. The browser sends heartbeats, garment switches, failover and end to the TryItOn API with the session secret.
// Once per product, e.g. at catalog sync (cached per image + category):
const garment = await client.prepareLiveGarment({ garmentImage: productImageUrl, category: "clothing", subcategory: "tops" });

// When a shopper opens live try-on. Return `start` to the browser as-is:
const start = await client.startLiveSession({
  garmentId: garment.id,
  endUserId: shopper.id,                       // one stream per end user
  providers: ["vidu", "ikawn"],                // tryiton-live's LIVE_PROVIDERS (0.5+)
});

await client.getLiveSession(start.session.id);   // { status, seconds, creditsCharged, refunded, ... }
await client.stopLiveSession(start.session.id);  // end it from your server
await client.getLiveConfig();                    // { enabled, secondsPerCredit, maxSeconds, ... }

Billing is per secondsPerCredit seconds of streamed video, from the first try-on frame. Garment switches during a session are free.

prepareLiveGarment also takes optional overrides:

await client.prepareLiveGarment({
  garmentImage: productImageUrl,
  category: "footwear",
  detailImages: [sideViewUrl, backViewUrl],               // up to 3 extra views; they only sharpen the description
  description: "black leather knee-high boots",           // your description (max 200), used in the generated prompt
  instructions: "Replace only the shoes with the boots.", // or your own prompt (max 1000), used verbatim
  enhancePrompt: false,                                   // keep the prompt as-is (default true)
});

Outfits

Combine 2–3 prepared garments into one outfit worn together. The outfit's id works wherever a garment id does (startLiveSession, the browser's switchGarment). To swap one item, prepare the new combination (cached) and switch to it.

const top = await client.prepareLiveGarment({ garmentImage: shirtUrl, category: "clothing", subcategory: "tops" });
const trousers = await client.prepareLiveGarment({ garmentImage: trousersUrl, category: "clothing", subcategory: "bottoms" });
const shoes = await client.prepareLiveGarment({ garmentImage: shoesUrl, category: "footwear" });

const outfit = await client.prepareLiveOutfit({ garmentIds: [top.id, trousers.id, shoes.id] });
// outfit.category === "outfit", outfit.items = the garment ids top to bottom
const start = await client.startLiveSession({ garmentId: outfit.id, endUserId: shopper.id });

// Later the shopper picks another top: prepare that outfit and switch the running stream to it.
const jacket = await client.prepareLiveGarment({ garmentImage: jacketUrl, category: "clothing", subcategory: "tops" });
const next = await client.prepareLiveOutfit({ garmentIds: [jacket.id, trousers.id, shoes.id] });
// In the browser (tryiton-live): await live.switchGarment(next.id);

prepareLiveOutfit also takes instructions and enhancePrompt, as above.

Session history

List your sessions, newest first, for usage reports or billing checks. Every session carries creditsCharged, refunded (the held credit was given back for a failed connect, or support refunded it), creditsRefunded (credits support refunded by hand) and apiKeyId (the key that started it).

let cursor: string | undefined;
do {
  const page = await client.listLiveSessions({ limit: 100, status: "ended", cursor });
  for (const s of page.sessions) console.log(s.id, s.endReason, s.creditsCharged, s.refunded);
  cursor = page.nextCursor ?? undefined;
} while (cursor);

Filters (all optional): limit (1–100, default 20), cursor, status ("active" | "ended"), endReason, apiKeyId and refunded: true (only refunded sessions).

Webhooks

Set up an endpoint in the dashboard and we POST a signed tryon.completed or tryon.failed event when a job finishes, so you don't have to poll. verifyWebhook checks the signature and returns the event. Pass the raw body: parsed and re-serialized JSON doesn't verify.

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

const app = express();

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

It throws a TryItOnError with errorName "WebhookVerificationFailed" when a header is missing, the timestamp is more than 5 minutes off (toleranceSeconds changes that), no signature matches or the body isn't JSON. It uses Web Crypto, so it also runs on edge runtimes, Deno and Bun. See the webhooks guide.

Error handling

All failures throw TryItOnError, which carries the HTTP status code and the API error name.

import { TryItOn, TryItOnError } from "tryiton";

try {
  await client.tryOnFashion({ /* ... */ });
} catch (err) {
  if (err instanceof TryItOnError) {
    console.error(err.status, err.errorName, err.message); // e.g. 429, "OutOfCredits"
  }
}

Notes

  • Output image URLs expire 72 hours after completion. Download any results you want to keep.
  • Failed jobs are never charged.

Documentation

Full documentation, parameter reference, and guides: docs.tryiton.now

Development

npm ci
npm test            # vitest: contract cases + unit tests
npx tsc --noEmit    # type check
npm run build       # tsup → dist/ (ESM + CJS + .d.ts)

test/fixtures/sdk-cases.json holds the contract cases every TryItOn SDK runs against a fake HTTP layer. It is generated: edit tryiton/backend/api-contract/sdk-cases.json in the main repo, then run node tryiton-sdk/sync-contract.mjs to copy it into each SDK. Changes are listed in CHANGELOG.md.

License

MIT

About

Official Node.js & TypeScript SDK for the TryItOn AI virtual try-on API (clothing, accessories, hairstyle, tattoo).

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages