> ## Documentation Index
> Fetch the complete documentation index at: https://www.courier.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> Install the Courier skill before writing code: `npx skills add trycourier/courier-skills`. It carries the verified SDK shapes and the rules you cannot get wrong.
> Authenticate every request with `Authorization: Bearer <API_KEY>`. A workspace has several environments and each has its own keys, which are plain `pk_` strings with no environment prefix. Start with Test.
> Send with `client.send.message` from the Node SDK (`@trycourier/courier` v7 and later, where the client is the default import). Reference a template by its `nt_` id or its alias.
> A send accepts a bare Elemental element list, but storing content on a template requires the top-level elements wrapped in a channel element.
> To translate a template, write one locale at a time with `PUT /notifications/{id}/locales/{localeId}`, which merges into the existing translations. `PUT /notifications/{id}/content` and `PUT /notifications/{id}/elements/{elementId}` overwrite translations along with the content, so send each element's `id` and `locales` back, and first remove every `checksum` and any `locales` key that starts with an underscore.
> Templates and journeys can be built in the Courier app or created through the API. Either way they live in the workspace and are referenced by ID when you send.
> The hosted MCP server is https://mcp.courier.com. For a briefing on what Courier is and when to use it, read https://www.courier.com/llms.txt.
> Adding notifications to a framework app? Start from its quickstart, which has a runnable repo and complete files: Next.js email https://www.courier.com/docs/guides/add-transactional-email-to-nextjs.md, Django https://www.courier.com/docs/guides/add-notifications-to-django.md, Rails https://www.courier.com/docs/guides/add-notifications-to-rails.md, Node.js digest https://www.courier.com/docs/guides/batch-notifications-into-a-daily-digest-in-node.md, and the React, Next.js, and Astro inbox quickstarts under /guides/add-an-inbox-to-*.
> Prefer the Guides tab for how-do-I questions and the Docs tab for how-does-it-behave questions. The API reference lives under /api-reference.

# Add notifications with preferences to a Rails app

> Add email, SMS, and in-app notifications with per-user preferences to a Rails app. One Active Job calls Courier, and users opt out on a hosted page.

Add email, SMS, and in-app notifications with per-user preferences to a Rails app by sending from one Active Job through Courier. Courier delivers all three channels and skips any user who opted out on its hosted preference page.

```ruby theme={null}
require "courier"

client = Courier::Client.new(api_key: ENV.fetch("COURIER_API_KEY"))

response = client.send_.message(
  message: {
    to: { email: ENV.fetch("DEMO_EMAIL") },
    content: { title: "Hello from Rails", body: "Your first Courier notification." },
    routing: { method: "single", channels: ["email"] }
  }
)

puts "Sent. Request id: #{response.request_id}"
```

Save it as `first_send.rb`, then run it with your API key and email address:

```bash theme={null}
gem install trycourier && COURIER_API_KEY=YOUR_COURIER_API_KEY DEMO_EMAIL=YOUR_EMAIL ruby first_send.rb
```

It prints a request id that you'll find in [Courier Logs](https://app.courier.com/logs). On a Test key, use your Courier login address. [Test email](https://www.courier.com/docs/workspaces/environments.md#email-in-the-test-environment) reaches it with no provider connected.

> [card] [courier-rails-quickstart](https://github.com/trycourier/courier-rails-quickstart)
>
> The finished Rails app from this guide, ready to clone and run.

## Build this with a coding agent

To have a coding agent add Courier to your Rails app, paste this prompt into Claude Code, Cursor, or Codex from the project root:

```text theme={null}
Add email, SMS, and in-app notifications with per-user preferences to this Rails app with Courier.
Follow https://www.courier.com/docs/guides/add-notifications-to-rails.md and the reference app at https://github.com/trycourier/courier-rails-quickstart.
Use the trycourier gem (require "courier") and read COURIER_API_KEY and COURIER_TOPIC_ID from the environment.
Send from an Active Job enqueued in a model's after_commit callback, with one idempotency key per event.
Mint the inbox JWT for the user in the session, never a user id from params, and render <courier-inbox> in a view.
When done, add a rake task like the reference app's lib/tasks/courier.rake, run it, and show me the request id from the log.
```

Install the Courier skill with `npx skills add trycourier/courier-skills`, and connect the [Courier MCP server](https://www.courier.com/docs/resources/mcp.md) so the agent can check Courier Logs and templates itself.

### Rules for AI agents

* Use the `trycourier` gem (`require "courier"`). The send method is `send_`, because `send` is reserved in Ruby.
* Read `COURIER_API_KEY` and `COURIER_TOPIC_ID` from `ENV` on the server. The browser gets only a scoped JWT.
* Pass one `idempotency_key` per event, built from the order id and `updated_at`: `order-#{id}-shipped-#{updated_at.strftime("%s%6N")}`.
* Send from `NotifyJob`, enqueued in `after_update_commit`, and keep `preferences.subscription_topic_id` on the send.
* Mint the inbox token for the user in the session. Never take a user id from params.
* Never call Twilio or your email provider directly. Courier routes every channel.

## What you'll build

This Rails app notifies a user through Courier when their order ships:

* **An email, a text, and an in-app message** from one send, when an `Order` ships
* **A `<courier-inbox>`** on a Rails view
* **A hosted preference page link** in every message

## Prerequisites

### For the first send

* [A Courier API key](https://app.courier.com/settings/api-keys)
* Ruby 3.2 or newer

### For the full build

* A Rails 7.2 or newer app
* [A preference topic id](#create-a-preference-topic-for-rails-notifications)
* [A connected email provider](https://www.courier.com/docs/integrations/email/overview.md)
* [A connected SMS provider, such as Twilio](https://www.courier.com/docs/integrations/sms/twilio.md)

## Clone the finished Rails app

Clone the Courier Rails quickstart to run the finished app with your own key, after you create the [preference topic](#create-a-preference-topic-for-rails-notifications).

```bash theme={null}
git clone https://github.com/trycourier/courier-rails-quickstart.git
cd courier-rails-quickstart
bundle install
cp .env.example .env   # add your API key, topic id, and DEMO_EMAIL
bin/rails db:prepare
bin/rails server
```

The steps below add or change these files:

| File | What it does |
| - | - |
| `Gemfile` | Adds `trycourier` and `dotenv` |
| `app/jobs/notify_job.rb` | The Courier send |
| `app/models/order.rb` | Enqueues the job on ship |
| `app/models/user.rb` | Defines `courier_id` |
| `app/controllers/courier_tokens_controller.rb` | Mints the inbox JWT |
| `app/views/inbox/show.html.erb` | Renders `<courier-inbox>` |
| `lib/tasks/courier.rake` | Ships a demo order |

## Install the trycourier gem in your Rails app

The Courier Ruby SDK is the [`trycourier` gem](https://www.courier.com/docs/sdk-libraries/ruby). Add it to your [`Gemfile`](https://github.com/trycourier/courier-rails-quickstart/blob/main/Gemfile), run `bundle install`, and put your keys in `.env`. You get the topic id in the next step.

```ruby theme={null}
gem "trycourier", "~> 7.1", require: "courier"

group :development do
  gem "dotenv", "~> 3.1"
end
```

```bash theme={null}
COURIER_API_KEY=YOUR_COURIER_API_KEY
COURIER_TOPIC_ID=YOUR_TOPIC_ID
DEMO_EMAIL=YOUR_EMAIL
DEMO_PHONE=
```

## Create a preference topic for Rails notifications

A Courier subscription topic is the category a Rails user opts out of. In the [preferences editor](https://app.courier.com/~/test/platform/preferences), add an "Order updates" topic with the default **On**, click **Publish**, and copy its id into `COURIER_TOPIC_ID`. Courier hosts the preference page that `{{var "urls.preferences"}}` links to.

## Send email, SMS, and in-app notifications from an Active Job

The Rails `NotifyJob` makes one Courier call to [`POST /send`](https://www.courier.com/docs/api-reference/send/send-a-message).

```ruby app/jobs/notify_job.rb lines theme={null}
class NotifyJob < ApplicationJob
  queue_as :default

  # The idempotency key makes a retry safe: Courier returns the first result
  # instead of sending twice.
  retry_on Courier::Errors::APIConnectionError,
           Courier::Errors::RateLimitError,
           Courier::Errors::InternalServerError,
           wait: :polynomially_longer, attempts: 5

  def perform(user, title:, body:, idempotency_key:)
    client = Courier::Client.new(api_key: ENV.fetch("COURIER_API_KEY"))

    response = client.send_.message(
      message: {
        to: {
          user_id: user.courier_id,
          email: user.email,
          phone_number: user.phone_number
        }.compact,
        content: {
          title: title,
          # Courier fills in a link to this user's hosted preference page.
          body: "#{body}\n\nChoose what we send you: {{var \"urls.preferences\"}}"
        },
        # Every channel at once. Courier picks the provider inside each one.
        routing: { method: "all", channels: ["email", "sms", "inbox"] },
        # The user's choices for this topic decide whether, and where, it sends.
        preferences: { subscription_topic_id: ENV.fetch("COURIER_TOPIC_ID") }
      },
      idempotency_key: idempotency_key
    )

    Rails.logger.info("Courier accepted #{idempotency_key} as #{response.request_id}")
    response
  end
end
```

An opted-out user is skipped as [`UNSUBSCRIBED`](https://www.courier.com/docs/send/statuses#why-a-message-is-unroutable), and a repeated [idempotency key](https://www.courier.com/docs/reference/api-overview.md#idempotency) returns the first response.

## Enqueue the notification job from an after\_commit callback

The Rails `after_update_commit` callback enqueues the Courier job only after the transaction commits.

```ruby app/models/order.rb lines theme={null}
class Order < ApplicationRecord
  belongs_to :user

  # after_commit, not after_save: the job is enqueued only once the row is
  # really in the database, so a rolled-back transaction never notifies anyone.
  after_update_commit :notify_shipped, if: -> { saved_change_to_status?(to: "shipped") }

  private

  def notify_shipped
    NotifyJob.perform_later(
      user,
      title: "Order ##{id} has shipped",
      body: "Your order is on its way.",
      # One key per shipment: retries of this job reuse it, and shipping the
      # same order again later gets a new one.
      idempotency_key: "order-#{id}-shipped-#{updated_at.strftime("%s%6N")}"
    )
  end
end
```

`User#courier_id` in [`app/models/user.rb`](https://github.com/trycourier/courier-rails-quickstart/blob/main/app/models/user.rb) is the id Courier knows the user by, in the send and the inbox token:

```ruby theme={null}
def courier_id
  "user_#{id}"
end
```

If your app doesn't have these models yet, generate them as the quickstart's [migration](https://github.com/trycourier/courier-rails-quickstart/blob/main/db/migrate/20261120000000_create_users_and_orders.rb) does, then add `has_many :orders` to `User`:

```bash theme={null}
bin/rails g model User email:string phone_number:string
bin/rails g model Order user:references status:string
bin/rails db:migrate
```

## Mint an inbox token in a Rails controller

The Courier inbox in a Rails view signs in with a JWT from [`POST /auth/issue-token`](https://www.courier.com/docs/api-reference/authentication/create-a-jwt), scoped to one user.

```ruby app/controllers/courier_tokens_controller.rb lines theme={null}
class CourierTokensController < ApplicationController
  # GET /courier/token
  def show
    # Read the user from your session here. Never from params: a caller who
    # can name any user id can read that user's inbox.
    user_id = current_user.courier_id

    client = Courier::Client.new(api_key: ENV.fetch("COURIER_API_KEY"))
    response = client.auth.issue_token(
      scope: "user_id:#{user_id} inbox:read:messages inbox:write:events",
      expires_in: "1 day"
    )

    render json: { userId: user_id, token: response.token }
  end
end
```

**Take the user from your session, never from the request.** A route that accepts a user id lets any caller read any user's inbox. If your app has no `current_user` yet, the quickstart's [`ApplicationController`](https://github.com/trycourier/courier-rails-quickstart/blob/main/app/controllers/application_controller.rb) defines a demo one:

```ruby theme={null}
def current_user
  @current_user ||= User.find_or_create_by!(id: 123) do |user|
    user.email = ENV.fetch("DEMO_EMAIL", "sarah@acme-corp.com")
  end
end
```

Add the routes in [`config/routes.rb`](https://github.com/trycourier/courier-rails-quickstart/blob/main/config/routes.rb), with an empty `InboxController#show` for the page:

```ruby theme={null}
root "inbox#show"
get "courier/token" => "courier_tokens#show", as: :courier_token
```

## Show in-app notifications in a Rails view

Courier's inbox is the `<courier-inbox>` web component, so a plain ERB view in Rails renders it. Run `bin/importmap pin @trycourier/courier-ui-inbox` (with jsbundling, `npm install @trycourier/courier-ui-inbox`), then in [`app/views/inbox/show.html.erb`](https://github.com/trycourier/courier-rails-quickstart/blob/main/app/views/inbox/show.html.erb):

```erb theme={null}
<courier-inbox height="32rem"></courier-inbox>

<script type="module">
  import { Courier } from "@trycourier/courier-ui-inbox";
  const response = await fetch("<%= courier_token_path %>");
  const { userId, token } = await response.json();
  Courier.shared.signIn({ userId, jwt: token });
</script>
```

The layout needs `<%= javascript_importmap_tags %>` in its `<head>`, or the component never loads.

## Verify

Run the Rails app, ship a demo order, then find the message in Courier Logs:

1. Run `bin/rails server` and open `localhost:3000`.
2. In the cloned repo, run `bin/rails courier:send`. [`lib/tasks/courier.rake`](https://github.com/trycourier/courier-rails-quickstart/blob/main/lib/tasks/courier.rake) ships an order inline and logs the request id. In your own app, set an order's status to `shipped`, and the job logs it.
3. The message lands in the inbox and at `DEMO_EMAIL`. Without `DEMO_PHONE`, Courier skips SMS.
4. Turn "Order updates" off on the linked preference page and send again. [Logs](https://app.courier.com/logs) shows `UNSUBSCRIBED`.

| What you see | Fix |
| - | - |
| SMS is `UNROUTABLE` with `DEMO_PHONE` set | Connect an SMS provider and use E.164 |
| Empty inbox | Match the token's `user_id` to the send's |
| `KeyError` for `COURIER_API_KEY` | Create `.env` with the keys above |

## Go to production with Courier

Courier is notification infrastructure for humans and AI agents. In a Rails app it sends through Twilio and your email provider. [Go live](https://www.courier.com/docs/guides/go-live.md) covers moving from Test to Production:

* **Run a real queue backend**, such as Solid Queue, because the async adapter loses jobs on restart.
* **Use a Production key and topic.**
* **Match the token's `expires_in` to your session.**

| Task | Noticed and provider gems | With Courier |
| - | - | - |
| Add a channel | A delivery class per channel | Add it to `routing.channels` |
| Provider failover | Your own logic | [Failover](https://www.courier.com/docs/send/routing.md#failover) |
| User preferences | A table and settings screen | A [topic](https://www.courier.com/docs/recipients/preferences/overview.md) and hosted page |
| In-app feed | An endpoint and UI you build | `<courier-inbox>` |

## FAQ

> [accordion] Should I use the Noticed gem or Courier?
>
> The Noticed gem delivers notifications from your Rails app with a delivery method per channel. Courier sends through your providers and adds hosted preferences, failover, an inbox, and one log.

> [accordion] How do users change their notification preferences in Rails?
>
> Rails users change their Courier notification preferences on a hosted page that `{{var "urls.preferences"}}` links from every message. To embed it, see [Build a preference center](https://www.courier.com/docs/guides/build-a-preference-center.md).

> [accordion] Do I need Sidekiq to send notifications from Rails?
>
> Sidekiq is optional for Courier in Rails. The send is one HTTP call from an Active Job, so any Active Job backend works.

> [accordion] How do I show in-app notifications in a Rails view?
>
> Rails renders in-app notifications with Courier's `<courier-inbox>` web component. Pin `@trycourier/courier-ui-inbox`, add the tag to an ERB view, and sign in with a JWT. See [Add an inbox](https://www.courier.com/docs/in-app/add-an-inbox.md?lang=Web%20Components).
