When you are developing a Phoenix application, you might want to see the server logs in the browser console. This can be useful to debug issues that only happen in the server side.

There are two changes you need to make to your Phoenix application to achieve this:

  1. You need to enable the web_console_logger in your dev.exs configuration file:

    config :my_app, MyAppWeb.Endpoint,
    live_reload: [
    +   web_console_logger: true,
        patterns: [
        ~r"priv/static/.*(js|css|png|jpeg|jpg|gif|svg)$",
        ~r"priv/gettext/.*(po)$",
        ~r"lib/my_app_web/(controllers|live|components)/.*(ex|heex)$"
        ]
    ]
    
  2. Then in your assets/js/app.js enable the server logs when live reload is attached:

    window.addEventListener("phx:live_reload:attached", ({detail: reloader}) => {
        // Enable server log streaming to client.
        // Disable with reloader.disableServerLogs()
        reloader.enableServerLogs()
        window.liveReloader = reloader
    })
    

That's it! Happy hacking!