Azure Static Web Apps and the Trailing Slash

I recently published a blog post on setting up Twitter Cards in Hugo and shared it on Twitter and LinkedIn. A friend of mine (shout out Scott Cate) kindly sent me a message letting me know my images were broken. After brief panic and embarrassment, I went and checked my blog post (for the nth) time and was confused… I checked from the link I shared on Twitter and I checked manually in Chrome and Safari on my iPhone, but my images were showing just fine.. I responded to Scott and told him I couldn’t replicate the issue. He sent me screenshots of the images being broken on his end and I checked again, this time from 3 different laptops. I still couldn’t recreate the issue. Then Scott sent me another message…

He realized I was looking at the blog post with a trailing slash i.e. https://jessicadeen.com/posts/2024/twitter-cards-hugo/ and he was looking at it without it i.e. https://jessicadeen.com/posts/2024/twitter-cards-hugo. This created a problem because my posts rely on relative links for image URLs. Yikes! How embarrassing - I published a blog post about how to have images in your Twitter cards and my own site had broken images in certain scenarios.

I fired up my dev container and immediately went to work. I ran hugo serve and attempted to replicate the issue locally, wondering how I missed this the first time. Interestingly enough, when I tried to view the link without a trailing slash http://localhost:1313/posts/2024/twitter-cards-hugo, hugo automatically corrected it and added a trailing slash i.e. http://localhost:1313/posts/2024/twitter-cards-hugo/. It donned on me the issue likely was happening with my web server: Azure Static Web Apps.

I discovered this issue on GitHub that addressed my exact problem and the solution was super easy.

TL;DR:

I added a staticwebapp.config.json file to the root of my hugo directory. In that file I put the following code:

{
    "trailingSlash": "always"
}

I created a new branch, pushed my single file change, and opened a PR. Once the PR build completed, I tested the change by intentionally going to posts without a trailing slash. Sure enough, I was now redirected as expected to the correct URL!

Great! I merged the pull request and set off to write the blog post you’re currently reading in case others run into the same confusion Scott and I did.