# Realtime events from Hanami

> Register the pusher gem as a Hanami 2 provider, publish Hibira events from actions and operations, and sign channel subscriptions in an action.

Source: https://hibira.io/guides/hanami

Register the pusher gem as a Hanami 2 provider, publish Hibira events from actions and operations, and sign channel subscriptions in an action.

Package: pusher

- A provider registers one client; actions and operations get it with Deps.
- An action signs private and presence channels for pusher-js and Laravel Echo.

## 1. Install

```shell
bundle add pusher
```

## 2. Set it up

```ruby
# config/providers/hibira.rb
Hanami.app.register_provider(:hibira) do
  prepare { require "pusher" }
  start do
    register "hibira", Pusher::Client.new(
      app_id: target["settings"].hibira_app_id, key: target["settings"].hibira_app_key,
      secret: target["settings"].hibira_app_secret, host: "ws.hibira.io", port: 443, use_tls: true
    )
  end
end

# config/settings.rb: setting :hibira_app_id, setting :hibira_app_key, setting :hibira_app_secret
```

## 3. Use it

```ruby
# app/actions/pusher/auth.rb (config/routes.rb: post "/pusher/auth", to: "pusher.auth")
module Bookshelf
  module Actions
    module Pusher
      class Auth < Bookshelf::Action
        include Deps["hibira"]

        def handle(request, response)
          # check the signed-in user may join request.params[:channel_name] first
          response.format = :json
          response.body = hibira.authenticate(request.params[:channel_name], request.params[:socket_id]).to_json
        end
      end
    end
  end
end

# anywhere: hibira.trigger("orders", "order.shipped", { id: 1042 })
```

## Before you start

- The app secret is shown only once, when you create the app or rotate its secret. Keep it on your server, never in a browser or game build.
- On the Free plan, list every origin your pages load from in the app’s allowed origins (http://localhost:3000 while developing, then your domain). "*" needs a paid plan.

- [RubyGems](https://rubygems.org/gems/pusher)
