Skip to content

Instantly share code, notes, and snippets.

@chaance
Created March 11, 2023 00:32
Show Gist options
  • Save chaance/3294b9a2b6d94c77ff58b1d989b5f586 to your computer and use it in GitHub Desktop.
Save chaance/3294b9a2b6d94c77ff58b1d989b5f586 to your computer and use it in GitHub Desktop.
Remove trailing slashes to URL via redirect in Remix
import { redirect, type LoaderArgs } from "@remix-run/node";
export async function removeTrailingSlashes(request: Request) {
let url = new URL(request.url);
if (url.pathname.endsWith("/") && url.pathname !== "/") {
throw redirect(url.pathname.slice(0, -1) + url.search);
}
}
export async function loader({ request }: LoaderArgs) {
removeTrailingSlashes(request);
// ... return your data!
}
@donavon-silverback
Copy link

donavon-silverback commented Mar 12, 2023

Thank you for this. It's very useful.

I would suggest doing this instead of manually rebuilding the URL. It also covers hash by default.

export async function removeTrailingSlashes(request: Request) {
  const url = new URL(request.url);
  if (url.pathname.endsWith("/") && url.pathname !== "/") {
    url.pathname = url.pathname.slice(0, -1);
    throw redirect(url.href);
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment