Rack middleware for Server-Sent Events (HTML5 SSE)


Rack middleware for Server-Sent Events (HTML5 SSE).

Requires an EventMachine backed server, like Thin or Rainbows (with the EventMachine backend only).


Supported backends:


Put meerkat and pg or em-hiredis in your Gemfile, depending on which backend you plan to use. Gemfile:

gem 'meerkat'
gem 'amqp'
# or
gem 'pg'
# or
gem 'em-hiredis'

Require meerkat and the backend you would like to use.

require 'bundler/setup'
require 'meerkat' 
require 'meerkat/backend/amqp' 
#require 'meerkat/backend/pg' 
#require 'meerkat/backend/redis' 
#require 'meerkat/backend/inmemory' 
require './app'

#Meerkat.backend = 
Meerkat.backend = 'amqp://guest:guest@localhost'
#Meerkat.backend = 'redis://localhost/0'
#Meerkat.backend = :dbname => 'postgres'
map '/' do
  run App
map '/stream' do

On the client:

var source = new EventSource('/stream/foo');
var streamList = document.getElementById('stream');
// Use #onmessage if you only listen to one topic
source.onmessage = function(e) {
  var li = document.createElement('li');
  li.innerHTML = JSON.parse(;

var multiSource = new EventSource('/stream/foo.*');
// You have to add custom event listerns when you 
// listen on multiple topics
multiSource.addEventListener('', function(e) {
  // Do something
}, false);
multiSource.addEventListener('', function(e) {
  // Do something
}, false);

To push things from the server:

Meerkat.publish "", { :any => 'hash' } # the hash will automatically be json encoded
Meerkat.publish "", 'any string'
Meerkat.publish "", myobj.to_json, true # the third parameter indicates that the message already is json encoded

The published objects will be JSON serialized before sent to the backend. You'll have to deserialize it in the client.

From the client:

$.post('/stream', { topic: '', data: JSON.stringify(my_object) })
$.post('/stream/', { data: JSON.stringify(my_object) })

A simple POST request, with a parameter called 'data' (or 'json' or 'msg') containing a JSON string.

The topic can be specified other as a post parameter or in the path.

Read more about Server-Sent Events and the EventSource API on HTML5Rocks.


A simple demo can be seen here:

It's deployed on Heroku's Cedar stack. It's using the AMQP backend, provided by CloudAMQP and the free Lemur plan.