Real-Time Virtual Try-On Quickstart
Add real-time virtual try-on to your site: prepare garments and start live sessions on your server, then stream the shopper's webcam with tryiton-live.
This guide adds live, real-time virtual try-on from the shopper's webcam to a web page.
It needs two pieces:
- Your server keeps the API key. It prepares garments and starts a session for each shopper, using an official SDK or the REST endpoints.
- The shopper's browser streams with
tryiton-live. It only ever sees the session-scoped response from step 1, never your key.
Your server ──(API key)──▶ POST /live/garments once per product, cached
Your server ──(API key)──▶ POST /live/sessions → start response
│ return the start response to the browser
Browser ── tryiton-live ──▶ camera ⇄ WebRTC ⇄ media provider (video never passes through TryItOn)
Browser ── tryiton-live ──▶ heartbeat / switch / end (session secret)You need an API key (dashboard Developer API → API Keys, see
Authentication & API Keys) and at least minCredits usable credits (5 by default)
to start a session. The Node.js samples are ES modules: use "type": "module" in package.json or a .mjs file.
Prepare your garments
Prepare each product once, for example when you sync your catalog, and store the returned id with the product.
Pass the category if you know it: detection can misread photos that show more than the item.
import { TryItOn } from "tryiton";
const client = new TryItOn({ apiKey: process.env.TRYITON_API_KEY });
const garment = await client.prepareLiveGarment({
garmentImage: "https://example.com/products/shirt.jpg",
category: "clothing",
subcategory: "tops",
});
console.log(garment.id); // store it with the productimport os
from tryiton import TryItOn
client = TryItOn(api_key=os.environ["TRYITON_API_KEY"])
garment = client.prepare_live_garment(
garment_image="https://example.com/products/shirt.jpg",
category="clothing",
subcategory="tops",
)
print(garment["id"]) # store it with the productpackage main
import (
"context"
"fmt"
"log"
"os"
"github.com/tryiton-now/tryiton-go/v2"
)
func main() {
client, err := tryiton.New(os.Getenv("TRYITON_API_KEY"))
if err != nil {
log.Fatal(err)
}
garment, err := client.PrepareLiveGarment(context.Background(), tryiton.PrepareLiveGarmentParams{
GarmentImage: "https://example.com/products/shirt.jpg",
Category: "clothing",
Subcategory: "tops",
})
if err != nil {
log.Fatal(err)
}
fmt.Println(garment.ID) // store it with the product
}<?php
require 'vendor/autoload.php';
use TryItOn\Client;
$client = new Client(getenv('TRYITON_API_KEY'));
$garment = $client->prepareLiveGarment([
'garment_image' => 'https://example.com/products/shirt.jpg',
'category' => 'clothing',
'subcategory' => 'tops',
]);
echo $garment['id'], PHP_EOL; // store it with the productrequire "tryiton"
client = Tryiton::Client.new(api_key: ENV.fetch("TRYITON_API_KEY"))
garment = client.prepare_live_garment(
garment_image: "https://example.com/products/shirt.jpg",
category: "clothing",
subcategory: "tops"
)
puts garment["id"] # store it with the productcurl -X POST https://tryiton.now/api/v1/live/garments \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_API_KEY" \
-d '{
"garment_image": "https://example.com/products/shirt.jpg",
"category": "clothing",
"subcategory": "tops"
}'Start a session on your server
Add an endpoint your page can call, here POST /live-session with a JSON body { "garmentId": "..." }. It starts a
session for the shopper and returns the start response unchanged. Replace shopper-42 with your signed-in
shopper's id: with end_user_id, each shopper gets one stream, and a reload ends their previous session.
import express from "express";
import { TryItOn } from "tryiton";
const client = new TryItOn({ apiKey: process.env.TRYITON_API_KEY });
const app = express();
app.use(express.json());
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
allowedOrigin: "https://shop.example.com", // locks the media token to your site
});
res.json(start);
} catch (err) {
res.status(err.status ?? 502).json({ error: err.errorName ?? "LiveStartFailed" });
}
});
app.listen(3000);import os
from flask import Flask, jsonify, request
from tryiton import TryItOn, TryItOnError
client = TryItOn(api_key=os.environ["TRYITON_API_KEY"])
app = Flask(__name__)
@app.post("/live-session")
def live_session():
try:
start = client.start_live_session(
garment_id=request.json["garmentId"],
end_user_id="shopper-42", # your signed-in shopper's id
allowed_origin="https://shop.example.com",
)
except TryItOnError as err:
return jsonify(error=err.error_name), err.status or 502
return jsonify(start)package main
import (
"encoding/json"
"errors"
"log"
"net/http"
"os"
"github.com/tryiton-now/tryiton-go/v2"
)
func main() {
client, err := tryiton.New(os.Getenv("TRYITON_API_KEY"))
if err != nil {
log.Fatal(err)
}
http.HandleFunc("/live-session", liveSession(client))
log.Fatal(http.ListenAndServe(":3000", nil))
}
func liveSession(client *tryiton.Client) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
var body struct {
GarmentID string `json:"garmentId"`
}
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
http.Error(w, "invalid JSON body", http.StatusBadRequest)
return
}
start, err := client.StartLiveSession(r.Context(), tryiton.StartLiveSessionParams{
GarmentID: body.GarmentID,
EndUserID: "shopper-42", // your signed-in shopper's id
AllowedOrigin: "https://shop.example.com",
})
if err != nil {
status := http.StatusBadGateway
var apiErr *tryiton.Error
if errors.As(err, &apiErr) && apiErr.Status != 0 {
status = apiErr.Status
}
http.Error(w, err.Error(), status)
return
}
// Marshals back to the same JSON the API returned, which the browser passes to connectLiveTryOn.
w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(start); err != nil {
log.Println(err)
}
}
}<?php
require 'vendor/autoload.php';
use TryItOn\Client;
use TryItOn\TryItOnException;
$client = new Client(getenv('TRYITON_API_KEY'));
$body = json_decode(file_get_contents('php://input'), true) ?? [];
header('Content-Type: application/json');
try {
$start = $client->startLiveSession([
'garment_id' => $body['garmentId'] ?? null,
'end_user_id' => 'shopper-42', // your signed-in shopper's id
'allowed_origin' => 'https://shop.example.com',
]);
echo json_encode($start);
} catch (TryItOnException $e) {
http_response_code($e->status ?? 502);
echo json_encode(['error' => $e->errorName]);
}require "json"
require "sinatra"
require "tryiton"
TRYITON = Tryiton::Client.new(api_key: ENV.fetch("TRYITON_API_KEY"))
post "/live-session" do
content_type :json
payload = JSON.parse(request.body.read)
begin
start = TRYITON.start_live_session(
garment_id: payload["garmentId"],
end_user_id: "shopper-42", # your signed-in shopper's id
allowed_origin: "https://shop.example.com"
)
start.to_json
rescue Tryiton::Error => e
halt (e.status || 502), { error: e.error_name }.to_json
end
endStream in the browser
npm install tryiton-live<video id="tryon" autoplay playsinline muted></video>import { connectLiveTryOn, openCamera } from "tryiton-live";
const garmentId = "6b0827eba2f220ae7dd7c7fb"; // from step 1
const otherGarmentId = "6b0827eba2f220ae7dd7c7fc"; // another prepared garment
// 1. Camera first: the session holds a credit from the moment it starts.
const camera = await openCamera();
// 2. Ask your server for a session.
const start = await fetch("/live-session", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ garmentId }),
}).then((r) => r.json());
// 3. Stream.
const live = await connectLiveTryOn(start, {
camera,
onStream: (stream) => (document.getElementById("tryon").srcObject = stream),
onSecondsLeft: (s) => console.log(`${s}s left`),
onEnd: ({ reason, session }) => {
camera.getTracks().forEach((t) => t.stop());
console.log("ended:", reason, session?.creditsCharged, "credits");
},
});
// Swap garments on the running stream (no reconnect, free):
await live.switchGarment(otherGarmentId);
// Done:
await live.end();switchGarment lives on the browser live object that connectLiveTryOn returns, not on the server SDKs. It takes
any garment prepared on your account.
connectLiveTryOn resolves once the first try-on frame arrives, usually within a few seconds. If no video arrives
within 20 seconds (connectTimeoutMs), it rejects with a TryItOnLiveError and you aren't charged. The error's
code is one of camera_denied, camera_unavailable, garment_required, busy, connect_failed,
heartbeat_failed or http_error. When the page closes, tryiton-live ends the session for you.
Billing
Each credit buys secondsPerCredit seconds of video (2 s by default), counted from the first try-on frame, and the
stream stops when the balance runs out or max_seconds is reached. The exact rules for the held credit, partial
ticks and refunds are in Billing.
Bundlers
On Chromium, the media layer sends each outgoing video frame through a Web Worker, which it loads with
new URL(…, import.meta.url).
- Vite, webpack 5, Next.js: they emit the worker for you.
- esbuild, Bun, or a plain script tag: copy
node_modules/@decartai/sdk/dist/realtime/browser/frame-metadata-worker.jsnext to your bundle, or runnode node_modules/tryiton-live/scripts/copy-media-worker.mjs <outdir>.
Without the worker, the camera connects but no video is sent, and connectLiveTryOn rejects with
connect_failed (unbilled).
Debugging: pass { debug: true } to connectLiveTryOn to log connection states and media diagnostics to the
console, prefixed [tryiton-live].
Related
- Live Virtual Try-On API: every server endpoint, billing, end reasons and errors.
- Live Try-On Browser Endpoints: for building your own client.
- Virtual Try-On SDKs: install the server SDK for your language.
OpenAPI Spec
Download the OpenAPI 3.1 spec of the virtual try-on API to import it into Postman or Insomnia, generate a client, or hand it to an LLM agent.
Node.js
Use the virtual try-on API from Node.js and TypeScript with the tryiton SDK: clothing, hairstyle and tattoo try-ons, errors, and live sessions in Express.