# Nuxt

> Embed the Muzekit editor in Nuxt 3: a Nitro server route opens the session and a .client.vue component 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 Nuxt app." It writes these same files.</Callout>

## How it works in Nuxt

`server/api/muzekit-session.post.js` answers POST only and runs on the server, so the key stays there. The example reads `process.env.MUZEKIT_SECRET_KEY`; to use `runtimeConfig` instead, declare `muzekitSecretKey` in `nuxt.config` and set `NUXT_MUZEKIT_SECRET_KEY`. `defineEventHandler` and `createError` are auto-imported in server routes.

## 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 for the signed-in user, in `server/api/muzekit-session.post.js`:

```js tab="server/api/muzekit-session.post.js"
export default defineEventHandler(async (event) => {
  const user = await getCurrentUser(event); // Your signed-in user: replace with your own auth
  if (!user) throw createError({ statusCode: 401, statusMessage: "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})`);
  return { client_secret: session.client_secret };
});
```

## 3. Mount the editor

The editor (.client: browser only), in `components/MuzekitEditor.client.vue`:

```vue tab="components/MuzekitEditor.client.vue"
<script setup>
import { onBeforeUnmount, onMounted, ref } from "vue";

const el = ref(null);
let editor;

function loadSdk() {
  if (window.Muzekit) return Promise.resolve();
  return new Promise((resolve, reject) => {
    const s = document.createElement("script");
    s.src = "https://muzekit.com/sdk/v1.js";
    s.onload = resolve;
    s.onerror = reject;
    document.head.appendChild(s);
  });
}

onMounted(async () => {
  await loadSdk();
  editor = window.Muzekit.mount(el.value, {
      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),
      },
    });
});
onBeforeUnmount(() => editor?.destroy());
</script>

<template>
  <div ref="el" style="height: 720px" />
</template>
```

## 4. Run it

```bash
npm run dev
```

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

### getCurrentUser is not defined

It stands for your auth module: `getUserSession(event)` from nuxt-auth-utils, or `getServerSession(event)` from sidebase's nuxt-auth.

### Nothing renders on the server

That's what `.client.vue` does. Wrap the component in `ClientOnly` with a fallback slot if you want a placeholder while it loads.

### 404 on GET

The `.post` suffix limits the route to POST, which is what the SDK sends.

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

Nitro builds the server route into your output for Node, Vercel or Netlify. Set the key in that platform's environment variables.

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 I fetch the secret with useFetch?

Let the SDK call the route through `fetchClientSecret` instead. Secrets work once and expire in 10 minutes, so a value fetched with the page can go stale.

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