Trailing Slashes with Astro on Vercel

Handling trailing slashes to avoid SEO issues by using Vercel rewrites

ยท 1 min read

While implementing this blog with Astro, I realized that it was necessary to handle trailing slashes to avoid duplicated content from an SEO perspective. This behavior is usually provided out of the box for a Next.js application.

Generating the canonical URL can easily with the following snippet and be assigned to a link header.

---
const canonicalUrl = new URL(Astro.url.pathname, Astro.site);
---

<!DOCTYPE html>
<html lang="en">
  <head>
    <link rel="canonical" href={canonicalUrl} />
  </head>
</html>

However, when deploying a static output to Vercel, this does not prevent browsers to access either /about and /about/ for example as the page will be generated as /about/index.html.

Besides going back to SSR, Vercel rewrites can be used to perform the redirection. Since this is a common use-case, trailingSlash option in the vercel.json configuration file can be used to get this behavior.

{
  "trailingSlash": false
}

When using @astrojs/sitemap, sitemap links can be ensured to follow the trailingSlash Astro option thanks to withastro/astro#4553.

export default defineConfig({
  // ...
  trailingSlash: 'never',
  // ...
});