Is there a tutorial of Phoenix for Server sent event

I have a process that will run for a while (but not indefinitely). I want to keep my user informed on the progress. Using Liveview for that feels like overkill; SSE (Server sent events) should fill the bill. Can someone point me to a blog post that show me how to do it with Phoenix? Or show me some code? Much appreciated.

3 Likes

Woah, that is interesting I have never seen this before. I would be interested to see an implementation as well. I would have just made a channel.

1 Like

Dunno about a tutorial, but the Plug docs have the functions you need:

https://hexdocs.pm/plug/Plug.Conn.html#send_chunked/2

https://hexdocs.pm/plug/Plug.Conn.html#chunk/2

3 Likes

also take a look at sse | Hex

3 Likes

It just works. The only small gotcha is that I need to add a MIME type of

config :mime, :types, %{
  "text/event-stream" => ["sse"]
}

and add it to the plug accepts:

plug :accepts, ["html", "sse"]

Or the content negotiation would fail.

3 Likes

One more thing. For anyone using Nginx as a reverse proxy, please add the following header to disable buffering in the proxy:

conn
|> put_resp_header("x-accel-buffering", "no")

Or your user will see some lag.

6 Likes