Using Firebase and Hugo? Use front matter aliases to automatically add redirects to your firebase.json configuration. Turning your aliases into proper 301 or 302 redirects.

First we need to output all aliases to a json file, and to do that we need to define a new output to our Hugo configuration file — in my case: config.toml

[outputs]
  home = ["HTML", "RSS", "REDIR"]

[outputFormats.REDIR]
  baseName = "redirects"
  isPlainText = true
  mediaType = "application/json"
  notAlternative = true

Then we need to create a layout file, layouts/index.redir.json

{{- $index := slice -}}
{{- range $p := .Site.Pages -}}
{{- range .Aliases -}}
{{- $index = $index | append (dict "source" . "destination" $p.RelPermalink "type" ($p.Params.HTTPCode | default 301)) -}}
{{- end -}}
{{- end -}}
{{- $index | jsonify (dict "indent" "  ") -}}

When we generate our site now; we will get a redirects.json file listing all defined aliases. I currently only have one, so my file looks like this:

[
  {
    "destination": "/2021/01/optiplex-9010-sff-cmos-battery/",
    "source": "/2021/01/optiplex-9010-sff-bios-battery/",
    "type": 301
  }
]

So far so good — except it doesn’t really do anything. We need to add this to our firebase.json file, and we can do that with the jq command.

Let’s try it now. We start with this minimum firebase.json configuration:

{
  "hosting": {
    "public": "public"
  }
}

From your Hugo project root — run the command:

jq ".hosting.redirects += $(cat public/redirects.json)" firebase.json > firebase_test.json

And now look at our firebase_test.json — it has redirects! 😃

{
  "hosting": {
    "public": "public",
    "redirects": [
      {
        "destination": "/2021/01/optiplex-9010-sff-cmos-battery/",
        "source": "/2021/01/optiplex-9010-sff-bios-battery/",
        "type": 301
      }
    ]
  }
}

To do this during deployment; I added a new step to my Drone SSH pipeline configuration (.drone.yml) file, between my build and deploy steps:

- name: firebase-redirects
  commands:
  - jq ".hosting.redirects += $(cat public/redirects.json)" firebase.json > firebase_redir.json
  - mv firebase_redir.json firebase.json
  - cat firebase.json

If you already have redirects defined in your firebase.json — the aliases will just be appended. Works great 🙂

Resources

Last commit 2024-04-05, with message: More tag clean up.