sreyansjain

sreyansjain

Hello,

I am trying to get server sent events to work with Phoenix. And I can get it to work successfully over http.
Following are the steps i followed -
Add mime type to config.exs

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

In my controller I have

defmodule MyAppWeb.NotificationController do
  use MyAppWeb, :controller
  # alias Phoenix.PubSub

  def index(conn, _params) do
    conn =
      conn
      |> put_resp_header("Cache-Control", "no-cache")
      |> put_resp_header("connection", "keep-alive")
      |> put_resp_header("Content-Type", "text/event-stream; charset=utf-8")
      |> put_resp_header("Access-Control-Allow-Origin", "*")
      |> send_chunked(200)

    IO.puts("===============")

    PubSub.subscribe(
      self(),
      :notification
    )
    |> IO.inspect()

    IO.puts("===============")

    IO.inspect(self())
    sse_loop(conn, self())
  end

  defp sse_loop(conn, pid) do
    # receive is what stops the router from processing
    # and waits for an event to come in
    receive do
      # Send updates when :cagg is finished.
      {:notification, :done} ->
        # Fetch notification
        IO.inspect("*************************")
        # Send update.
        chunk(conn, "data: message\n\n")
        # Wait for next publish.
        sse_loop(conn, pid)

      # Stop SSE if this conn is actually down.
      # Ignore other processes finishing.
      # Notice the "^" in front of pid.
      {:DOWN, _reference, :process, ^pid, _type} ->
        nil

      # Don't stop SSE because of unrelated events.
      other -> 
        sse_loop(conn, pid)
    end
  end
end

In the router I have

get "/notification", NotificationController, :index

Also need to set idle_timeout for cowboy to infinity otherwise it times out after 60secs
So in the dev.exs file I have

http: [port: 8066, compress: true, protocol_options: [idle_timeout: :infinity]],
  https: [
    port: 8077,
    compress: true,
    cipher_suite: :strong,
    keyfile: "priv/keys/localhost.key",
    certfile: "priv/keys/localhost.cert",
    protocol_options: [idle_timeout: :infinity]
  ],

In the template I have simple javascript for SSE

<script>
    let eventSource = new EventSource("/notification");

    eventSource.onmessage = function(event) {
      console.log("New message", event.data);
    };
  </script>

I got great help from this blog - Server Sent Events with Elixir

Everything works over http. However for https it doesn’t work.
I get this error
GET https://localhost:8077/notification net::ERR_HTTP2_PROTOCOL_ERROR

Request your kind help.

First 10 of 13 Posts Switch mode

sreyansjain

sreyansjain OP

Whole thing works well over https when I use a real domain and a valid certificate. The issue seems to be there only with localhost.

I am still trying to figure out how to make it work over localhost using https.

vfsoraki

vfsoraki

For local certificates, I use makecert to generate valid certificates for local domains. I am on Linux, but this or similar tools should be available for other OSes.

I then add my local domains to /etc/hosts and I also have a local Nginx configured to serve my local projects using their respective local domains.

Should be easy to set up. If you’re having a problem, reply here.

sreyansjain

sreyansjain OP

Thanks. I will try it out.

hauleth

hauleth

If you are using systemd-resolved then you can use *.localhost without editing /etc/hosts (whole domain should resolve to loopback address).

vfsoraki

vfsoraki

Nice to know. I am indeed using it.

But I’m not using *.localhost.

Exadra37

Exadra37

Phoenix has a built-in tool for this:

mix phx.gen.cert

Check instructions at config/dev.exs:

# ## SSL Support
#
# In order to use HTTPS in development, a self-signed
# certificate can be generated by running the following
# Mix task:
#
#     mix phx.gen.cert
#
# Note that this task requires Erlang/OTP 20 or later.
# Run `mix help phx.gen.cert` for more information.
#
# The `http:` config above can be replaced with:
#
#     https: [
#       port: 4001,
#       cipher_suite: :strong,
#       keyfile: "priv/cert/selfsigned_key.pem",
#       certfile: "priv/cert/selfsigned.pem"
#     ],
#
# If desired, both `http:` and `https:` keys can be
# configured to run both http and https servers on
# different ports.

vfsoraki

vfsoraki

Is is locally trusted? I can’t find it if docs mention this anywhere.

Exadra37

Exadra37

No, you need to allow the certificate when the browser prompts you.

vfsoraki

vfsoraki

mkcerts makes them trusted locally, which is a nice thing.

Exadra37

Exadra37

But also creates certificates for example.com and I don’t like it overriding a website that exists:

I usually prefer Bash for this type of tasks, and I have wrote a script to do it. I use it in my docker builds or from my localhost host when needed.

Where Next? Top

Trending in Questions Top

stjefim
Hello! Suppose you are building workflow (order / task / payment) processing system with the following requirements: Each workflow con...
New
jonnycharles
I’m in search of an Elixir library that offers PDF generation capabilities similar to Ruby’s Prawn. While there have been discussions abo...
New
spammy
I’m looking to build a personal workflow to quickly deploy web applications written in elixir/phoenix, for local consumption (ie not on t...
New
dli
Before I dive in myself, did anyone successfully sprinkle Hologram into their existing LiveView app? Looking for hints regarding: Addi...
New
roeland
Kia ora, We have been using elixir-google-api to connect to Google Drive. However, with the updates to Tesla due to CVEs this is now bro...
New
bottlenecked
Hi all, I wanted to ask how the community is dealing with post-release steps. Today we have Ecto migrations, which make sure that the db...
New
rahultumpala
Hello, I have an Elixir backend that implements a custom protocol over TCP. I want to load test the backend and assess the performance o...
New

Other Trending Topics Top

JesseHerrick
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Damirados
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge &amp; Solve. They are GUI (Emerge) and State management (S...
New
netoum
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
New
ausimian
Emily is an Elixir library that runs Nx computations on Apple’s MLX. Install it as the default Nx backend and Nx, defn, Axon, Nx.Serving,...
New
wintermeyer
There are three potential reasons for members of this forum to have a look at https://vutuv.de You are tired or annoyed of LinkedIn. Yo...
New

We're in Beta

About us Mission Statement