# React

> Embed the Muzekit editor in a React app built with Vite: a component mounts the editor and your backend opens the session.

<Callout title="Let your coding agent do it">Connect Claude Code, Cursor or Codex to the [MCP server](/docs/mcp#set-up-the-editor-in-your-app) and ask: "Set up the Muzekit editor in this React app." It writes these same files.</Callout>

## How it works in React

The component loads the SDK script once, mounts the editor into a div it holds with `useRef`, and destroys it when it unmounts. Nothing secret is in the bundle: every `VITE_` variable is public, so the key must never be one. The backend route reads the signed-in user from your session or JWT before calling Muzekit.

## 1. Add your secret key

[Create an editor](/signup) and copy its Test key (`mk_test_…`) from **API keys** in the dashboard. Put it in `.env` on your server:

```bash tab=".env"
MUZEKIT_SECRET_KEY=mk_test_…
```

<Screenshot src="/docs/1-embed-code.webp" original="/docs/raw/1-embed-code.png" alt="The Embed code page in the Muzekit dashboard: the Test key for the server, then the session route and mount code" />

## 2. Open a session on your server

Opens a session at POST /api/muzekit-session, in `server: your backend`:

```js tab="server: your backend"
// Add to your Express app (Node 18+). Needs express.json() only if you send a body.
app.post("/api/muzekit-session", async (req, res) => {
  const user = req.user; // Your signed-in user: replace with your own auth
  if (!user) return res.status(401).json({ error: "Sign in first" });
  const response = await fetch("https://api.muzekit.com/v1/sessions", {
    method: "POST",
    headers: {
      Authorization: `Bearer ${process.env.MUZEKIT_SECRET_KEY}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({ user: { id: String(user.id), name: user.name, email: user.email }, mode: "design" }),
  });
  const session = await response.json();
  if (!response.ok) throw new Error(`Muzekit: ${session.error?.message} (${session.error?.code})`);
  res.json({ client_secret: session.client_secret });
});
```

## 3. Mount the editor

The editor, in `src/components/MuzekitEditor.jsx`:

```jsx tab="src/components/MuzekitEditor.jsx"
import { useEffect, useRef } from "react";

const SDK = "https://muzekit.com/sdk/v1.js";

function loadSdk() {
  if (window.Muzekit) return Promise.resolve();
  return new Promise((resolve, reject) => {
    const s = document.createElement("script");
    s.src = SDK;
    s.onload = resolve;
    s.onerror = reject;
    document.head.appendChild(s);
  });
}

export default function MuzekitEditor() {
  const ref = useRef(null);
  useEffect(() => {
    let editor;
    let gone = false;
    loadSdk().then(() => {
      if (gone) return;
      editor = window.Muzekit.mount(ref.current, {
      fetchClientSecret: () =>
        fetch("/api/muzekit-session", { method: "POST" })
          .then((r) => r.json())
          .then((s) => s.client_secret),
      on: {
        ready: () => console.log("Muzekit editor ready"),
        save: (e) => console.log("Saved", e.template, e.revision),
        error: (e) => console.error("Muzekit", e.code, e.message),
      },
    });
    });
    return () => {
      gone = true;
      editor?.destroy();
    };
  }, []);
  return <div ref={ref} style={{ height: 720 }} />;
}
```

## 4. Run it

```bash
npm run dev (front end and backend)
```

Sign in, then open `http://localhost:5173`. The editor loads in its container and the first session shows on your dashboard's Home. With a Test key, sessions on `localhost` and `127.0.0.1` are free.

## Common problems

### CORS errors on the session route

In development the Vite server and your backend run on different ports. Proxy `/api` in `vite.config.js` with `server.proxy`, so the browser calls one origin and your session cookie goes along.

### A blank editor in a hidden tab

The editor fills its container. A container with no height, like one inside a closed tab, shows nothing: give it a height when it is visible.

### TypeScript says Muzekit doesn't exist on Window

Add `declare global { interface Window { Muzekit: any } }` to the component, or a `.d.ts` file.

## Notes

- With Vite, proxy /api/muzekit-session to your backend in vite.config (server.proxy) during development.
- Secret key: MUZEKIT_SECRET_KEY goes in .env (or your secret store) on the server only. Never in browser code, never committed.
- Every user.id is your own id for that person: their designs and uploads follow it across sessions.
- mode: "design" opens the full editor; "fill" opens a form over a template (send template: "`<key or tpl_ id>`" too).
- Give the container a real height: the editor fills it.

## Deploy and go live

Ship the static build to any host (Netlify, Vercel, S3 and CloudFront) and keep `MUZEKIT_SECRET_KEY` in the backend's environment. When the front end and API are on different domains, send credentials with the fetch or serve the API under the same domain.

Then make a Live key (`mk_live_…`), add your domain to Live under [Allowed domains](/docs/allowed-domains) and use **Copy to Live** for your templates, look and features.

## Questions

### Is there an npm package for React?

The SDK is one script, served by Muzekit so it always matches the editor. The component loads it on demand, so it adds nothing to your bundle.

<Cards>
  <Card title="Editor modes" description="Design, fill-in and view, and what each shows." href="/docs/editor-modes" />
  <Card title="Browser SDK" description="Events, saving from your own button, and destroy." href="/docs/embed-sdk" />
</Cards>
