# Next.js

> Embed the Muzekit editor in a Next.js App Router app: a Route Handler opens the session and a Client 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 Next.js app." It writes these same files.</Callout>

## How it works in Next.js

Server Components can't touch `window`, which is why the editor lives in its own file that starts with `"use client"` and loads the SDK in `useEffect`. The Route Handler at `app/api/muzekit-session/route.js` runs only on the server. Get the signed-in user there from your auth library: `auth()` from Auth.js, `currentUser()` from Clerk, or `supabase.auth.getUser()`.

## 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.local` on your server:

```bash tab=".env.local"
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 `app/api/muzekit-session/route.js`:

```js tab="app/api/muzekit-session/route.js"
export async function POST() {
  const user = await getCurrentUser(); // Your signed-in user: replace with your own auth
  if (!user) return Response.json({ error: "Sign in first" }, { status: 401 });
  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 Response.json({ client_secret: session.client_secret });
}
```

## 3. Mount the editor

The editor (client component), in `components/muzekit-editor.jsx`:

```jsx tab="components/muzekit-editor.jsx"
"use client";

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. Show it on a page

The page that shows it, in `app/editor/page.jsx`:

```jsx tab="app/editor/page.jsx"
import MuzekitEditor from "@/components/muzekit-editor";

export default function Page() {
  return <MuzekitEditor />;
}
```

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

### window is not defined

The editor component was imported without `"use client"` as its first line. Keep the directive at the top of `components/muzekit-editor.jsx`.

### The key is undefined in the route

Next.js reads `.env.local` when `next dev` starts, so restart it after adding the key. Never prefix it with `NEXT_PUBLIC_`: that ships it to the browser.

### The editor mounts twice in development

React Strict Mode runs effects twice in dev. The cleanup calls `editor.destroy()`, so only one editor stays; production mounts once.

## Notes

- Secret key: MUZEKIT_SECRET_KEY goes in .env.local (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

On Vercel, add `MUZEKIT_SECRET_KEY` under Settings, Environment Variables: your Test key for Preview, your Live key for Production. Add your preview domain (like `your-app-git-main.vercel.app`) to Test's allowed domains and your production domain to Live's.

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 use a Server Action instead of a Route Handler?

Yes, an action that returns the client secret works with `fetchClientSecret`. A Route Handler is simpler, because the SDK calls it again whenever the editor reopens.

### Does it run on the Edge runtime?

Yes. The route only uses `fetch` and an environment variable, which the Edge and Node.js runtimes both have.

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