How to generate and serve sitemap.xml dynamically?

I have an application with a sitemap.xml. I need to modify it dynamically once a day. In production environment.

I know how to generate the content for it. But how can I actually replace(!) my current sitempa.xml with a new generated one, or rather its content? If it was a rails app, I’d merely replace its content and it’ll work, but for phoenix it’s different because it’s somehow compiled, right?

My code for serving sitemap.xml is the standard one:

defmodule MyApp.Endpoint do
  # ................

  # Serve at "/" the static files from "priv/static" directory.
  #
  # You should set gzip to true if you are running phoenix.digest
  # when deploying your static files in production.
  plug Plug.Static,
    at: "/", from: :my_app, gzip: false,
    only: ~w(css fonts images js favicon.ico robots.txt sitemap.xml)

Should I create a special route/action for “sitemap.xml” and serve it in a controller?

It is not different, just put a new sitemap.xml file and it will be served. Only *.ex files are compiled.

There is already package which will help you to do that easier.

put where?

As indicated

In case of release those folders do not exist physically m

1 Like

In case of release, would You recommand to add a route? Like mentionned?

That’s what I’m saying too. Then how?

I do see basically 2 and a half possibilities:

  1. If you are behind a reverse proxy, just generate the file and put it to a place where your RP can find and serve it before handing the request over to you. This is what I’d prefer for all static and semi-static resources
  2. Let Phoenix handle the generation of the data. Generate it once a day and put it into temporal storage on diosk or database and serve it from there.
  3. (this is the half one) Generate the data on each request. If you can do this quickly just do this for the sake of simplicity, if though generating the sitemap is costly, try to do one of the other points first!
4 Likes

Another option is to use a static .xml file for the static content that then points to a phoenix route for the dynamic content.