Platforms
React and Next.js
Add try-on to a React or Next.js storefront with a server route.
Add try-on to a React or Next.js storefront. The browser sends the shopper's photo to your server route, and your route calls TryOnCloud with the API key. The key never reaches the browser.
Browser
Your Next.js route
POST /api/try-on (photo + product image URL)
â–¶
POST /api/v1/generate (X-API-KEY)
â—€
200 image/png
â—€
200 image/png
â—€
1. Add your key
.env.local:
bash
TRYONCLOUD_API_KEY=tk_dev_v1_your_key_here2. Server route (App Router)
app/api/try-on/route.ts:
ts
export const runtime = "nodejs"
export const maxDuration = 120
export async function POST(req: Request) {
const incoming = await req.formData()
const person = incoming.get("person")
const garmentUrl = incoming.get("garmentUrl")
if (!(person instanceof Blob) || typeof garmentUrl !== "string") {
return Response.json({ error: "person file and garmentUrl are required" }, { status: 400 })
}
const form = new FormData()
form.append("person_image", person, "person.jpg")
form.append("garment_url", garmentUrl)
const res = await fetch("https://www.tryoncloud.com/api/v1/generate", {
method: "POST",
headers: { "X-API-KEY": process.env.TRYONCLOUD_API_KEY! },
body: form,
signal: AbortSignal.timeout(120_000),
})
if (!res.ok) {
const { error, code } = await res.json()
return Response.json({ error, code }, { status: res.status })
}
return new Response(await res.arrayBuffer(), { headers: { "Content-Type": "image/png" } })
}On the Pages Router, put the same logic in pages/api/try-on.ts and disable the default body parser so the file upload passes through.
3. Try-on component
tsx
"use client"
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)
const res = await fetch("/api/try-on", { method: "POST", body: form })
setBusy(false)
if (!res.ok) return setError((await res.json()).error)
setResult(URL.createObjectURL(await res.blob()))
}
return (
<div>
<input type="file" accept="image/*" onChange={(e) => e.target.files?.[0] && onFile(e.target.files[0])} />
{busy && <p>Creating your look, about 20 seconds...</p>}
{error && <p role="alert">{error}</p>}
{result && <img src={result} alt="You wearing this product" />}
</div>
)
}Tips
productImageUrlmust be a publichttpsURL (your CDN or Shopify CDN).- Show a progress message: a try-on takes about 20 seconds.
- Use
?mock=trueon the API URL while you build; it is free. - Plain React (Vite, CRA) works the same; the server route lives in your backend instead. See Node.js.