Phoenix Cache Policy Not Working - unable to see headers in developers tools

Hi, I have setup some headers for Static Files. I’m serving a SPA, which are already build outside the server. I’m using this headers.

defmodule MyWeb.Headers do
  @behaviour Plug
  import Plug.Conn

  @impl Plug
  def init(opts), do: opts

  @impl Plug
  def call(conn, param) do
    conn
    |> put_resp_header("x-frame-options","SAMEORIGIN")
    |> put_resp_header("x-xss-protection","1; mode=block")
    |> put_resp_header("x-content-type-options","nosniff")
    |> put_resp_header("referrer-policy","no-referrer-when-downgrade")
    |> put_resp_header("cache-control","public max-age=31436000")
  end
  
end

And invoking it from the router:

defmodule MyWeb.Router do
  use MyWeb, :router

  pipeline :browser do
    plug :accepts, ["html"]
    plug MyWeb.Headers
  end

  scope "/", MyWeb do
    pipe_through :browser
    forward "/", Static
  end

end

However, I’m no able to see the headers in the developers tools. Any idea what could be wrong?

Probably because the :browser pipeline would only apply them to HTML documents? Do you see the headers if you request one of your Phoenix-generated pages (.html.eex)?

Yes! I see them only for html. How do I apply these headers for CSS, JS and other static files?

see https://hexdocs.pm/plug/Plug.Static.html#module-options it has a key for setting the headers on everything related to static assets. You can find the configuring of the Static plug (if not changed from default) in your endpoint.ex file. Hope this helps!

3 Likes

@rjk thnx! the headers: option was the solution. Thank you so much.