# Angular

> Embed the Muzekit editor in Angular: a standalone component mounts it after the view renders, and your backend opens the session.

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

## How it works in Angular

The component waits for the view so the host div exists, mounts the editor into it with `@ViewChild`, and destroys it in `ngOnDestroy`. `HttpClient` isn't needed: the SDK calls your route itself. With Angular SSR, `ngAfterViewInit` also runs on the server, so mount from `afterNextRender` or check `isPlatformBrowser` first.

## 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: your backend`:

```js tab="server: your backend"
// 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 (standalone component), in `src/app/muzekit-editor.component.ts`:

```ts tab="src/app/muzekit-editor.component.ts"
import { AfterViewInit, Component, ElementRef, OnDestroy, ViewChild } from "@angular/core";

declare global { interface Window { Muzekit: any } }

@Component({ selector: "app-muzekit-editor", standalone: true, template: '<div #host style="height: 720px"></div>' })
export class MuzekitEditorComponent implements AfterViewInit, OnDestroy {
  @ViewChild("host") host!: ElementRef<HTMLDivElement>;
  private editor: any;

  async ngAfterViewInit() {
    if (!window.Muzekit) {
      await 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);
      });
    }
    this.editor = window.Muzekit.mount(this.host.nativeElement, {
      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),
      },
    });
  }

  ngOnDestroy() {
    this.editor?.destroy();
  }
}
```

## 4. Run it

```bash
ng serve --proxy-config proxy.conf.json
```

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

### Calls to /api fail under ng serve

Map `/api` to your backend in `proxy.conf.json` and start with `--proxy-config`, so the browser calls one origin.

### Muzekit is not on Window in TypeScript

The `declare global` block in the component adds it; keep it there or move it to `src/typings.d.ts`.

### An NgModule app

Add the component to the `imports` of the module that uses it; it works the same as standalone.

## Notes

- Proxy /api/muzekit-session to your backend in proxy.conf.json during ng serve.
- 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

Build with `ng build` and serve the output from any host. The backend keeps `MUZEKIT_SECRET_KEY` in its own 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 backend be .NET, Java or something else?

Yes. The backend makes one `POST /v1/sessions` call with the secret key; the [quick start](/docs/quick-start) shows the request, and the Go, Python and PHP examples show other languages.

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