Fundamentals of passing data from the Plug connection to the LiveView

There are two ways:

  1. By storing it in the session. You can define a plug that executes in your router and calls put_session to store the locale in the session. Then it will be available in the session in mount/3. This is the preferred approach and we even have an example with it in the docs: https://hexdocs.pm/phoenix_live_view/Phoenix.LiveView.html#module-using-gettext-for-internationalization

  2. Via get_connect_params. Open up your app.js and you will see there are some parameters passed to LiveSocket. If you wrap the locale on the page, in a meta tag for example, you can pass it down. This is how we handle things like csrf_token. You will be able to read it in your LiveView by calling Phoenix.LiveView.get_connect_params. Note though it will only be available in the websocket connection

17 Likes