Serve dynamic JavaScript generated by HEEx with mime-type text/javascript for Chrome

I needed to send a dynamic JavaScript file generated with HEEx with mime-type text/javascript because Chrome refused to execute script from ‘http://localhost:4000/script.js’ because its MIME type (‘text/html’) is not executable, and strict MIME type checking is enabled.

  pipeline :text_javascript do
    plug :accepts, ["html"]
    plug :put_resp_content_type, "text/javascript"
  end

  scope "/", [AppName]Web do
    pipe_through :text_javascript

    get "/script.js", PageController, :web_config
  end

Hey @user20230119 can you elaborate a bit on what about your JS file needs to be generated? Heex in particular is a very strange template for that since it isn’t designed for JS.

Beyond that, normally you’d set the response content type in your controller, can you show the web_config function?

I’m porting an older application that uses a generated JS file.

How do you send a response content type from the controller? I couldn’t find how.

defmodule [AppName]Web.PageController do
  use [AppName]Web, :controller

  plug :put_root_layout, false

  def web_config(conn, _params) do
    render(conn, :web_config, layout: false)
  end

  def home(conn, _params) do
    # The home page is often custom made,
    # so skip the default app layout.
    render(conn, :home, layout: false)
  end
end

You call the put_resp_content_type function within the controller function

  def web_config(conn, _params) do
    conn
    |> Plug.Conn.put_resp_content_type("text/javascript")
    |> render(:web_config, layout: false)
  end
1 Like