Search docs

Search the TryOnCloud API docs

Platforms

Shopify Hydrogen (headless)

Headless Shopify on Hydrogen and Oxygen: one server route and a product-page button.

Add virtual try-on to a headless Shopify storefront built with Hydrogen and hosted on Oxygen. It takes one server route and one product-page component, and the API key never reaches the browser.

What "headless" means

A normal Shopify store renders its pages with a theme. Our Shopify app adds the try-on button to that theme with no code.

A headless store keeps Shopify for products, cart, checkout and payments, but the storefront shoppers see is a separate React app built by your developers. Hydrogen is Shopify's framework for that app and Oxygen is Shopify's hosting for it. Because there is no theme, theme app blocks do not appear, so a headless store adds try-on through the Developer API instead.

Theme storeHeadless (Hydrogen) store
StorefrontShopify themeYour React app on Oxygen
How try-on is addedInstall the Shopify app, add the blockOne server route and one component
BillingShopify plan, on your Shopify invoiceDeveloper API credits, prepaid
GuideShopifyThis page

How it works

Shopper browser
Your Hydrogen route

POST /api/try-on (photo + product image URL)

â–¶

POST /api/v1/generate (X-API-KEY)

â—€

200 image/png

â—€

200 image/png

â—€
  1. The shopper taps Try it on on a product page and takes or uploads a photo.
  2. The browser sends the photo and the product's image URL to your Hydrogen route.
  3. Your route calls TryOnCloud with your secret key and gets the finished image back, usually in about 20 seconds.
  4. The shopper sees themselves wearing the product. Nothing is stored by TryOnCloud unless you turn result storage on.

1. Get an API key

Sign up, open Dashboard > API Keys and create a key. It starts with tk_dev_v1_ and is shown in full only once. Your account starts with free try-ons, and test mode (?mock=true) is always free.

2. Store the key in Oxygen

In the Shopify admin open Hydrogen > your storefront > Storefront settings > Environments and variables and add a secret variable:

bash
TRYONCLOUD_API_KEY=tk_dev_v1_your_key_here

For local development, pull it into .env with npx shopify hydrogen env pull, or add it to .env by hand. Then add it to the Env type in env.d.ts so context.env is typed:

ts
interface Env extends HydrogenEnv {
  TRYONCLOUD_API_KEY: string
}

3. Add the server route

Create app/routes/api.try-on.tsx. Hydrogen serves it at /api/try-on. The route only accepts product images from your own Shopify CDN, so nobody can use your key to try on random images.

ts
import type { Route } from "./+types/api.try-on"

const MAX_PHOTO_BYTES = 15 * 1024 * 1024

export async function action({ request, context }: Route.ActionArgs) {
  if (request.method !== "POST") return new Response("Method not allowed", { status: 405 })

  const incoming = await request.formData()
  const person = incoming.get("person")
  const garmentUrl = incoming.get("garmentUrl")
  // One id per try-on, made in the browser. A retry with the same id is never charged twice.
  const tryOnId = incoming.get("tryOnId")

  if (!(person instanceof Blob) || person.size === 0 || person.size > MAX_PHOTO_BYTES) {
    return Response.json({ error: "Please add a photo under 15MB." }, { status: 400 })
  }
  // Only your own product images: blocks anyone using this route as a free try-on service.
  if (typeof garmentUrl !== "string" || !garmentUrl.startsWith("https://cdn.shopify.com/")) {
    return Response.json({ error: "Invalid product image." }, { status: 400 })
  }

  const form = new FormData()
  form.append("person_image", person, "person.jpg")
  form.append("garment_url", garmentUrl)
  // Optional: your own shopper id (for example a hash of the Customer Account id),
  // so you can find this shopper's try-ons and erase them on request.
  // form.append("customer_id", shopperId)

  const headers: Record<string, string> = { "X-API-KEY": context.env.TRYONCLOUD_API_KEY }
  if (typeof tryOnId === "string" && /^[\w-]{8,64}$/.test(tryOnId)) headers["Idempotency-Key"] = tryOnId

  const res = await fetch("https://www.tryoncloud.com/api/v1/generate", {
    method: "POST",
    headers,
    body: form,
    signal: AbortSignal.timeout(120_000),
  })
  const requestId = res.headers.get("X-Request-Id") ?? ""

  if (!res.ok) {
    const { error, code } = await res.json()
    console.error("try-on failed", code, requestId) // quote requestId to TryOnCloud support
    return Response.json({ error, code }, { status: res.status })
  }
  return new Response(res.body, {
    headers: { "Content-Type": "image/png", "Cache-Control": "no-store", "X-Request-Id": requestId },
  })
}

On an older Remix-based Hydrogen project, import the types from @shopify/remix-oxygen instead: import type { ActionFunctionArgs } from "@shopify/remix-oxygen", and type the action as ({ request, context }: ActionFunctionArgs).

Note: A try-on takes about 20 seconds. Keep the request open and do not add a shorter timeout in front of this route. Failed try-ons are refunded automatically.

4. Add the button to the product page

Create app/components/TryOnButton.tsx:

tsx
import { useState } from "react"

export function TryOnButton({ productImageUrl }: { productImageUrl: string }) {
  const [result, setResult] = useState<string | null>(null)
  const [busy, setBusy] = useState(false)
  const [error, setError] = useState<string | null>(null)

  async function onFile(file: File) {
    setBusy(true)
    setError(null)
    const form = new FormData()
    form.append("person", file)
    form.append("garmentUrl", productImageUrl)
    form.append("tryOnId", crypto.randomUUID()) // reuse the same id if you add a "Retry" button
    try {
      const res = await fetch("/api/try-on", { method: "POST", body: form })
      if (!res.ok) throw new Error((await res.json()).error ?? "Try-on failed")
      setResult(URL.createObjectURL(await res.blob()))
    } catch (e) {
      setError(e instanceof Error ? e.message : "Try-on failed")
    } finally {
      setBusy(false)
    }
  }

  return (
    <div>
      <label>
        {busy ? "Creating your look..." : "Try it on"}
        <input
          type="file"
          accept="image/*"
          capture="user"
          hidden
          disabled={busy}
          onChange={(e) => e.target.files?.[0] && onFile(e.target.files[0])}
        />
      </label>
      <p>Your photo is used only to create this image and is not stored.</p>
      {error && <p role="alert">{error}</p>}
      {result && <img src={result} alt="You wearing this product" />}
    </div>
  )
}

Then render it in your product route, app/routes/products.$handle.tsx, with the image of the selected variant, falling back to the product's main image:

tsx
const garmentUrl =
  product.selectedOrFirstAvailableVariant?.image?.url ?? product.featuredImage?.url

{garmentUrl && <TryOnButton productImageUrl={garmentUrl} />}

Make sure your product query requests image { url } on the variant and featuredImage { url } on the product.

5. Allow the result image in your CSP

Hydrogen sends a strict Content Security Policy. The result is shown from a blob: URL, so add blob: to imgSrc in app/entry.server.tsx:

ts
const { nonce, header, NonceProvider } = createContentSecurityPolicy({
  shop: { checkoutDomain: context.env.PUBLIC_CHECKOUT_DOMAIN, storeDomain: context.env.PUBLIC_STORE_DOMAIN },
  imgSrc: ["'self'", "https://cdn.shopify.com", "data:", "blob:"],
})

No connectSrc change is needed: the browser only talks to your own /api/try-on route.

6. Test before going live

  1. Point the route at test mode while you build: use https://www.tryoncloud.com/api/v1/generate?mock=true. It runs every check and returns the photo unchanged, with no credit used.
  2. Try a few products: tops, dresses, sarees, kurta sets and bottoms.
  3. Try a photo that is too large, and a non-image file, and check the error messages.
  4. Remove ?mock=true and run real try-ons.

7. Run it at retail scale

Large catalogues and many stores need a little more than a button. All of this is built in:

NeedHow
Separate staging and productionCreate one key per environment on API Keys. Give the staging key a monthly credit limit and an expiry date, so tests can never spend production credits.
Safe retries on mobile networksSend an Idempotency-Key (the tryOnId above). A retry of the same try-on after a dropped connection is charged once, and the button is disabled while a try-on runs, so a double tap cannot start a second one.
Support and auditEvery response carries X-Request-Id. Log it with your errors and quote it to us.
Shopper privacy requestsSend customer_id, then erase that shopper's data with DELETE /api/v1/customers/:id. Shopper photos are never stored by default.
Popular productsThe garment analysis is cached for 30 days, so repeat try-ons of the same product photo are about 2 seconds faster.
Catalogue imageryCreate on-model photos for many SKUs with POST /api/v1/batches (up to 500 per batch) and a signed webhook when each is ready. See async jobs, batches and webhooks.
Traffic peaks300 requests per minute per key and 600 per account. Before a big sale or festive launch, tell us so capacity is planned.
MonitoringLive success rate and speed at /status, usage per key in Generations (search, CSV export).
Client generatorsOpenAPI 3.1 spec at /api/v1/openapi.json.

8. Go-live checklist

  • TRYONCLOUD_API_KEY is a secret variable in the production Oxygen environment
  • The key appears nowhere in browser code or the page source
  • ?mock=true removed from the route
  • blob: added to imgSrc
  • Product images come from cdn.shopify.com and show the garment clearly
  • Privacy line shown next to the button (photo used only for the try-on, not stored)
  • Credits topped up. We email the account owner automatically when the balance drops to 10% of the last purchase (at least 20 credits)
  • A production key separate from the staging key, each with the monthly credit limit you want
  • Idempotency-Key sent on every try-on, and X-Request-Id logged on errors

Timeline

A Hydrogen team usually needs 1 to 2 weeks for a pilot: a day to add the key and test in mock mode, two or three days for the route and the product-page button, and the rest for QA on real products and a staged rollout.

Stores too

Have physical stores as well? The in-store kiosk runs try-on on a screen or smart mirror, including shoppers holding a garment up to the camera. It uses the same account.

Pricing

Headless stores use Developer API credits: prepaid, never expire, and a failed try-on is never charged. See pricing. For high volumes or a pilot across many stores, contact us for enterprise pricing.