Next.js (Pages Router)

Embed the Muzekit editor in a Next.js Pages Router app: an API Route opens the session and next/dynamic loads the editor in the browser only.

View as Markdown
Let your coding agent do it
Connect Claude Code, Cursor or Codex to the MCP server and ask: "Set up the Muzekit editor in this Next.js (Pages Router) app." It writes these same files.

How it works in Next.js (Pages Router)

API Routes never reach the client bundle, so process.env.MUZEKIT_SECRET_KEY stays on the server. Read the signed-in user from the request: getServerSession(req, res, authOptions) with NextAuth, getAuth(req) with Clerk, or your own session cookie. The handler answers POST only, which is what the SDK sends.

1. Add your secret key

Create an editor and copy its Test key (mk_test_…) from API keys in the dashboard. Put it in .env.local on your server:

.env.local
MUZEKIT_SECRET_KEY=mk_test_…

2. Open a session on your server

Opens a session for the signed-in user, in pages/api/muzekit-session.js:

pages/api/muzekit-session.js
export default async function handler(req, res) {
  if (req.method !== "POST") return res.status(405).end();
  const user = await getCurrentUser(req); // 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 components/muzekit-editor.jsx:

components/muzekit-editor.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. Show it on a page

The page, in pages/editor.jsx:

pages/editor.jsx
import dynamic from "next/dynamic";

const MuzekitEditor = dynamic(() => import("@/components/muzekit-editor"), { ssr: false });

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

5. Run it

Shell
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

405 when you open the route in a browser

Typing the URL sends a GET, and the handler answers only POST on purpose. The SDK's request goes through.

Hydration warnings

Rendering the editor on the server would differ from the browser. Keep the dynamic(..., { ssr: false }) import.

Moving to the App Router later

The session code stays the same; only the file moves to a Route Handler. See the Next.js (App Router) example.

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

Set MUZEKIT_SECRET_KEY wherever the app runs: Vercel or Netlify environment variables, or the process environment of next start on your own server. Restart after changing it.

Then make a Live key (mk_live_…), add your domain to Live under Allowed domains and use Copy to Live for your templates, look and features.

Questions

Can I open the session in getServerSideProps?

You can, but client secrets work once and last 10 minutes, so a page left open couldn't reopen the editor. Let the SDK call the API Route each time instead.