Remove and redirect trailing slashes from URLs in Nuxt 3

Create this file in your middleware folder called middleware/trailing-slash.global.js:

export default function ({ path, query, hash }) {
  if (path === "/" || !path.endsWith("/")) return;

  const nextPath = path.replace(/\/+$/, "") || "/";
  const nextRoute = { path: nextPath, query, hash };

  // 308 Permanent Redirect
  return navigateTo(nextRoute, { redirectCode: 308 });
}

Happy coding! – Found a mistake or a typo? Please submit a PR to my GitHub-repo.

Like this post? Follow @adriaandotcom on X