# JSXImage docs

JSXImage is a REST API that renders images from JSX and Tailwind templates, so
you can ship dynamic images without building or hosting an image pipeline. Define
a template once, then `POST` its uid and your `props` from any backend and get a
PNG, JPEG or WebP back.

Prefer step by step? The [guides](https://jsximage.com/guides) walk through whole tasks, starting
with [Open Graph images for every page](https://jsximage.com/guides/open-graph-images).

Templates can also [load their own data](https://jsximage.com/docs#data-driven-templates) from an API
before they render.

Working with an AI assistant? Give it [jsximage.com/docs.md](https://jsximage.com/docs.md), these
docs as plain Markdown.

## Quick start

1. Open the [playground](https://jsximage.com/playground) and write a template. The preview updates
   as you work. Previews run in your browser, so they are unlimited.
2. Sign in, name the template, and click **Save**.
3. In the [dashboard](https://jsximage.com/dashboard/api-keys), create an API key. It is shown once,
   so copy it.
4. Click **API** in the playground to get the request for your template,
   with its [template uid](https://jsximage.com/docs#finding-your-template-uid) filled in.

```sh
curl -X POST https://jsximage.com/api/render \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"template":"<template-uid>","props":{"title":"Hello"}}' \
  --output image.png
```

## Using the playground

What you can do with a template in the playground, besides writing it.

### Trying other values: Params

The editor panel has two tabs, **Params** and **Code**, and opens on
**Params**: a form built from the template's `export const props`, a field for every prop, in a
fitting type. Long text gets a text area, a hex color like `"#7c5cff"` a color
picker, and props named like `logo`, `photo` or `imageUrl` an address field.
Numbers, true/false, lists and nested objects get their own fields.

- **The preview updates as you type,** with no Refresh needed.
- **Params are not written into the code.** The defaults stay in
  `export const props`; **Reset** brings the form back to them. A dot on the
  **Params** tab shows when the preview uses other values than the code.
- **They are used for the rest of the playground:** **Export image**, the
  examples in the **API** dialog, and **Create URL**. Try a value, then copy
  the request or create the URL with it.
- **The form follows the code.** Add or remove a prop in `export const props`
  and the form changes with it. Values you changed in the form are kept.
- **Opening another template** starts the form again from its defaults.

### Exporting an image

The arrow next to **Create URL** opens **Export image**. It saves the image to
your computer, rendered with the props in **Params** (the template's defaults
unless you changed them). It runs in your
browser, so it is unlimited on every plan and doesn't use your monthly renders.

### Restoring an earlier version

Every save keeps the version it replaced, and so does deleting a template. With a
saved template open, click the **history** button next to Save. The dialog lists
the earlier versions with when they were replaced and by whom. **View preview**
shows how a version looked, rendered live in the preview frame, and **View code**
shows its source. **Restore** puts a version in the editor as an unsaved change. Nothing is
overwritten until you press **Save**, and saving keeps the version you replaced in
the list too. The last 50 versions are kept.

### Deleting a template

The trash button next to Save asks you to confirm, and says what changes:

- **Live image URLs stop working.** Every URL made from the template returns `404`,
  wherever it is embedded.
- **API requests fail.** Calls to `/api/render` with its uid return `404`.
- **It disappears for your team.** It no longer shows in the templates list.
- **You can restore it for 30 days**, under **Recently deleted** (below).
- **After 30 days it is deleted for good**, with its version history.

Only an organization admin or the template's creator can delete or restore a
template.

### Recently deleted

A deleted template stays in **Recently deleted** for 30 days, with the days left.
Find it on the **Recently deleted** page in the dashboard sidebar, or in the
playground's **Templates** dialog.

- **Restore** brings it back with the same uid, so its
  [signed URLs](https://jsximage.com/docs#live-image-urls) and API calls work again.
- **Delete forever** removes it now, with its version history. It asks you to
  confirm, because it can't be undone: the uid never works again, and a new
  template gets a new uid.

### Sharing a template

The playground's address always says what is open, so you can copy it from the
address bar to share or bookmark it:

- `/playground?example=<name>`: an example. Opens for anyone.
- `/playground?temp=<id>`: a template an [AI assistant](https://jsximage.com/docs#use-with-an-ai-assistant)
  created. Opens for anyone with the link, for 7 days.
- `/playground?shared=<token>`: a template its owner shared publicly (below).
  Opens for anyone until the link expires.
- `/playground?template=<uid>`: a template saved in your organization. It opens
  for members of that organization, who need to be signed in. The link doesn't
  expire.

### Sharing a template publicly

With a saved template open, click **Share**, choose how long the link lasts (7,
30 or 90 days) and click **Create link**. Anyone with the link can open the
template in the playground, see its code and preview, and edit it in their own
browser. **Save** makes a copy in their own organization. Your template is never
changed by someone else.

- **It shows the template as last saved.** If you edit and save the template,
  people who open the link again see the new version.
- **It ends** when it expires, when you press **Stop sharing**, or when the
  template is deleted. A new link replaces the old one, which stops working at
  once.
- **Anyone with the link sees the code.** Don't share templates that contain
  secrets.
- **Only an organization admin or the template's creator** can create or remove
  the link.
- Opening the link doesn't use renders and doesn't affect image URLs or API
  requests.

Opening or saving a template, or starting a new one, updates the address. The
link opens the template as it is saved, not your unsaved edits.

## API or image URLs?

JSXImage returns an image in two ways. Pick by what the image is used for.

|                                      | Render API (`POST /api/render`)                                                  | Live image URL                                                                             |
| ------------------------------------ | -------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------ |
| **You get**                          | The image bytes in the response                                                  | A URL that serves the image                                                                |
| **Who stores it**                    | You do (S3, a database, an email attachment)                                     | JSXImage serves and caches it                                                              |
| **When the template changes**        | The file you stored stays as it was                                              | The URL shows the new design                                                               |
| **Needs a request from your server** | Yes, with an API key                                                             | No. You sign the URL in your own code                                                      |
| **Counts as a render**               | Every request                                                                    | The first time each URL is opened                                                          |
| **Use it for**                       | Files you keep: attachments, PDFs, certificates, receipts, uploads to other APIs | Images you embed: `og:image`, `<img>` tags, link previews, emails that should stay current |

If an image must never change after it is sent, such as a certificate or a
receipt, render it with the API and store the bytes. If it should follow your
design, use a live image URL.

## The render API

### `POST /api/render`

Renders a saved template to an image.

**Headers**

| Header          | Value                   |
| --------------- | ----------------------- |
| `Authorization` | `Bearer <your API key>` |
| `Content-Type`  | `application/json`      |

**Body**

| Field      | Type   | Description                                                     |
| ---------- | ------ | --------------------------------------------------------------- |
| `template` | string | The uid of a saved template in your organization. **Required.** |
| `props`    | object | Passed to your template component as props. Defaults to `{}`.   |
| `options`  | object | Overrides `width`, `height`, `format` or `quality` for this image. Optional. |

Everything else (fonts, CSS) lives in the template's [options](https://jsximage.com/docs#options).

**Overriding options per request.** One template can render several sizes and
formats. `options` takes `width` and `height` (1–4000 px), `format` (`"png"`,
`"jpeg"` or `"webp"`) and `quality` (1–100); anything you leave out comes from
the template. An unknown field returns `400`.

```json
{
  "template": "<template-uid>",
  "props": { "title": "Spring sale" },
  "options": { "width": 1080, "height": 1080, "format": "jpeg", "quality": 85 }
}
```

The template is laid out at the requested size, so build it to stretch: a root
element with `h-full w-full`, flexbox, and sizes that work in every shape you
render. A layout with fixed pixel positions for one size looks wrong in another;
give that size its own template.

**Response**

`200` with the image bytes. `Content-Type` is `image/png`, `image/jpeg` or
`image/webp`, matching the format: `options.format` from the request, or the
template's.

**Errors**

Errors are JSON: `{ "ok": false, "error": "message" }`.

| Status | Meaning                                                                                   |
| ------ | ----------------------------------------------------------------------------------------- |
| `400`  | The body is invalid: missing `template`, or `props` is not an object.                     |
| `401`  | The API key is missing, wrong or revoked.                                                 |
| `402`  | The free trial has ended, or its renders are used. Choose a plan. See [Monthly quota](https://jsximage.com/docs#monthly-quota). |
| `404`  | No template with that uid in the key's organization.                                      |
| `429`  | Your organization's monthly render quota is used up. See [Monthly quota](https://jsximage.com/docs#monthly-quota). |
| `500`  | The template failed to parse or render. `error` says why. Check it in the playground.     |

### Monthly quota

Each successful render uses one render from your plan's monthly quota, shown in
the [dashboard](https://jsximage.com/dashboard) and listed on the [pricing](https://jsximage.com/pricing) page. Requests
that fail (invalid body, unknown template, a template that errors) don't count.

Every successful response includes your quota:

| Header              | Meaning                                  |
| ------------------- | ---------------------------------------- |
| `X-Quota-Limit`     | Renders included in your plan per month. |
| `X-Quota-Remaining` | Renders left this month.                 |

When the quota is used up, `/api/render` returns `429` with a `Retry-After`
header (seconds until the quota resets) and a JSON body that includes `quota`,
`used` and `resets_at`. The quota resets on your subscription's billing date
each month. To render more, upgrade your plan.

**The free trial.** A new organization gets a 30-day trial with 250 renders and
3 templates, and no credit card. The 250 renders are for the whole trial; they
don't reset. When the trial ends or its renders are used, `/api/render` returns
`402` with `trial_ends_at` in the body, and new image URLs return `402` too.
Your templates and API keys stay. Choose a plan on the
[Plans page](https://jsximage.com/dashboard/plans) to keep rendering.

### Finding your template uid

Every saved template has a uid, a long random id. It is the `template` value in
the request. You can find it in three places:

- **Dashboard.** Open [Templates](https://jsximage.com/dashboard). Each of your saved templates
  shows its uid under the card, with a **Copy** button.
- **Playground, API.** Open a saved template and click **API**.
  The uid is shown at the top, and the request below already has it filled in.
- **Playground, Templates.** The Templates dialog shows the same cards with
  their uids.

A template needs to be saved first. A draft in the editor has no uid, and the
examples get one when you save them as your own. The uid doesn't change when
you rename or edit the template.

### Examples

**JavaScript**

```js
const res = await fetch("https://jsximage.com/api/render", {
  method: "POST",
  headers: {
    Authorization: "Bearer YOUR_API_KEY",
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    template: "<template-uid>",
    props: { title: "Hello" },
  }),
});

if (!res.ok) throw new Error((await res.json()).error);
const image = Buffer.from(await res.arrayBuffer());
```

**Python**

```python
import requests

res = requests.post(
    "https://jsximage.com/api/render",
    headers={"Authorization": "Bearer YOUR_API_KEY"},
    json={"template": "<template-uid>", "props": {"title": "Hello"}},
)
res.raise_for_status()
open("image.png", "wb").write(res.content)
```

### API keys

- Keys look like `jsx_live_…` and belong to an organization. A key can only
  render that organization's templates.
- Organization admins create and revoke keys in the
  [dashboard](https://jsximage.com/dashboard/api-keys). Every member can see them listed.
- A key is shown in full **once**, when it is created. We only store a hash, so
  a lost key can't be recovered. Revoke it and create a new one.
- Keep keys on your server. Don't put them in browser code or a public repo.

## Live image URLs

A live image URL is a signed link that renders a saved template with fixed props,
and shows the template as it is saved now. Use it where you can't make an
authenticated request: an `<img>` tag, an
`og:image` meta tag, an email, a README.

```html
<meta
  property="og:image"
  content="https://jsximg.com/i/<template-uid>.png?title=Hello&s=<signature>"
/>
```

> **A live image URL follows your template. It is not a snapshot.** It always
> renders the template as it is saved _now_. If you edit and save the template
> later, every URL created from it shows the new design, including URLs you have
> already published or embedded. Deleting the template makes its URLs return
> `404` until you restore it (within 30 days). The URL itself never changes. To keep an image as it is, use
> [`POST /api/render`](https://jsximage.com/docs#the-render-api) and store the result, or save a copy of
> the template under a new name and create URLs from the copy.

There are two ways to get a URL: create it in the playground or with the API, or
sign it yourself in your own code.

### Creating a URL

In the playground, save the template, click **Create URL** and copy it. It
puts the current props in the URL: the values in **Params**, or the defaults in
`export const props` if you haven't changed them. They are part of the URL: if you later edit the template, every URL shows
the new design, but keeps the values it was made with. To create URLs with
other props, call the API with an API key:

```sh
curl -X POST https://jsximage.com/api/image-urls \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"template":"<template-uid>","props":{"title":"Hello"},"format":"webp","quality":80}'
```

`format` (`png`, `jpeg` or `webp`) and `quality` (1-100, JPEG and WebP only) are
optional. Without `format`, the URL uses the template's format at the time you
create it. Without `quality`, it uses the template's quality, which can change
later. The response is `{ "ok": true, "url": "…" }`.

### Signing URLs yourself

Each organization has a **signing key**. Admins can see it on the
[API keys page](https://jsximage.com/dashboard/api-keys). With it you can sign URLs in your own code,
in any language, with no API call per URL. That suits thousands of pages, each
with its own Open Graph image.

A URL looks like this:

```
https://jsximg.com/i/<template-uid>.<ext>?<props>&q=<quality>&s=<signature>
```

- `<ext>` is the format: `png`, `jpg` or `webp`.
- `<props>` is either one query parameter per prop (`title=Hello&price=12`),
  where every value is text, or all props as JSON in one `p` parameter
  (`p=eyJ0aXRsZSI6IkhlbGxvIn0`), where they keep their types. See
  [Props as JSON](https://jsximage.com/docs#props-as-json).
- `q` (1-100) is optional and only applies to `jpg` and `webp`.
- `s` is the signature and must be the last parameter.

The signature is the lowercase hex HMAC-SHA256, using your signing key, of this
text: the file name, a `?`, and the query string without `&s=…`.

```
<template-uid>.<ext>?<query string>
```

Sign exactly the query string you send: the same encoding, the same order.

```js
import { createHmac } from "node:crypto";

const file = `${templateUid}.png`;
const query = new URLSearchParams({ title: "Hello", price: "12" }).toString();
const s = createHmac("sha256", process.env.JSX_SIGNING_KEY)
  .update(`${file}?${query}`)
  .digest("hex");
const url = `https://jsximg.com/i/${file}?${query}&s=${s}`;
```

```python
import hmac, hashlib, os
from urllib.parse import urlencode

file = f"{template_uid}.png"
query = urlencode({"title": "Hello", "price": "12"})
s = hmac.new(os.environ["JSX_SIGNING_KEY"].encode(), f"{file}?{query}".encode(), hashlib.sha256).hexdigest()
url = f"https://jsximg.com/i/{file}?{query}&s={s}"
```

### Props as JSON

Instead of one parameter per prop, you can send all props in one `p` parameter:
the props object as JSON, base64url-encoded (`-` and `_`, no `=` padding). It
works for any props, text included, so you can use it for every URL if you prefer
one format. Props in `p` keep their types: numbers, lists and objects arrive as
they are, while query parameters are always text.

```js
const json = JSON.stringify({ title: "Hello", price: 12 });
const p = Buffer.from(json).toString("base64url");
const query = `p=${p}`; // sign `${file}?${query}` as above
```

- `p` must decode to a JSON object. Anything else returns `404`.
- You can combine `p` with ordinary parameters. A prop in both takes the
  ordinary parameter's value.
- `q` and `s` always stay separate parameters, outside `p`.
- A prop named `p`, `q` or `s` has to go in `p`.

- **Keep the key on your server.** Anyone with it can sign URLs. Don't put it in
  browser code. If it leaks, rotate it on the API keys page.
- **Rotating breaks existing URLs.** Every URL signed with the old key returns
  `404`, wherever it is embedded.
- **Signed.** Changing the template uid, the extension or any parameter
  invalidates the URL and returns `404`. A missing or wrong signature also
  returns `404`.
- **What is fixed and what follows the template.** Fixed in the URL: the
  template, the props, the format and a quality you set. Everything else follows
  the template as last saved: layout, text, colors, fonts, images, size, and a
  quality you left out. When you create a URL without a format, the format is
  fixed at that moment.
- **Public.** Anyone with the URL can fetch the image. Don't put secrets in
  props.
- **Changes show after you save.** Edits in the playground don't affect any URL
  until you click **Save**. After saving, the new image is served right away.
  Browsers and CDNs that already hold the old image can keep showing it for up
  to an hour. Saving does not use quota.
- **Quota.** Creating or signing a URL is free. A URL uses one render from your
  monthly quota the first time it is opened, and nothing after that: the same
  URL, with the same props, format and quality, is counted once. When the quota
  is used up, a URL that has never been opened returns `429` (`402` in the free
  trial); URLs that have already been opened keep working. A render that fails
  isn't counted.
- **Cached.** Responses are cached per template version.
- **Size.** The query string can be up to about 3 KB.

## Bulk export

Bulk export turns a spreadsheet into a zip of images: one image per row. Use it
for badges, certificates, product cards or social posts for a whole list at once.

Bulk export needs an account (the free trial works). In the playground, sign in
and click **Bulk**:

1. Choose a `.csv` or `.xlsx` file. The first row is the header. (Old `.xls`
   files aren't supported; save them as `.xlsx` or CSV.)
2. **Map columns to props.** Each column becomes a prop with the text of its
   cell, named after the header in camelCase (`First name` becomes `firstName`).
   Rename a prop, or clear its name to skip the column. A preview shows the
   props of the first row.
3. Choose what the files are called (the row number, or the values of a column),
   the format (`png`, `jpeg` or `webp`) and, optionally, the quality.
4. Click **Render**. A progress bar shows the run, and you can cancel it. The zip
   downloads when it's done.

```csv
name,role,company
Ada Chen,Staff Engineer,Northwind
Sam Okafor,Designer,Acme
```

With a template whose `export const props` has `name`, `role` and `company`,
this gives `001.png` and `002.png`, or `Ada-Chen.png` and `Sam-Okafor.png` if the
file names come from the `name` column.

- **It uses the template in the editor.** Saved or not, with its current code and
  options. Props are always text, so a template that needs a number should
  convert it (`Number(price)`).
- **It runs in your browser.** The images are rendered in the preview and zipped
  on your computer. Nothing is uploaded, and bulk export doesn't use your
  monthly render quota.
- **Limit per run.** The number of rows one run may have depends on your plan:
  trial 5, Starter 250, Team 1,000, Business 2,000. Split larger files into
  several runs. The [pricing](https://jsximage.com/pricing) page lists the limits.
- **Failed rows.** A row whose template throws an error is skipped and listed
  with its error in `errors.csv` inside the zip. The other rows still render.
- **File names.** Unsafe characters are removed, and repeated names get `-2`,
  `-3` and so on.
- **Memory.** The zip is built in memory, so very large runs with large images
  need a computer with enough free memory.

## Use with an AI assistant

JSXImage has a public [MCP](https://modelcontextprotocol.io) server, so an AI
assistant can write a template for you. In the playground, the **MCP** button
shows the same instructions with your server's address filled in.

### How it works

1. **You ask for an image.** Describe it to your assistant: what it says, the
   size, the style. For example: "an Open Graph image for my blog posts, dark,
   with the title and author".
2. **The assistant writes the template.** The server's instructions teach it the
   template format: JSX with Tailwind classes, props with defaults, `options` for
   size and format, fonts and images, and common sizes. It needs nothing else.
3. **`create_template` checks and stores it.** The tool takes a `name` and the
   template's `code`. The code is parsed before it is stored. A template that
   doesn't run, or that would render unstyled (for example with `className`
   instead of `class`), is refused with an error the assistant can fix and retry.
4. **You open the link.** It opens the template in the playground with a live
   preview. It works for 7 days. Sign in and press **Save** to keep it in your
   organization, then render it with the [API](https://jsximage.com/docs#the-render-api).

### Changing a shared template

Paste a link from the playground's **Share** dialog (or a link an assistant gave
you) into the chat and describe the change: "make the background dark blue and
the title larger". The assistant calls `modify_template` in two steps:

1. With only the link, it gets the template's current source.
2. With the link and the complete modified source, it gets a link to the
   modified copy. The code is checked the same way as in `create_template`.

The original is never changed. Shared links are read-only, and the result is a
new temporary link (7 days) that you can open, edit and **Save**. A link that
has expired, been turned off or been deleted is refused, and the assistant tells
you.

### Install

Add the server to a client that supports remote (HTTP) MCP servers.

**Claude Code:**

```sh
claude mcp add --transport http jsximage https://jsximage.com/mcp
```

Start a new `claude` session afterwards and run `/mcp`: `jsximage` should be
connected.

**Clients with a JSON configuration:**

```json
{ "mcpServers": { "jsximage": { "url": "https://jsximage.com/mcp" } } }
```

**Clients with a form for remote servers or custom connectors:** enter
`https://jsximage.com/mcp` as the server URL (Streamable HTTP, no authentication).

### Good to know

- **No account.** Creating and opening a template needs no sign-in.
- **Temporary.** The link works for 7 days, then the template is deleted.
- **Anyone with the link can open it.** Don't put secrets in a template.
- **Limits.** The code can be up to 40,000 characters, and one client can create
  20 templates an hour.

## Writing a template

A template is a JSX file with three exports, all required:

- `export const props`: the inputs the template takes, with their default values.
- `export default`: a function component that returns your layout.
- `export const options`: how to render it (size, format, and so on).

```tsx
export const props = { title: "Hello" };

type Props = typeof props;

export default function Card(props: Props) {
  return (
    <div class="bg-ink flex h-full w-full flex-col justify-end p-20">
      <h1 class="text-paper m-0 text-8xl font-bold">{props.title}</h1>
    </div>
  );
}

export const options = {
  width: 1200,
  height: 630,
  format: "png",
  css: {
    selector: ":root",
    style: { "--color-ink": "#16130f", "--color-paper": "#fdfaf4" },
  },
};
```

- **Props** from the request are laid over the defaults in `export const props`
  and arrive as the component's one argument. See [Props](https://jsximage.com/docs#props) below.
- **TypeScript** is supported. The playground's editor knows about React types.
- **It renders once**, to a still image, as a plain function of its props. Hooks
  (`useState`, `useEffect` and so on), effects, event handlers and anything that
  changes over time are not available. Helper components are fine.
- **`React` is available** without importing it.
- **No `import` statements.** Templates are self-contained, and an import fails
  with `require is not defined`. Put helpers and data in the same file.

### Props

`export const props` is required. It lists every input the template takes, with
its default value. A template with no inputs exports an empty object:
`export const props = {}`. Without it the template fails with "The template must
export props".

```tsx
export const props = {
  title: "Weekly report",
  visits: 1280,
  weekly: [12, 18, 9, 22, 15],
  author: { name: "Ada Chen", role: "Engineer" },
};

type Props = typeof props;

export default function Report(props: Props) {
  return (
    <div class="flex h-full w-full p-16">
      {props.title}: {props.visits} visits by {props.author.name}
    </div>
  );
}
```

- **Write the names once.** `type Props = typeof props` takes the type from the
  object, and the component takes one `props: Props` parameter. Read values as
  `props.title`, so the names aren't repeated in the function's signature. The
  editor completes `props.` from the object.
- **What a request sends is laid over the defaults.** The component receives
  `{ ...defaults, ...sent }`, so it never needs defaults of its own, and a request
  can send only what changes. The merge is shallow: a prop that is sent replaces
  the default whole, so a sent `weekly` list replaces the default list.
- **The defaults are what you see first.** The preview, **Params**, **Export
  image** and a template that is opened for the first time all start from them,
  so make them realistic.
  A prop sent as `null` stays `null`: the default applies only to a missing prop.
- **Put `export const props` above the component,** after any constants it uses.
  It has to be plain data: text, numbers, booleans, lists and objects.
- **Types depend on how the props arrive.** In an `/api/render` request, in a
  signed URL's `p` parameter, props are JSON,
  so numbers, booleans, lists and objects keep their types. Signed URL query
  parameters (`?title=Hi`) and spreadsheet columns in bulk export are always
  text, so convert them in the template: `Number(props.visits)`.
- **Extra props are ignored.** Sending a prop that isn't in `export const props`
  isn't an error, and has no effect.
- **Keep data small.** A template runs in a sandbox with limited memory and time,
  so very long lists slow it down. See [Limits and gotchas](https://jsximage.com/docs#limits-and-gotchas).

To try other values while you write, open the **Params** tab next to **Code**:
a form built from `export const props` that updates the preview as you type,
without changing the code. See [Trying other values: Params](https://jsximage.com/docs#trying-other-values-params).

## Data-driven templates

A template can load its own data before it renders. Export an async function
named `data`: it gets the props, and what it returns is laid over them. Your
app sends an id, and the template fetches the rest, so the image always shows
the current numbers without your code building the props.

- **Live cards from an API:** a repository's stars, a release's version.
- **Images that stay current:** a [live image URL](https://jsximage.com/docs#live-image-urls) is cached
  for 6 hours instead of 30 days, so the same URL follows the data.
- **Smaller requests:** send `{"repo": "react/react"}`, not every field the
  image shows.

```tsx
export const props = { repo: "facebook/react" };

export async function data(props) {
  const res = await fetch(`https://api.github.com/repos/${props.repo}`);
  if (!res.ok) throw new Error(`GitHub answered ${res.status}`);
  const repo = await res.json();
  return { stars: repo.stargazers_count, description: repo.description };
}

type Props = typeof props & Awaited<ReturnType<typeof data>>;

export default function Repo(props: Props) {
  return (
    <div class="flex h-full w-full flex-col p-16">
      {props.repo}: {props.stars} stars
    </div>
  );
}
```

The request sends only `repo`, and the image shows the live numbers. The free
[GitHub README card](https://jsximage.com/tools/github-readme-card),
[npm package card](https://jsximage.com/tools/npm-package-card) and
[Shopify product image](https://jsximage.com/tools/shopify-product-image) are templates like this:
open one in the playground to see its `data` function. For a walkthrough, see the guide
[Build a data-driven template](https://jsximage.com/guides/data-driven-templates).

- **Where it can fetch.** Public APIs that need no key (`https` only):

  | Host                         | What                                                    |
  | ---------------------------- | ------------------------------------------------------- |
  | `api.github.com`             | GitHub repositories, releases and users                 |
  | `raw.githubusercontent.com`  | Files in a public repository, such as your own JSON     |
  | `<shop>.myshopify.com`       | Shopify products: `/products/<handle>.json`             |
  | `registry.npmjs.org`         | npm package versions and metadata                       |
  | `api.npmjs.org`              | npm download counts                                     |
  | `pypi.org`                   | Python packages: `/pypi/<name>/json`                    |
  | `hacker-news.firebaseio.com` | Hacker News items and users                             |
  | `api.open-meteo.com`         | Weather forecasts                                       |
  | `geocoding-api.open-meteo.com` | A city name to coordinates, for the weather           |
  | `<lang>.wikipedia.org`       | Wikipedia page summaries                                |

  For Shopify, use the shop's `.myshopify.com` address, not its own domain.
  Need another API? [Tell us](mailto:info@jsximage.com).
- **GET only.** `fetch(url)` returns `ok`, `status`, `json()` and `text()`.
  The template can't set headers or send a body.
- **Limits.** Up to 3 requests per render, 256 KB per response and 5 seconds
  per request. Waiting for a response doesn't count toward the template's time
  limit.
- **Freshness.** A [live image URL](https://jsximage.com/docs#live-image-urls) whose template loads data
  is cached for 6 hours instead of 30 days, so it follows the data. It still
  uses one render, the first time it is opened. Responses from GitHub are also
  cached for up to an hour.
- **Errors.** Throw from `data` to fail the render with your message, as in the
  example above.
- **In the playground** the preview runs `data` in your browser, with the same
  rules.

## Options

`options` is the second export. All fields except `format` are optional.

| Option    | Default     | Description                                                                                                |
| --------- | ----------- | ---------------------------------------------------------------------------------------------------------- |
| `format`  | none        | **Required.** `"png"`, `"jpeg"` or `"webp"`.                                                               |
| `width`   | auto        | Image width in pixels, 1–4000. Without it, the width follows the content.                                  |
| `height`  | auto        | Image height in pixels, 1–4000.                                                                            |
| `quality` | `100`       | 1–100, for lossy output such as JPEG. WebP output is always lossless.                                      |
| `fonts`   | none        | Extra fonts: Google Fonts by name, or a file URL. See [Fonts and images](https://jsximage.com/docs#fonts-and-images).               |
| `css`     | none        | A style rule (or stylesheet) applied to the template. Used for theme colors.                               |
| `emoji`   | `"twemoji"` | The emoji set, or `false` to leave emoji as text. See [Emoji and other scripts](https://jsximage.com/docs#emoji-and-other-scripts). |
| `version` | `2`         | Renderer version. Leave it at the default unless you need `1`.                                             |

Set `width` and `height`, and use `h-full w-full` on your root element so the
layout fills the image.

`options` can also be a function of the props, for options that change per
image, such as a font chosen by a prop. The examples and free tools all do
this with a `googleFont` prop: Geist by default, which is built in, or any
Google Font by name:

```jsx
export const props = { title: "Hello", googleFont: "Geist" };

export function options(props: Props) {
  const font = props.googleFont;
  return {
    width: 1200,
    height: 630,
    format: "png",
    fonts:
      font && font !== "Geist"
        ? [{ googleFont: font, weight: 400 }, { googleFont: font, weight: 700 }]
        : [],
  };
}

// on the root element
<div style={{ fontFamily: props.googleFont || "Geist" }}>…</div>
```

It gets the same props as the component (with anything `data()` returned).
Load the regular and bold weights only: almost every Google Font has them, and
other weights (such as `font-semibold`) use the nearest one.

## Styling with Tailwind

Style elements with Tailwind classes in the **`class`** attribute, not
`className`. Rendering uses
[Takumi](https://takumi.kane.tw), which has its own Tailwind parser, so it
supports a practical subset of Tailwind, not all of it.

```jsx
<div class="flex items-center gap-4 rounded-2xl bg-white p-8 shadow-lg">
  <h1 class="text-4xl font-bold text-slate-900">Hello</h1>
</div>
```

Classes can be built at runtime, so ``class={`w-${size}`}`` works.

### What works

- **Layout:** flexbox and grid, absolute positioning, sizing, spacing, borders,
  rounded corners, overflow and opacity.
- **Typography:** size, weight, color, tracking, leading and alignment.
- **Color and effects:** backgrounds, gradients, shadows.
- **Arbitrary values**, such as `bg-[#16130f]` or `w-[420px]`.
- **Breakpoints and structural variants**, such as `md:`, `first:`, `last:`,
  `odd:` and `even:`.
- **Inline `style` objects**, such as `style={{ letterSpacing: "-0.02em" }}`.
- **A `<style>` tag** inside the JSX, for plain CSS.

### Custom colors and design tokens

Define theme colors in `options.css` as variables on `:root`. Classes then
resolve against them:

```jsx
export const options = {
  format: "png",
  width: 1200,
  height: 630,
  css: {
    selector: ":root",
    style: {
      "--color-brand": "#ff4d4d",
      "--color-ink": "#16130f",
    },
  },
};

// bg-brand, text-ink, border-brand ... now work in `class`
```

### What doesn't work

- **`hover:`, `focus:` and other interactive variants.** The output is a still
  image, so they never apply.
- **`dark:`.** There is no dark mode in a rendered image. Set colors directly.
- **Some Tailwind at-rules**, such as `@utility`, `@plugin` and `@config`.
- **Parts of Tailwind's feature set.** The parser is not a full Tailwind build.
  If a class does nothing, try an arbitrary value or an inline `style`.

### Things to know

- **Gradients need a direction class.** `from-*` and `to-*` color stops alone
  paint nothing. Add `bg-linear-to-r` (or `bg-radial`, `bg-conic`).
- **There is no CSS reset.** A bare `<h1>` keeps a default top margin, so add
  `m-0` or `mt-0`. A border utility such as `border-l-2` draws on every side
  unless you also set the other sides to `border-0`.
- **A bare `<div>` is a block**, as in a browser. Add `flex` when you want
  flexbox.
- **Conflicting utilities** are resolved by Tailwind's order, not by their
  order in `class`.

## Fonts and images

### Fonts

**Geist** is built in, with weights 300–800 and Latin characters. System fonts
are not available. For anything else, name a Google Font in `options.fonts` and
use it by name:

```jsx
export const props = {};

export default function Card() {
  return <h1 style={{ fontFamily: "Playfair Display" }}>Hello</h1>;
}

export const options = {
  format: "png",
  width: 1200,
  height: 630,
  fonts: [
    { googleFont: "Playfair Display", weight: 700 },
    { googleFont: "Inter", weight: 400, style: "italic" },
  ],
};
```

A Google Font entry takes these fields:

| Field        | Default    | Description                                                                        |
| ------------ | ---------- | ---------------------------------------------------------------------------------- |
| `googleFont` | none       | **Required.** The family name as on fonts.google.com: `"Inter"`, `"Open Sans"`.    |
| `weight`     | `400`      | A weight the font has, 100–900. `700` is bold.                                     |
| `style`      | `"normal"` | `"normal"` or `"italic"`.                                                          |
| `subset`     | `"latin"`  | The character set: `"latin-ext"`, `"cyrillic"`, `"greek"`, `"japanese"` and so on. |
| `name`       | the family | What `fontFamily` uses. Only needed if you want a different name.                  |

List a font once per weight and style you use. Fonts come from
[Fontsource](https://fontsource.org), a mirror of Google Fonts, and are fetched
when the image renders. If the family, weight or subset doesn't exist, the render
fails with `Could not load … (HTTP 404)` and the font's URL.

For a font that isn't on Google Fonts, give a direct URL to a `.ttf`, `.otf`,
`.woff` or `.woff2` file instead:

```jsx
fonts: [{ name: "Playfair", url: "https://example.com/fonts/PlayfairDisplay.ttf" }],
```

A URL font is fetched when the image renders, so use a URL that is reliably
reachable. In the playground it is fetched by your browser, so the host must
allow cross-origin requests (CORS). The API has no such restriction.

### Emoji and other scripts

- **Emoji work automatically.** They are drawn as images (Twemoji), so `🎉 🚀 ❤️
👍🏽 🇸🇪` are fine in text. The images are fetched when the image renders. Set
  `emoji: false` in `options` to leave them as plain text, or choose another set
  with `emoji: "noto"`, `"openmoji"`, `"fluent"` and so on.
- **Other scripts need a font.** The built-in font has no Japanese, Chinese,
  Korean, Arabic and so on. List a font that has them in `options.fonts`. It is
  then used for any glyph the default font lacks, so you don't need to name it in
  `fontFamily`. Arabic is shaped right to left.
- **A listed font is used for every glyph it contains,** including Latin letters,
  so other text can change typeface. Preview the result.
- **Fonts are large.** A CJK font is about 1 MB. Only list one when the text
  needs it.
- **Symbols.** `✓ ✔ ★ ♥` work with a symbols font. Arrows and math such as
  `→ ≠ ≈` are missing from the default font: draw them with an inline `<svg>`.

```jsx
export const options = {
  format: "png",
  width: 1200,
  height: 630,
  fonts: [{ googleFont: "Noto Sans JP", weight: 500, subset: "japanese" }],
};

// <h1>Order #4821 受注確認 🎉</h1>
```

### Images

Use `<img>` with an absolute URL, such as
`<img src="https://example.com/logo.png" />`. Remote images are fetched when
the image renders. Keep them small, make sure they are publicly reachable, and
give them a size, for example `class="h-16 w-16"`. As with fonts, the
playground fetches images from your browser, so the host needs CORS headers
there. The API doesn't.

## Limits and gotchas

- **Parse time.** A template has about 200 ms to parse. Very heavy templates are
  rejected with a `500`.
- **Template size.** Template source is capped at 200,000 characters.
- **Image size.** `width` and `height` are capped at 4000 px each.
- **What uses your monthly renders.** Each successful call to `/api/render`, and
  the first time each [signed URL](https://jsximage.com/docs#live-image-urls) is opened. A different
  prop, format or quality is a different URL. Failed renders aren't counted.
  Playground previews, [bulk export](https://jsximage.com/docs#bulk-export), creating or signing a URL,
  and opening a URL again are free.
- **`class`, not `className`.** Using the wrong attribute is the most common
  reason a style doesn't appear.
- **No imports, no browser or Node APIs.** The template runs once, in an
  isolated sandbox with 8 MB of memory and a short time limit. `process` and
  `require` don't exist there, and `fetch` only works in
  [`data`](https://jsximage.com/docs#data-driven-templates), for the hosts listed there.
- **Debug in the playground.** Anything that fails over the API fails there
  too, with the error shown under the preview.

## Built on Takumi

Every JSXImage image is drawn by [Takumi](https://takumi.kane.tw), an open-source
renderer that turns JSX into images. It is written in Rust and runs
as WebAssembly, the same engine in the playground preview and on the server. Its
Tailwind support, layout engine and font handling are what make JSXImage
templates work. Thank you to Takumi and its contributors.

Step-by-step walkthroughs are in the [guides](https://jsximage.com/guides). Quick answers are in
the [FAQ](https://jsximage.com/faq). Questions or something missing? Email [info@jsximage.com](mailto:info@jsximage.com).
