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 store | Headless (Hydrogen) store | |
|---|---|---|
| Storefront | Shopify theme | Your React app on Oxygen |
| How try-on is added | Install the Shopify app, add the block | One server route and one component |
| Billing | Shopify plan, on your Shopify invoice | Developer API credits, prepaid |
| Guide | Shopify | This page |
How it works
POST /api/try-on (photo + product image URL)
POST /api/v1/generate (X-API-KEY)
200 image/png
200 image/png
- The shopper taps Try it on on a product page and takes or uploads a photo.
- The browser sends the photo and the product's image URL to your Hydrogen route.
- Your route calls TryOnCloud with your secret key and gets the finished image back, usually in about 20 seconds.
- 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:
TRYONCLOUD_API_KEY=tk_dev_v1_your_key_hereFor 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:
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.
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).
4. Add the button to the product page
Create app/components/TryOnButton.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:
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:
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
- 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. - Try a few products: tops, dresses, sarees, kurta sets and bottoms.
- Try a photo that is too large, and a non-image file, and check the error messages.
- Remove
?mock=trueand 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:
| Need | How |
|---|---|
| Separate staging and production | Create 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 networks | Send 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 audit | Every response carries X-Request-Id. Log it with your errors and quote it to us. |
| Shopper privacy requests | Send customer_id, then erase that shopper's data with DELETE /api/v1/customers/:id. Shopper photos are never stored by default. |
| Popular products | The garment analysis is cached for 30 days, so repeat try-ons of the same product photo are about 2 seconds faster. |
| Catalogue imagery | Create 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 peaks | 300 requests per minute per key and 600 per account. Before a big sale or festive launch, tell us so capacity is planned. |
| Monitoring | Live success rate and speed at /status, usage per key in Generations (search, CSV export). |
| Client generators | OpenAPI 3.1 spec at /api/v1/openapi.json. |
8. Go-live checklist
TRYONCLOUD_API_KEYis a secret variable in the production Oxygen environment- The key appears nowhere in browser code or the page source
?mock=trueremoved from the routeblob:added toimgSrc- Product images come from
cdn.shopify.comand 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-Keysent on every try-on, andX-Request-Idlogged 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.
Related
- Generate a try-on: every field and response
- Errors and limits
- Async jobs, batches and webhooks
- API status and the OpenAPI spec
- Data and privacy and the Data Processing Agreement