# Node.js and Express

> Embed the Muzekit editor in a Node.js app with Express: one route behind your auth opens the session, and any template 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 Node.js and Express app." It writes these same files.</Callout>

## How it works in Node.js and Express

Put the route behind your existing auth middleware (Passport, express-session or a JWT check), so `req.user` is the signed-in user. Node 18 and later have `fetch` built in. The SDK's POST has no body, so this route doesn't need `express.json()`.

## 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.js (or your routes file)`:

```js tab="server.js (or your routes file)"
// 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 `your editor page or template`:

```html tab="your editor page or template"
<div id="muzekit-editor" style="height: 720px"></div>
<script src="https://muzekit.com/sdk/v1.js"></script>
<script>
  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
node --env-file=.env server.js
```

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

### req.user is undefined

Register the route after your session and auth middleware, like `app.use(session(...))` and `app.use(passport.session())`.

### CSRF middleware rejects the POST

With csrf-csrf or a similar package, send the token as a header from the fetch in `fetchClientSecret`.

### Fastify, Koa or Hono

Put the same body in their handler: read the user, call `/v1/sessions`, return the `client_secret`.

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

Set `MUZEKIT_SECRET_KEY` in your process manager or host: a PM2 ecosystem file, Docker environment, or Render and Railway variables. Locally, `node --env-file` (Node 20.6 and later) or dotenv loads it.

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 a Node SDK?

Not needed: the server side is one HTTP call, shown above. [Create a session](/docs/api-reference/sessions-create) lists every field.

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