# TryYourSize Web SDK SDK reference
---
# Web SDK reference (TryYourSize.js)
> TryYourSize.js for any storefront: the client, elements, events and web components.
Source: https://docs.tryyoursize.com/reference/web/
*SDK* · `@tryyoursize/sdk` · v0.2.0
TryYourSize.js puts the TryYourSize elements in your storefront: a **Size guide** link next to your size picker, a **Find my size** button, or the inline **fit** element. Shoppers measure once with a tape measure; your page receives their size in your own size labels, never their measurements. Same shape as Stripe.js: a client per publishable key, an elements group, elements you mount, events you listen to.
## Install
**Script tag**
```html
```
**npm**
```bash
npm install @tryyoursize/sdk
```
## Initialize
**JavaScript**
```js
const tys = TryYourSize("pk_test_…"); // publishable key only
const elements = tys.elements(); // inherits your page's font and colours
const guide = elements.create("sizeGuide", { product: "SKU-123" });
guide.mount("#size-guide");
guide.on("recommendation", (r) => {
if (r.status === "ready") preselect(r.size); // your size label, e.g. "M"
});
```
**React**
```tsx
return (
r.status === "ready" && preselect(r.size)} />
);
}
```
**HTML**
```html
```
Allow our origins in your Content Security Policy: `script-src https://js.tryyoursize.com` (CDN build) and `frame-src https://embed.tryyoursize.com`. Error codes are listed in [Web SDK errors](https://docs.tryyoursize.com/sdk/errors.md).
## Client
| | |
|---|---|
| [`TryYourSize()`](https://docs.tryyoursize.com/reference/web/tryyoursize.md) | Creates a client for your publishable key. |
| [`loadTryYourSize()`](https://docs.tryyoursize.com/reference/web/load-tryyoursize.md) | Loads TryYourSize.js from our CDN once (the latest compatible v1 build) and creates a client, like loadStripe(). |
| [`elements()`](https://docs.tryyoursize.com/reference/web/client-elements.md) | Creates an elements group: the appearance and language shared by the elements you create from it. |
| [`recommendation()`](https://docs.tryyoursize.com/reference/web/client-recommendation.md) | The shopper's recommended size for a product, in your size labels, without mounting anything (a hidden frame on our origin answers). |
| [`recommendationHandle()`](https://docs.tryyoursize.com/reference/web/client-recommendation-handle.md) | A sealed handle for your server's POST /v1/recommendations (headless or server-rendered pages). |
| [`experiment()`](https://docs.tryyoursize.com/reference/web/client-experiment.md) | The visitor's A/B holdout assignment when the store runs one (null otherwise). |
| [`version`](https://docs.tryyoursize.com/reference/web/client-version.md) | The SDK version (semver) of the loaded TryYourSize.js. |
## Elements group
| | |
|---|---|
| [`create()`](https://docs.tryyoursize.com/reference/web/elements-create.md) | Creates an element for one product. |
| [`getElement()`](https://docs.tryyoursize.com/reference/web/elements-get-element.md) | The most recently created element of a type that is still alive, or null. |
| [`update()`](https://docs.tryyoursize.com/reference/web/elements-update.md) | Live update, e.g. |
## Element
| | |
|---|---|
| [`mount()`](https://docs.tryyoursize.com/reference/web/element-mount.md) | Shows the element inside a container of your page. |
| [`unmount()`](https://docs.tryyoursize.com/reference/web/element-unmount.md) | Removes the element from the page and closes its window. |
| [`destroy()`](https://docs.tryyoursize.com/reference/web/element-destroy.md) | Unmounts the element and drops its handlers. |
| [`update()`](https://docs.tryyoursize.com/reference/web/element-update.md) | Changes the element's options in place. |
| [`open()`](https://docs.tryyoursize.com/reference/web/element-open.md) | Opens the TryYourSize window for this element's product, as the element itself does on click. |
| [`close()`](https://docs.tryyoursize.com/reference/web/element-close.md) | Closes the window if it is open. |
| [`getRecommendation()`](https://docs.tryyoursize.com/reference/web/element-get-recommendation.md) | The shopper's recommended size for this product once known (see the recommendation event). |
| [`on()`](https://docs.tryyoursize.com/reference/web/element-on.md) | Listens to an element event. |
| [`once()`](https://docs.tryyoursize.com/reference/web/element-once.md) | Like on(), for the next event only. |
| [`off()`](https://docs.tryyoursize.com/reference/web/element-off.md) | Removes a handler, or every handler of the event when you pass none. |
| [`elementType`](https://docs.tryyoursize.com/reference/web/element-element-type.md) | The element's type: "fit", "button" or "sizeGuide". |
## Events
Listen with `element.on(name, handler)`, with the React `on…` props, or as `tys:` DOM events on the web components.
| | |
|---|---|
| [`"ready"`](https://docs.tryyoursize.com/reference/web/event-ready.md) | The element is on the page (the size guide and button at once; the inline element once our window is connected). |
| [`"size"`](https://docs.tryyoursize.com/reference/web/event-size.md) | The shopper chose a size in our window ("Use this size"): preselect that variant. |
| [`"open"`](https://docs.tryyoursize.com/reference/web/event-open.md) | Our window opened. |
| [`"close"`](https://docs.tryyoursize.com/reference/web/event-close.md) | Our window closed. |
| [`"loaderror"`](https://docs.tryyoursize.com/reference/web/event-loaderror.md) | Our window could not be loaded or reached (network, Content Security Policy, an origin not registered for the key). |
| [`"recommendation"`](https://docs.tryyoursize.com/reference/web/event-recommendation.md) | The shopper's recommended size for this product, in your size labels: on mount when the shopper is already connected, and on every change. |
## Web components
For no-code platforms and CMS blocks: load `tys.js` (or import `@tryyoursize/sdk/elements`) and use the tags. Each forwards the element events as bubbling `tys:` DOM events with the payload in `event.detail`.
| | |
|---|---|
| [``](https://docs.tryyoursize.com/reference/web/tys-size-guide.md) | The size guide element as a tag: "Size guide" with the TryYourSize mark, then "Your size: M" once the shopper is connected. |
| [``](https://docs.tryyoursize.com/reference/web/tys-fit.md) | The inline element as a tag: sign-in and "your body is ready" in your page. |
| [``](https://docs.tryyoursize.com/reference/web/tys-fit-button.md) | The compact "Find my size" button as a tag. |
## Types and utilities
| | |
|---|---|
| [`Appearance`](https://docs.tryyoursize.com/reference/web/appearance.md) | Look and feel of the elements and our windows, modelled on Stripe's Appearance API: a theme, a few variables, and web fonts. |
| [`Recommendation`](https://docs.tryyoursize.com/reference/web/recommendation.md) | Recommendation |
| [`TryYourSizeError`](https://docs.tryyoursize.com/reference/web/tryyoursize-error.md) | Every error the SDK throws or emits: a stable type and code to branch on, a message, and a link to its explanation. |
| [`isPublishableKey()`](https://docs.tryyoursize.com/reference/web/is-publishable-key.md) | A publishable key is the only key allowed in a browser. |
| [`resolveAppearance()`](https://docs.tryyoursize.com/reference/web/resolve-appearance.md) | Resolves what the windows receive: for "inherit", the font, text colour and background where the element is mounted (buttons use the text colour, the way most stores style their primary button); expli |
| [`VERSION`](https://docs.tryyoursize.com/reference/web/version.md) | The SDK version (semver), also sent to our windows. |
---
# Appearance
> Look and feel of the elements and our windows, modelled on Stripe's Appearance API: a theme, a few variables, and web fonts.
Source: https://docs.tryyoursize.com/reference/web/appearance/
*Type* · `@tryyoursize/sdk`
Look and feel of the elements and our windows, modelled on Stripe's Appearance API: a theme, a few variables, and web fonts. The default theme, `inherit`, reads your page where the element is mounted, so it looks native to your store.
```ts
interface Appearance
```
## Properties
- **`theme`** (`Theme`, optional): `"inherit"` (default): your page's font, text colour and background. `"tryyoursize"`: our light beige brand.
- **`variables`** (`AppearanceVariables`, optional)
- **`colorPrimary`** (`string`, optional): Buttons and the tape line on the body.
- **`colorBackground`** (`string`, optional)
- **`colorText`** (`string`, optional)
- **`fontFamily`** (`string`, optional)
- **`borderRadius`** (`number`, optional): Corner radius in px for cards, inputs and buttons.
- **`fonts`** (`{ cssSrc: string }[]`, optional): Stylesheets with @font-face rules (Google Fonts only), like Stripe's cssSrc.
## Example
**JavaScript**
```js
tys.elements({
appearance: {
theme: "inherit",
variables: { colorPrimary: "#3b2f26", fontFamily: "Inter, sans-serif", borderRadius: 8 },
fonts: [{ cssSrc: "https://fonts.googleapis.com/css2?family=Inter:wght@400;600" }],
},
});
```
**Swift**
```swift
let config = TryYourSize.Configuration(appearance: Appearance(
colorPrimary: TYSColor(hex: "#3b2f26"), fontFamily: "Inter, -apple-system", borderRadius: 8))
```
**Kotlin**
```kotlin
val config = TryYourSize.Configuration(
appearance = Appearance(colorPrimary = 0xFF3B2F26.toInt(), borderRadius = 8f),
)
```
## See also
- [Appearance and theming](https://docs.tryyoursize.com/guides/appearance.md)
---
# tys.elements()
> Creates an elements group: the appearance and language shared by the elements you create from it.
Source: https://docs.tryyoursize.com/reference/web/client-elements/
*Method* · `@tryyoursize/sdk`
Creates an elements group: the appearance and language shared by the elements you create from it.
```ts
elements(options?: ElementsOptions): Elements;
```
## Parameters
- **`options`** (`ElementsOptions`, optional)
- **`appearance`** (`Appearance`, optional): Look and feel. By default (`theme: "inherit"`) elements take your page's font and colours. See `Appearance`(/reference/web/appearance/).
- **`locale`** (`Locale`, optional)
## Returns
`Elements`: An `Elements` group: `create()`, `getElement()`, `update()`.
## Example
**JavaScript**
```js
const elements = tys.elements({
appearance: { variables: { colorPrimary: "#3b2f26", borderRadius: 10 } },
locale: "auto",
});
```
**React**
```tsx
```
---
# tys.experiment()
> The visitor's A/B holdout assignment when the store runs one (null otherwise).
Source: https://docs.tryyoursize.com/reference/web/client-experiment/
*Method* · `@tryyoursize/sdk`
The visitor's A/B holdout assignment when the store runs one (null otherwise). Save `visitorId` with the order (POST /v1/orders `visitor_id`) so returns are attributed to the right arm.
```ts
experiment(): Promise;
```
## Returns
`Promise`: The assignment, or `null` when the store runs no A/B holdout (or the API cannot be reached: then everyone sees TryYourSize).
- **`experimentId`** (`string`, required)
- **`arm`** (`ExperimentArm`, required)
- **`visitorId`** (`string`, required): The anonymous visitor ID: save it with the order (`visitor_id` in POST /v1/orders).
## Example
**JavaScript**
```js
const a = await tys.experiment();
// Keep it with the cart; your server sends it with the order.
if (a) cart.attributes.tys_visitor_id = a.visitorId;
```
**Node.js**
```ts
await tys.orders.create({
id: "order_1042",
visitor_id: cart.attributes.tys_visitor_id, // from tys.experiment() in the browser
// …lines, currency
});
```
## See also
- [A/B holdout](https://docs.tryyoursize.com/guides/ab-holdout.md)
- [Orders and returns](https://docs.tryyoursize.com/guides/outcomes.md)
---
# tys.recommendationHandle()
> A sealed handle for your server's POST /v1/recommendations (headless or server-rendered pages).
Source: https://docs.tryyoursize.com/reference/web/client-recommendation-handle/
*Method* · `@tryyoursize/sdk`
A sealed handle for your server's POST /v1/recommendations (headless or server-rendered pages). Send `handle` to your server; it gets sizes only. Null when the shopper is not signed in to TryYourSize on your site, has no body yet, or is in the A/B holdout. Expires after an hour.
```ts
recommendationHandle(): Promise;
```
## Returns
`Promise`: `{ handle, expiresAt }`, or `null`.
- **`handle`** (`string`, required): Opaque, starts with `tys_rh_`; send it to your server as is.
- **`expiresAt`** (`string`, required): ISO date-time; ask for a new one after it (an hour).
## Examples
### Browser: get a handle, send it to your server
**JavaScript**
```js
const h = await tys.recommendationHandle();
const res = await fetch("/api/sizes", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ handle: h?.handle, products: ["SKU-123", "SKU-456"] }),
});
```
### Server: exchange it for sizes
**Node.js**
```ts
const { data } = await tys.recommendations.create({ handle, products: ["SKU-123", "SKU-456"] });
```
**Python**
```python
answer = tys.recommendations.create(handle=handle, products=["SKU-123", "SKU-456"])
```
## See also
- [Server-side recommendations](https://docs.tryyoursize.com/guides/server-side-recommendations.md)
- [recommendations.create() (Node.js)](https://docs.tryyoursize.com/reference/node/recommendations-create.md)
---
# tys.recommendation()
> The shopper's recommended size for a product, in your size labels, without mounting anything (a hidden frame on our origin answers).
Source: https://docs.tryyoursize.com/reference/web/client-recommendation/
*Method* · `@tryyoursize/sdk`
The shopper's recommended size for a product, in your size labels, without mounting anything (a hidden frame on our origin answers). Sizes only.
A visitor in the [A/B holdout](https://docs.tryyoursize.com/guides/ab-holdout.md) always gets `unavailable`, so you show them no size either. The call never starts a simulation.
```ts
recommendation(product: string): Promise;
```
## Parameters
- **`product`** (`string`, required): Your product ID or SKU, as synced to TryYourSize.
## Returns
`Promise`: The shopper's recommended size for the product.
- **`product`** (`string`, required)
- **`status`** (`RecommendationStatus`, required): `ready` (`size` is set), `computing` (a try-on the shopper started is still running), `none` (no size of this garment can be worn on this body), `signed_out` (no TryYourSize session on your site) or `unavailable` (no size for this product yet).
- **`size`** (`string | null`, required): The recommended size in the store's own label (its size map), or null.
- **`studioSize`** (`string | null`, required): The same size as entered in TryYourSize Studio, or null.
- **`wearableSizes`** (`string[]`, optional): Sizes that can be worn on this body, in the store's labels (when simulated).
## Example
**JavaScript**
```js
const rec = await tys.recommendation("SKU-123");
if (rec.status === "ready") {
sizePicker.value = rec.size; // "M", in your own labels
}
```
**React**
```tsx
function usePreselect(product: string, select: (size: string) => void) {
const tys = useTryYourSize();
useEffect(() => {
tys?.recommendation(product).then((r) => r.status === "ready" && r.size && select(r.size));
}, [tys, product]);
}
```
## See also
- [Preselect the recommended size](https://docs.tryyoursize.com/guides/recommendation-event.md)
- ["recommendation" event](https://docs.tryyoursize.com/reference/web/event-recommendation.md)
---
# tys.version
> The SDK version (semver) of the loaded TryYourSize.js.
Source: https://docs.tryyoursize.com/reference/web/client-version/
*Property* · `@tryyoursize/sdk`
The SDK version (semver) of the loaded TryYourSize.js. Include it in support requests.
```ts
readonly version: string;
```
## Example
**JavaScript**
```js
console.log(tys.version); // "0.2.0"
```
---
# element.close()
> Closes the window if it is open.
Source: https://docs.tryyoursize.com/reference/web/element-close/
*Method* · `@tryyoursize/sdk`
Closes the window if it is open.
```ts
close(): void;
```
## Example
**JavaScript**
```js
guide.close();
```
---
# element.destroy()
> Unmounts the element and drops its handlers.
Source: https://docs.tryyoursize.com/reference/web/element-destroy/
*Method* · `@tryyoursize/sdk`
Unmounts the element and drops its handlers. Create a new element to show it again.
```ts
destroy(): void;
```
## Example
**JavaScript**
```js
// Single-page apps: when the product view goes away
guide.destroy();
```
**React**
```tsx
// React components destroy their element on unmount.
```
---
# element.elementType
> The element's type: "fit", "button" or "sizeGuide".
Source: https://docs.tryyoursize.com/reference/web/element-element-type/
*Property* · `@tryyoursize/sdk`
The element's type: `"fit"`, `"button"` or `"sizeGuide"`.
```ts
readonly elementType: ElementType;
```
## Example
**JavaScript**
```js
if (el.elementType === "sizeGuide") el.update({ variant: "button" });
```
---
# element.getRecommendation()
> The shopper's recommended size for this product once known (see the recommendation event).
Source: https://docs.tryyoursize.com/reference/web/element-get-recommendation/
*Method* · `@tryyoursize/sdk`
The shopper's recommended size for this product once known (see the `recommendation` event).
```ts
getRecommendation(): Promise;
```
## Returns
`Promise`: Resolves with the first recommendation once known (see `tys.recommendation()` for the fields).
## Example
**JavaScript**
```js
const r = await guide.getRecommendation();
if (r.status === "ready") preselect(r.size);
```
**React**
```tsx
const ref = useRef(null);
const r = await ref.current?.getRecommendation();
```
---
# element.mount()
> Shows the element inside a container of your page.
Source: https://docs.tryyoursize.com/reference/web/element-mount/
*Method* · `@tryyoursize/sdk`
Shows the element inside a container of your page. A visitor in the A/B holdout gets nothing at all.
```ts
mount(target: HTMLElement | string): void;
```
## Parameters
- **`target`** (`HTMLElement | string`, required): A CSS selector or an element. Put it where the shopper chooses a size.
## Errors
`TryYourSizeError` with code `mount_not_found`, `already_mounted` or `element_destroyed`.
## Example
**JavaScript**
```js
const guide = elements.create("sizeGuide", { product: "SKU-123" });
guide.mount("#size-guide"); // or guide.mount(document.querySelector(".size-row"))
```
**React**
```tsx
// React components mount for you on commit:
```
---
# element.off()
> Removes a handler, or every handler of the event when you pass none.
Source: https://docs.tryyoursize.com/reference/web/element-off/
*Method* · `@tryyoursize/sdk`
Removes a handler, or every handler of the event when you pass none.
```ts
off(event: K, handler?: (e: ElementEvents[K]) => void): void;
```
## Parameters
- **`event`** (`keyof ElementEvents`, required): The event name.
- **`handler`** (`(e: ElementEvents[K]) => void`, optional): The handler passed to `on()`. Omit it to remove all.
## Example
**JavaScript**
```js
const onSize = ({ size }) => preselect(size);
guide.on("size", onSize);
// later
guide.off("size", onSize);
```
---
# element.on()
> Listens to an element event.
Source: https://docs.tryyoursize.com/reference/web/element-on/
*Method* · `@tryyoursize/sdk`
Listens to an element event. A handler that throws never breaks the SDK or the other handlers.
```ts
on(event: K, handler: (e: ElementEvents[K]) => void): void;
```
## Parameters
- **`event`** (`keyof ElementEvents`, required): `"ready"`, `"size"`, `"open"`, `"close"`, `"loaderror"` or `"recommendation"`. See the event pages.
- **`handler`** (`(e: ElementEvents[K]) => void`, required): Called with the event payload.
## Example
**JavaScript**
```js
guide.on("recommendation", (r) => r.status === "ready" && preselect(r.size));
guide.on("size", ({ size }) => preselect(size)); // "Use this size" in the window
guide.on("loaderror", ({ error }) => console.warn(error.code));
```
**React**
```tsx
r.status === "ready" && preselect(r.size)}
onSize={({ size }) => preselect(size)}
onLoadError={({ error }) => console.warn(error.code)}
/>
```
**HTML**
```html
const el = document.querySelector("tys-size-guide");
el.addEventListener("tys:recommendation", (e) => e.detail.status === "ready" && preselect(e.detail.size));
el.addEventListener("tys:size", (e) => preselect(e.detail.size));
```
---
# element.once()
> Like on(), for the next event only.
Source: https://docs.tryyoursize.com/reference/web/element-once/
*Method* · `@tryyoursize/sdk`
Like `on()`, for the next event only.
```ts
once(event: K, handler: (e: ElementEvents[K]) => void): void;
```
## Parameters
- **`event`** (`keyof ElementEvents`, required): The event name.
- **`handler`** (`(e: ElementEvents[K]) => void`, required): Called once with the event payload.
## Example
**JavaScript**
```js
guide.once("ready", () => performance.mark("tys-ready"));
```
---
# element.open()
> Opens the TryYourSize window for this element's product, as the element itself does on click.
Source: https://docs.tryyoursize.com/reference/web/element-open/
*Method* · `@tryyoursize/sdk`
Opens the TryYourSize window for this element's product, as the element itself does on click. Use it from your own button or link.
```ts
open(): void;
```
## Example
**JavaScript**
```js
document.querySelector("#my-size-link").addEventListener("click", (e) => {
e.preventDefault();
guide.open();
});
```
**React**
```tsx
const ref = useRef(null);
```
---
# element.unmount()
> Removes the element from the page and closes its window.
Source: https://docs.tryyoursize.com/reference/web/element-unmount/
*Method* · `@tryyoursize/sdk`
Removes the element from the page and closes its window. Handlers are kept: you can `mount()` it again.
```ts
unmount(): void;
```
## Example
**JavaScript**
```js
guide.unmount();
guide.mount("#another-place");
```
---
# element.update()
> Changes the element's options in place.
Source: https://docs.tryyoursize.com/reference/web/element-update/
*Method* · `@tryyoursize/sdk`
Changes the element's options in place. A new `product` (or demo body) reloads the element; `variant` and `label` restyle it.
```ts
update(options: Partial): void;
```
## Parameters
- **`options`** (`Partial`, required)
- **`product`** (`string`, required): Your product ID or SKU, as synced to TryYourSize.
- **`variant`** (`"link" | "button"`, optional): "sizeGuide" only: a text link (default, like most stores' "Size guide") or an outlined button.
- **`label`** (`string`, optional): "sizeGuide" only: your own words for "Size guide" (otherwise localized from `locale`).
- **`demo`** (`DemoOptions`, optional): `"fit"` only, test keys only: demo mode. The element shows the garment on a named sample body (synthetic size-chart tape values, never a real person's), with no sign-in: size chips, objective numbers in cm and kPa, a turning body and a sample-body picker. For landing pages and sales demos.
- **`body`** (`string`, required): A sample body id: `sample-female-158`, `sample-female-165`, `sample-female-172`, `sample-male-172`, `sample-male-178` or `sample-male-186`.
- **`height`** (`number`, optional): Height of the element in px (default 640).
## Examples
### A variant page that switches product
**JavaScript**
```js
colorSelect.addEventListener("change", () => guide.update({ product: colorSelect.value }));
```
**React**
```tsx
// Changing the prop calls update() for you:
```
---
# elements.create()
> Creates an element for one product.
Source: https://docs.tryyoursize.com/reference/web/elements-create/
*Method* · `@tryyoursize/sdk`
Creates an element for one product. Mount it with `mount()`.
```ts
create(type: ElementType, options: ElementOptions): TysElement;
```
## Parameters
- **`type`** (`"fit" | "button" | "sizeGuide"`, required): `"sizeGuide"`: a link-sized "Size guide" with the TryYourSize mark, for the spot next to your size picker. `"button"`: a compact "Find my size" button. `"fit"`: the inline element, with sign-in and "your body is ready" in your page.
- **`options`** (`ElementOptions`, required)
- **`product`** (`string`, required): Your product ID or SKU, as synced to TryYourSize.
- **`variant`** (`"link" | "button"`, optional): "sizeGuide" only: a text link (default, like most stores' "Size guide") or an outlined button.
- **`label`** (`string`, optional): "sizeGuide" only: your own words for "Size guide" (otherwise localized from `locale`).
- **`demo`** (`DemoOptions`, optional): `"fit"` only, test keys only: demo mode. The element shows the garment on a named sample body (synthetic size-chart tape values, never a real person's), with no sign-in: size chips, objective numbers in cm and kPa, a turning body and a sample-body picker. For landing pages and sales demos.
- **`body`** (`string`, required): A sample body id: `sample-female-158`, `sample-female-165`, `sample-female-172`, `sample-male-172`, `sample-male-178` or `sample-male-186`.
- **`height`** (`number`, optional): Height of the element in px (default 640).
## Returns
`TysElement`: The element. Several of the same type are allowed (for example a product grid).
## Errors
`TryYourSizeError` with code `invalid_option` (missing `product`, bad `variant`, `label` or `demo`) or `unknown_element_type`.
## Examples
### Size guide next to the size picker
**JavaScript**
```js
const guide = tys.elements().create("sizeGuide", {
product: "SKU-123",
variant: "link", // or "button"
label: "Find your size", // optional; otherwise localized
});
guide.mount("#size-guide");
```
**React**
```tsx
```
**HTML**
```html
```
### Demo mode (test keys only)
**JavaScript**
```js
const demo = tys.elements().create("fit", {
product: "CREW-TSHIRT",
demo: { body: "sample-female-165", height: 640 },
});
demo.mount("#demo");
```
**React**
```tsx
```
**HTML**
```html
```
## See also
- [Size guide quickstart](https://docs.tryyoursize.com/quickstarts/size-guide.md)
---
# elements.getElement()
> The most recently created element of a type that is still alive, or null.
Source: https://docs.tryyoursize.com/reference/web/elements-get-element/
*Method* · `@tryyoursize/sdk`
The most recently created element of a type that is still alive, or `null`.
```ts
getElement(type: ElementType): TysElement | null;
```
## Parameters
- **`type`** (`"fit" | "button" | "sizeGuide"`, required): The element type.
## Returns
`TysElement | null`: The element, or `null`.
## Example
**JavaScript**
```js
elements.getElement("sizeGuide")?.open();
```
---
# elements.update()
> Live update, e.g.
Source: https://docs.tryyoursize.com/reference/web/elements-update/
*Method* · `@tryyoursize/sdk`
Live update, e.g. when the shop switches to dark mode.
Mounted elements and an open window restyle at once; nothing reloads.
```ts
update(options: ElementsOptions): void;
```
## Parameters
- **`options`** (`ElementsOptions`, required)
- **`appearance`** (`Appearance`, optional): Look and feel; by default the elements inherit the page's font and colours.
- **`locale`** (`Locale`, optional)
## Examples
### Follow your dark mode
**JavaScript**
```js
const dark = matchMedia("(prefers-color-scheme: dark)");
dark.addEventListener("change", () =>
elements.update({ appearance: { theme: "inherit" } }), // re-reads your page's colours
);
```
**React**
```tsx
// The provider calls elements.update() when options.appearance changes.
```
## See also
- [Appearance and theming](https://docs.tryyoursize.com/guides/appearance.md)
---
# "close" event
> Our window closed.
Source: https://docs.tryyoursize.com/reference/web/event-close/
*Event* · `@tryyoursize/sdk`
Our window closed. With unsaved measurements, the window asks the shopper first.
```ts
close: { elementType: ElementType };
```
## Payload
- **`elementType`** (`"fit" | "button" | "sizeGuide"`, required): Which element.
## Example
**JavaScript**
```js
guide.on("close", () => sizePicker.focus());
```
**React**
```tsx
pickerRef.current?.focus()} />
```
---
# "loaderror" event
> Our window could not be loaded or reached (network, Content Security Policy, an origin not registered for the key).
Source: https://docs.tryyoursize.com/reference/web/event-loaderror/
*Event* · `@tryyoursize/sdk`
Our window could not be loaded or reached (network, Content Security Policy, an origin not registered for the key).
```ts
loaderror: { elementType: ElementType; error: TryYourSizeError };
```
## Payload
- **`elementType`** (`"fit" | "button" | "sizeGuide"`, required): Which element.
- **`error`** (`TryYourSizeError`, required): Code `window_unreachable`. See [Web SDK errors](https://docs.tryyoursize.com/sdk/errors.md#window_unreachable).
## Example
**JavaScript**
```js
guide.on("loaderror", ({ error }) => {
console.warn(error.code, error.docUrl);
guide.unmount(); // fall back to your own size chart
});
```
**React**
```tsx
report(error.code)} />
```
---
# "open" event
> Our window opened.
Source: https://docs.tryyoursize.com/reference/web/event-open/
*Event* · `@tryyoursize/sdk`
Our window opened.
```ts
open: { elementType: ElementType };
```
## Payload
- **`elementType`** (`"fit" | "button" | "sizeGuide"`, required): Which element opened it.
## Example
**JavaScript**
```js
guide.on("open", () => analytics.track("size_guide_open"));
```
**React**
```tsx
track("size_guide_open")} />
```
**HTML**
```html
el.addEventListener("tys:open", () => track("size_guide_open"));
```
---
# "ready" event
> The element is on the page (the size guide and button at once; the inline element once our window is connected).
Source: https://docs.tryyoursize.com/reference/web/event-ready/
*Event* · `@tryyoursize/sdk`
The element is on the page (the size guide and button at once; the inline element once our window is connected). Fires once per mount.
```ts
ready: { elementType: ElementType };
```
## Payload
- **`elementType`** (`"fit" | "button" | "sizeGuide"`, required): Which element.
## Example
**JavaScript**
```js
guide.on("ready", ({ elementType }) => console.log(elementType, "ready"));
```
**React**
```tsx
setReady(true)} />
```
**HTML**
```html
el.addEventListener("tys:ready", (e) => console.log(e.detail.elementType));
```
---
# "recommendation" event
> The shopper's recommended size for this product, in your size labels: on mount when the shopper is already connected, and on every change.
Source: https://docs.tryyoursize.com/reference/web/event-recommendation/
*Event* · `@tryyoursize/sdk`
The shopper's recommended size for this product, in your size labels: on mount when the shopper is already connected, and on every change. Sizes only, never measurements.
The size guide element always listens; for other elements, adding a handler starts it. Preselect your picker, but never override a size the shopper picked themselves.
```ts
recommendation: Recommendation;
```
## Payload
- **`product`** (`string`, required)
- **`status`** (`RecommendationStatus`, required): `ready`, `computing`, `none`, `signed_out` or `unavailable`. See [tys.recommendation()](https://docs.tryyoursize.com/reference/web/client-recommendation.md).
- **`size`** (`string | null`, required): The recommended size in the store's own label (its size map), or null.
- **`studioSize`** (`string | null`, required): The same size as entered in TryYourSize Studio, or null.
- **`wearableSizes`** (`string[]`, optional): Sizes that can be worn on this body, in the store's labels (when simulated).
## Example
**JavaScript**
```js
let touched = false;
sizePicker.addEventListener("change", () => (touched = true));
guide.on("recommendation", (r) => {
if (r.status === "ready" && !touched) sizePicker.value = r.size;
});
```
**React**
```tsx
{
if (r.status === "ready" && !touched) setSize(r.size);
}}
/>
```
**HTML**
```html
el.addEventListener("tys:recommendation", (e) => {
if (e.detail.status === "ready" && !touched) sizePicker.value = e.detail.size;
});
```
## See also
- [Preselect the recommended size](https://docs.tryyoursize.com/guides/recommendation-event.md)
---
# "size" event
> The shopper chose a size in our window ("Use this size"): preselect that variant.
Source: https://docs.tryyoursize.com/reference/web/event-size/
*Event* · `@tryyoursize/sdk`
The shopper chose a size in our window ("Use this size"): preselect that variant.
```ts
size: SizeEvent;
```
## Payload
- **`product`** (`string`, required)
- **`size`** (`string`, required)
- **`verified`** (`boolean`, required): True when the size comes from a completed try-on on the shopper's body.
## Example
**JavaScript**
```js
guide.on("size", ({ product, size }) => {
if (product === currentSku) sizePicker.value = size;
});
```
**React**
```tsx
setSize(size)} />
```
**HTML**
```html
el.addEventListener("tys:size", (e) => (sizePicker.value = e.detail.size));
```
---
# isPublishableKey()
> A publishable key is the only key allowed in a browser.
Source: https://docs.tryyoursize.com/reference/web/is-publishable-key/
*Function* · `@tryyoursize/sdk`
A publishable key is the only key allowed in a browser.
```ts
function isPublishableKey(key: string): boolean
```
## Parameters
- **`key`** (`string`, required): Any string.
## Returns
`boolean`: True for `pk_test_…` and `pk_live_…` keys.
## Example
**JavaScript**
```js
if (!isPublishableKey(settings.tysKey)) throw new Error("Use the publishable key");
```
---
# loadTryYourSize()
> Loads TryYourSize.js from our CDN once (the latest compatible v1 build) and creates a client, like loadStripe().
Source: https://docs.tryyoursize.com/reference/web/load-tryyoursize/
*Function* · `@tryyoursize/sdk/loader`
Loads TryYourSize.js from our CDN once (the latest compatible v1 build) and creates a client, like `loadStripe()`. Resolves to `null` during server-side rendering, so it is safe to call at module level in Next.js, Remix or Astro.
```ts
async function loadTryYourSize(
publishableKey: string,
options: TryYourSizeOptions & { scriptUrl?: string } = {},
): Promise
```
## Parameters
- **`publishableKey`** (`string`, required): Your publishable key (`pk_test_…` or `pk_live_…`).
- **`options`** (`TryYourSizeOptions & { scriptUrl?: string }`, optional, default `{}`): The options of `TryYourSize()`, plus `scriptUrl` to load the script from another URL (development only).
- **`embedOrigin`** (`string`, optional): Override for development (e.g. http://localhost:5173).
- **`apiOrigin`** (`string`, optional): Override of the API origin for development (e.g. http://localhost:8000): the A/B holdout config.
- **`locale`** (`Locale`, optional): Language of our windows; "auto" follows the browser.
## Returns
`Promise`: A promise of the client, or `null` on the server.
## Errors
Rejects with `TryYourSizeError` code `script_load_failed` when the script cannot load (network, CSP). Call it again to retry.
## Example
**JavaScript**
```js
const tys = await loadTryYourSize("pk_test_…");
if (tys) tys.elements().create("sizeGuide", { product: "SKU-123" }).mount("#size-guide");
```
**React**
```tsx
const tysPromise = loadTryYourSize("pk_test_…"); // module level, once
return ;
}
```
---
# Recommendation
> Recommendation
Source: https://docs.tryyoursize.com/reference/web/recommendation/
*Type* · `@tryyoursize/sdk`
```ts
interface Recommendation
```
## Properties
- **`product`** (`string`, required)
- **`status`** (`RecommendationStatus`, required)
- **`size`** (`string | null`, required): The recommended size in the store's own label (its size map), or null.
- **`studioSize`** (`string | null`, required): The same size as entered in TryYourSize Studio, or null.
- **`wearableSizes`** (`string[]`, optional): Sizes that can be worn on this body, in the store's labels (when simulated).
## Example
**JavaScript**
```js
{
"product": "SKU-123",
"status": "ready",
"size": "M",
"studioSize": "M",
"wearableSizes": ["M", "L"]
}
```
## Notes
`status` is one of:
- `ready`: `size` is the recommended size.
- `computing`: a try-on the shopper started is running; you get another recommendation when it finishes.
- `none`: no size of this garment can be worn on this body.
- `signed_out`: no TryYourSize session on your site.
- `unavailable`: signed in, but no size for this product yet (no garment data, no body yet, or not tried on). Page views never start a simulation; the shopper does, with "See it on you".
---
# resolveAppearance()
> Resolves what the windows receive: for "inherit", the font, text colour and background where the element is mounted (buttons use the text colour, the way most stores style their primary button); expli
Source: https://docs.tryyoursize.com/reference/web/resolve-appearance/
*Function* · `@tryyoursize/sdk`
Resolves what the windows receive: for "inherit", the font, text colour and background where the element is mounted (buttons use the text colour, the way most stores style their primary button); explicit variables always win.
```ts
function resolveAppearance(mount: Element, input: Appearance = {}): Appearance
```
## Parameters
- **`mount`** (`Element`, required): The element whose computed style is read.
- **`input`** (`Appearance`, optional, default `{}`): Your appearance; explicit variables win.
## Returns
`Appearance`: The appearance our windows receive.
## Example
**JavaScript**
```js
console.log(resolveAppearance(document.querySelector("#size-guide")));
```
---
# TryYourSizeError
> Every error the SDK throws or emits: a stable type and code to branch on, a message, and a link to its explanation.
Source: https://docs.tryyoursize.com/reference/web/tryyoursize-error/
*Class* · `@tryyoursize/sdk`
Every error the SDK throws or emits: a stable `type` and `code` to branch on, a message, and a link to its explanation.
```ts
class TryYourSizeError extends Error
```
## Properties
- **`type`** (`ErrorType`, required): `"integration_error"` (fix your code) or `"load_error"` (network, CSP).
- **`code`** (`ErrorCode`, required): A stable code. All codes: [Web SDK errors](https://docs.tryyoursize.com/sdk/errors.md).
- **`docUrl`** (`string`, required): Link to the code's explanation.
## Example
**JavaScript**
```js
try {
TryYourSize(key);
} catch (e) {
if (e instanceof TryYourSizeError && e.code === "invalid_key") showConfigError();
}
```
---
# TryYourSize()
> Creates a client for your publishable key.
Source: https://docs.tryyoursize.com/reference/web/tryyoursize/
*Function* · `@tryyoursize/sdk`
Creates a client for your publishable key. Every element and call goes through it.
```ts
function TryYourSize(publishableKey: string, options: TryYourSizeOptions = {}): TryYourSizeClient
```
## Parameters
- **`publishableKey`** (`string`, required): Your publishable key (`pk_test_…` or `pk_live_…`) from Studio → Developers → API keys. It works only on the origins registered for it. A secret key (`sk_…`) throws `secret_key_in_browser`.
- **`options`** (`TryYourSizeOptions`, optional, default `{}`)
- **`embedOrigin`** (`string`, optional): Override for development (e.g. http://localhost:5173).
- **`apiOrigin`** (`string`, optional): Override of the API origin for development (e.g. http://localhost:8000): the A/B holdout config.
- **`locale`** (`Locale`, optional): Language of our windows; "auto" follows the browser.
## Returns
`TryYourSizeClient`: The client: `elements()`, `recommendation()`, `recommendationHandle()`, `experiment()` and `version`.
## Errors
`TryYourSizeError` with code `secret_key_in_browser` or `invalid_key`. See [Web SDK errors](https://docs.tryyoursize.com/sdk/errors.md).
## Example
**JavaScript**
```js
const tys = TryYourSize("pk_test_…", { locale: "es" }); // windows in Spanish
```
**HTML**
```html
```
**React**
```tsx
// The provider calls TryYourSize() for you.
```
## See also
- [loadTryYourSize()](https://docs.tryyoursize.com/reference/web/load-tryyoursize.md)
- [Keys and modes](https://docs.tryyoursize.com/get-started/keys-and-modes.md)
---
#
> The compact "Find my size" button as a tag.
Source: https://docs.tryyoursize.com/reference/web/tys-fit-button/
*Web component* · `@tryyoursize/sdk/elements`
The compact "Find my size" button as a tag.
## Attributes
- **`publishable-key`** (`string`, required): Your publishable key.
- **`product`** (`string`, required): Your product ID or SKU.
- **`locale`** (`string`, optional): BCP 47 language.
## Example
**HTML**
```html
```
---
#
> The inline element as a tag: sign-in and "your body is ready" in your page.
Source: https://docs.tryyoursize.com/reference/web/tys-fit/
*Web component* · `@tryyoursize/sdk/elements`
The inline element as a tag: sign-in and "your body is ready" in your page.
## Attributes
- **`publishable-key`** (`string`, required): Your publishable key.
- **`product`** (`string`, required): Your product ID or SKU.
- **`locale`** (`string`, optional): BCP 47 language.
- **`demo-body`** (`string`, optional): Test keys only: demo mode on a sample body, e.g. `sample-female-165`.
## Example
**HTML**
```html
```
---
#
> The size guide element as a tag: "Size guide" with the TryYourSize mark, then "Your size: M" once the shopper is connected.
Source: https://docs.tryyoursize.com/reference/web/tys-size-guide/
*Web component* · `@tryyoursize/sdk/elements`
The size guide element as a tag: "Size guide" with the TryYourSize mark, then "Your size: M" once the shopper is connected.
## Attributes
- **`publishable-key`** (`string`, required): Your publishable key (`pk_test_…` / `pk_live_…`).
- **`product`** (`string`, required): Your product ID or SKU.
- **`variant`** (`"link" | "button"`, optional): A text link (default) or an outlined button.
- **`label`** (`string`, optional): Your own words for "Size guide" (otherwise localized).
- **`locale`** (`string`, optional): BCP 47 language; default: your page's ``, then the browser.
## Example
**HTML**
```html
```
## See also
- [Shopify (no code)](https://docs.tryyoursize.com/quickstarts/shopify.md)
- [Size guide quickstart](https://docs.tryyoursize.com/quickstarts/size-guide.md)
---
# VERSION
> The SDK version (semver), also sent to our windows.
Source: https://docs.tryyoursize.com/reference/web/version/
*Constant* · `@tryyoursize/sdk`
The SDK version (semver), also sent to our windows.
```ts
VERSION
```
## Example
**JavaScript**
```js
```