Skip to content
Myr

index.ts

This file

Path

src/middleware/trailing-slash/index.ts

158 lines · 4.3 KiB · TypeScript

Last changed by

Not known.

History of this file

Take it

The walk stopped after 200 commits: lines older than f0b094d point at it.

Merge commit from forkYusuke Wadabefore adoptionf0b094d

lines 1–158why, one step back
1/**
2 * @module3 * Trailing Slash Middleware for Hono.4 */56import type { MiddlewareHandler } from '../../types'78type TrimTrailingSlashOptions = {9 /**10 * If `true`, the middleware will always redirect requests with a trailing slash11 * before executing handlers.12 * This is useful for routes with wildcards (`*`).13 * If `false` (default), it will only redirect when the route is not found (404).14 * @default false15 */16 alwaysRedirect?: boolean17}1819/**20 * Trailing Slash Middleware for Hono.21 *22 * @see {@link https://hono.dev/docs/middleware/builtin/trailing-slash}23 *24 * @param {TrimTrailingSlashOptions} options - The options for the middleware.25 * @returns {MiddlewareHandler} The middleware handler function.26 *27 * @example28 * ```ts29 * const app = new Hono()30 *31 * app.use(trimTrailingSlash())32 * app.get('/about/me/', (c) => c.text('With Trailing Slash'))33 * ```34 *35 * @example36 * ```ts37 * // With alwaysRedirect option for wildcard routes38 * const app = new Hono()39 *40 * app.use(trimTrailingSlash({ alwaysRedirect: true }))41 * app.get('/my-path/*', (c) => c.text('Wildcard route'))42 * ```43 */44export const trimTrailingSlash = (options?: TrimTrailingSlashOptions): MiddlewareHandler => {45 return async function trimTrailingSlash(c, next) {46 if (options?.alwaysRedirect) {47 if (48 (c.req.method === 'GET' || c.req.method === 'HEAD') &&49 c.req.path !== '/' &&50 c.req.path.at(-1) === '/'51 ) {52 const url = new URL(c.req.url)53 url.pathname = url.pathname.substring(0, url.pathname.length - 1)5455 return c.redirect(url.toString(), 301)56 }57 }5859 await next()6061 if (62 !options?.alwaysRedirect &&63 c.res.status === 404 &&64 (c.req.method === 'GET' || c.req.method === 'HEAD') &&65 c.req.path !== '/' &&66 c.req.path.at(-1) === '/'67 ) {68 const url = new URL(c.req.url)69 url.pathname = url.pathname.substring(0, url.pathname.length - 1)7071 c.res = c.redirect(url.toString(), 301)72 }73 }74}7576type AppendTrailingSlashOptions = {77 /**78 * If `true`, the middleware will always redirect requests without a trailing slash79 * before executing handlers.80 * This is useful for routes with wildcards (`*`).81 * If `false` (default), it will only redirect when the route is not found (404).82 * @default false83 */84 alwaysRedirect?: boolean85 /**86 * A function that determines whether to skip the redirect for a given path.87 * If the function returns `true`, the redirect will be skipped.88 * @param path - The request path89 * @returns `true` to skip the redirect90 *91 * @example92 * ```ts93 * // Skip redirect for paths with file extensions94 * app.use(appendTrailingSlash({95 * alwaysRedirect: true,96 * skip: (path) => /\.\w+$/.test(path),97 * }))98 * ```99 */100 skip?: (path: string) => boolean101}102103/**104 * Append trailing slash middleware for Hono.105 * Append a trailing slash to the URL if it doesn't have one. For example, `/path/to/page` will be redirected to `/path/to/page/`.106 *107 * @see {@link https://hono.dev/docs/middleware/builtin/trailing-slash}108 *109 * @param {AppendTrailingSlashOptions} options - The options for the middleware.110 * @returns {MiddlewareHandler} The middleware handler function.111 *112 * @example113 * ```ts114 * const app = new Hono()115 *116 * app.use(appendTrailingSlash())117 * ```118 *119 * @example120 * ```ts121 * // With alwaysRedirect option for wildcard routes122 * const app = new Hono()123 *124 * app.use(appendTrailingSlash({ alwaysRedirect: true }))125 * app.get('/my-path/*', (c) => c.text('Wildcard route'))126 * ```127 */128export const appendTrailingSlash = (options?: AppendTrailingSlashOptions): MiddlewareHandler => {129 return async function appendTrailingSlash(c, next) {130 if (options?.alwaysRedirect) {131 if (132 (c.req.method === 'GET' || c.req.method === 'HEAD') &&133 c.req.path.at(-1) !== '/' &&134 !options.skip?.(c.req.path)135 ) {136 const url = new URL(c.req.url)137 url.pathname += '/'138139 return c.redirect(url.toString(), 301)140 }141 }142143 await next()144145 if (146 !options?.alwaysRedirect &&147 c.res.status === 404 &&148 (c.req.method === 'GET' || c.req.method === 'HEAD') &&149 c.req.path.at(-1) !== '/' &&150 !options?.skip?.(c.req.path)151 ) {152 const url = new URL(c.req.url)153 url.pathname += '/'154155 c.res = c.redirect(url.toString(), 301)156 }157 }158}