To Add or Remove trailing slashes?

Last updated: 

So I conducted some research and a Twitter Poll on that matter.

I know that it's not overly important if a site redirects to strip or add trailing slashes, or even allows both, as long as the canonical meta tag is set consistently

It's just a personal curiosity which pleases my #OCD 🤓

Middlewares to remove trailing slashes in Oak (or Koa)

If you're using Oak or Koa then you can drop this somewhere in your codebase and then apply it to all the routes you want the trailing slash to be removed from

import { Status } from "https://deno.land/[email protected]/http/http_status.ts";
const removeTrailingSlashMiddleware = async (
  ctx: Context,
  next: NextMiddleware,
) => {
  const { url } = ctx.request;
  if (url.pathname.endsWith("/")) {
    url.pathname = url.pathname.replace(/\/$/, "");
    ctx.response.status = Status.Found;
    return ctx.response.redirect(url);
  }
  await next();
};

Usage of removeTrailingSlashMiddleware

router.get(
  "/blog/:slug",
  removeTrailingSlashMiddleware,
  async (ctx: Context, next: NextMiddleware) => {
    ctx.response.body = "Trailing slash has been removed 👏";
  },
);

Middlewares to add trailing slashes in Oak (or Koa)

import { Status } from "https://deno.land/[email protected]/http/http_status.ts";
const addTrailingSlashMiddleware = async (
  ctx: Context,
  next: NextMiddleware,
) => {
  const { url } = ctx.request;
  if (!url.pathname.endsWith("/")) {
    ctx.response.status = Status.Found;
    url.pathname = `${url.pathname}/`;
    return ctx.response.redirect(url);
  }
  await next();
};

Usage of addTrailingSlashMiddleware

router.get(
  "/blog/:slug",
  addTrailingSlashMiddleware,
  async (ctx: Context, next: NextMiddleware) => {
    ctx.response.body = "Trailing slash has been added 👏";
  },
);

Canonical meta tag

It's still recommended to add the canonical URL to your pages <head/> like so

Canonical URL without trailing slash

<link rel="canonical" href="https://www.my.canonical/url" />

Canonical URL with trailing slash

<link rel="canonical" href="https://www.my.canonical/url/" />

More about trailing slashes

Can Rau
Can Rau

Doing web-development since around 2000, building my digital garden with a mix of back-to-the-roots-use-the-platform and modern edge-rendered-client-side-magic tech 📻🚀

Living and working in Cusco, Perú 🦙