# Ruby on Rails

> Embed the Muzekit editor in Ruby on Rails: a controller opens the session with Net::HTTP, and the view sends Rails' CSRF token.

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

## How it works in Ruby on Rails

The controller runs behind `before_action :authenticate_user!` from Devise, or your own login check, so `current_user` is set. Rails checks a forgery token on every non-GET request, so the page sends the one from `csrf_meta_tags` in the `X-CSRF-Token` header. `Net::HTTP` ships with Ruby, so there is no gem to add. You can also keep the key in encrypted credentials and read `Rails.application.credentials.muzekit_secret_key`.

## 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; route it with: post "/api/muzekit-session", to: "muzekit_sessions#create", in `app/controllers/muzekit_sessions_controller.rb`:

```ruby tab="app/controllers/muzekit_sessions_controller.rb"
require "net/http"

class MuzekitSessionsController < ApplicationController
  before_action :authenticate_user! # Your signed-in user: replace with your own auth

  def create
    uri = URI("https://api.muzekit.com/v1/sessions")
    request = Net::HTTP::Post.new(uri, "Authorization" => "Bearer #{ENV.fetch("MUZEKIT_SECRET_KEY")}", "Content-Type" => "application/json")
    request.body = { user: { id: current_user.id.to_s, name: current_user.name, email: current_user.email }, mode: "design" }.to_json
    response = Net::HTTP.start(uri.host, uri.port, use_ssl: true) { |http| http.request(request) }
    session = JSON.parse(response.body)
    return render json: session, status: response.code.to_i unless response.is_a?(Net::HTTPSuccess)
    render json: { client_secret: session["client_secret"] }
  end
end
```

## 3. Mount the editor

The editor (the layout must have `<%= csrf_meta_tags %>`), in `app/views/editor/show.html.erb`:

```erb tab="app/views/editor/show.html.erb"
<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", headers: { "X-CSRF-Token": document.querySelector('meta[name="csrf-token"]').content } })
        .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
bin/rails server
```

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

### ActionController::InvalidAuthenticityToken

The layout is missing `csrf_meta_tags`, or the fetch lacks the header. Both are in the example.

### Turbo leaves an old editor behind

With Turbo Drive, mount from a Stimulus controller instead of an inline script: `connect()` mounts, `disconnect()` calls `editor.destroy()`.

### ENV doesn't see the key

Rails doesn't read env files by itself: add the dotenv gem, or use `bin/rails credentials:edit`.

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

On Heroku, run `heroku config:set MUZEKIT_SECRET_KEY=...`. With Kamal, add the key to `.kamal/secrets` and list it under `env.secret` in `config/deploy.yml`.

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 Ruby gem?

Not needed: it's one HTTP request. Faraday or HTTParty work the same if your app already uses them.

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