Search code examples
elixirphoenix-framework

Not able to get the accept-language header on a Phoenix LiveView


I have a liveview route where I need to get the accept-language header.

I've tried to call connect_info/2 on mount/3 but it looks like not all headers are available there.

I've also tried to create a Plug and add the language to the session. However, I only need it for one specific route. So, I'd rather do it on mount/3 instead. Is there a way to get the accept-language header there?


Solution

  • With connect_info you can get just a subset of information passed as request headers (:peer_data, :trace_context_headers, :x_headers, :uri) assuming you have modified your web socket in endpoint.ex like so:

    socket "/live", Phoenix.LiveView.Socket, websocket: [connect_info: [:user_agent, :x_headers, :uri, :peer_data, :trace_context_headers, session: @session_options]]
    

    to get the other headers like accept-language you would need to pass it over from conn object to your live views somehow. You can simply do it with session. Create a simple plug to do that or add that to your existing plug (eg. authentication)

    conn
    |> put_session(:accepted_lang, get_req_header(conn, "accept-language"))
    |> assign(:current_user, user)
    

    and in your LiveView's mount just read it

       def mount(_params, session, socket) do
         
         lang = session["accepted_lang"]
         .....
       end
    

    Hope that helps