Serving static CORS JSON with Caddy

For a side project, I needed to serve static JSON on a server that already ran Caddy. The front-end is a Svelte app, and the backend is a Rust cron-job that generates JSON files.

The easiest way to consume this JSON would be to serve it with Caddy, but I soon ran into CORS header issues.

After a couple of Google searches, I stumbled across this GitHub Gist Caddy v2.1 CORS whitelist, that almost made it work.

The complete solution was provided a few comments down, but for future reference for me and anyone else, this is the proper configuration:

(cors) {
  @origin{args.0} header Origin {args.0}
  header @origin{args.0} Access-Control-Allow-Origin "{args.0}"
  header @origin{args.0} Vary Origin
}
<your domain> {
  root * /home/<your app>
  file_server {
      index index.json
  }
  header Access-Control-Allow-Methods "POST, GET, OPTIONS"
  header Access-Control-Allow-Headers "*"

  import cors <any domain>
}

My full config looks like this:

(cors) {
  @origin{args.0} header Origin {args.0}
  header @origin{args.0} Access-Control-Allow-Origin "{args.0}"
  header @origin{args.0} Vary Origin
}
https://traveladvice-api.matsimitsu.com {
  root * /home/traveladvice/data
  file_server {
      index countries.json
  }
  header Access-Control-Allow-Methods "POST, GET, OPTIONS"
  header Access-Control-Allow-Headers "*"

  import cors http://localhost:3000
  import cors https://reisadvies.matsimitsu.nl
}