Getting error: (Plug.Conn.AlreadySentError) the response was already sent

Hello! I stuck with

    ** (Plug.Conn.AlreadySentError) the response was already sent

error, when I add localization to my phoenix application.
When I go to localhost:4000, I have redirected to localhost:4000/en, through my locale plug which gets locale from URL or session or header. And before that, I have an “the response was already sent” error.
Here’s my router.ex:

defmodule ProjectWeb.Router do
  use ProjectWeb, :router

  import ProjectWeb.UserAuth

  pipeline :browser do
    plug :accepts, ["html"]
    plug :fetch_session
    plug :fetch_live_flash
    plug :put_root_layout, {ProjectWeb.LayoutView, :root}
    plug :protect_from_forgery
    plug :put_secure_browser_headers
    plug :fetch_current_user
    plug ProjectWeb.Plugs.Locale

 live_session :default, on_mount: ProjectWeb.InitAssigns do
    scope "/", ProjectWeb do
      pipe_through [:browser]

      Enum.each(["/:locale", "/"], fn prefix ->
        get prefix <> "/", PageController, :index


And here’s my init_assigns.ex:

defmodule ProjectWeb.InitAssigns do
  import Phoenix.LiveView

  def on_mount(:default, _params, session, socket) do
    Gettext.put_locale(Map.get(session, "locale"))
    {:cont, socket}

Terminal output:

[info] GET /
[debug] Processing with ProjectWeb.PageController.index/2
[error] #PID<0.719.0> running ProjectWeb.Endpoint (connection #PID<0.718.0>, stream id 1) terminated
Server: localhost:4000 (http)
Request: GET /
** (exit) an exception was raised:
    ** (Plug.Conn.AlreadySentError) the response was already sent
[info] GET /en
[debug] Processing with ProjectWeb.PageController.index/2
  Parameters: %{"locale" => "en"}
  Pipelines: [:browser]

I hope I have described the problem clearly. Thanks in advance!

What is the code of ProjectWeb.Plugs.Locale?

1 Like