# Astro

> Embed the Muzekit editor in Astro: an on-demand endpoint opens the session, and an inline script on the page mounts the editor.

<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 Astro app." It writes these same files.</Callout>

## How it works in Astro

An endpoint in `src/pages` that exports `POST` runs on the server when it isn't prerendered. Variables without the `PUBLIC_` prefix never reach the browser, so `import.meta.env.MUZEKIT_SECRET_KEY` is safe in the endpoint. The page uses `is:inline` so Astro leaves the SDK script as written instead of bundling it. `locals.user` comes from your middleware.

## 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 (needs server output or an adapter), in `src/pages/api/muzekit-session.js`:

```js tab="src/pages/api/muzekit-session.js"
export async function POST({ locals }) {
  const user = locals.user; // Your signed-in user: replace with your own auth
  if (!user) return new Response("Sign in first", { status: 401 });
  const response = await fetch("https://api.muzekit.com/v1/sessions", {
    method: "POST",
    headers: {
      Authorization: `Bearer ${import.meta.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})`);
  return Response.json({ client_secret: session.client_secret });
}
```

## 3. Mount the editor

The page, in `src/pages/editor.astro`:

```astro tab="src/pages/editor.astro"
---
---
<div id="muzekit-editor" style="height: 720px"></div>
<script src="https://muzekit.com/sdk/v1.js"></script>
<script is:inline>
  const editor = Muzekit.mount("#muzekit-editor", {
    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),
    },
  });
</script>
```

## 4. Run it

```bash
npm run dev
```

Sign in, then open `http://localhost:4321/editor`. 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

### The endpoint 404s or returns HTML in production

With static output, add `export const prerender = false` to the endpoint and install an adapter, such as `npx astro add node`.

### The key changes but the app keeps the old one

Astro can fill `import.meta.env` at build time. To change the key without a rebuild, read `process.env` on Node or use `astro:env` with a secret server variable.

### Using a React or Vue island instead

Take the component from the React or Vue example and render it with `client:only`, so it never runs on the server.

## Notes

- 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

Pick the adapter for your host. On Vercel and Netlify, set the key in the project settings; with the Node adapter, set it in the process environment.

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

### Can the editor page stay static?

Yes. Only the endpoint needs the server; the page fetches the client secret from the browser, so it can be prerendered.

<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>
