Files
sweet/packages/fresh/src/middlewares/trailing_slashes.ts
T
Marvin Hagemeister 815b1940e3 chore: restructure repository into packages/ folder (#3197)
We're having a growing number of packages in this repository. This PR
moves them into a `packages/` directory like it's commonly done in other
projects.
2025-08-06 15:52:45 +02:00

30 lines
850 B
TypeScript

import type { Middleware } from "./mod.ts";
/**
* Fresh middleware to force URLs to end with a slash or never end with one.
*
* ```ts
* // Always add trailing slash
* app.use(trailingSlashes("always"));
* // Never add trailing slashes to URLs and remove them if present
* app.use(trailingSlashes("never"));
* ```
*/
export function trailingSlashes<State>(
mode: "always" | "never",
): Middleware<State> {
return function trailingSlashesMiddleware(ctx) {
const url = ctx.url;
if (url.pathname !== "/") {
if (mode === "always" && !url.pathname.endsWith("/")) {
return ctx.redirect(`${url.pathname}/${url.search}`);
} else if (
mode === "never" && url.pathname.endsWith("/")
) {
return ctx.redirect(`${url.pathname.slice(0, -1)}${url.search}`);
}
}
return ctx.next();
};
}