Skip to content
Myr

feat(middleware): add method-not-allowed middleware (#5132)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

* feat(middleware): add method-not-allowed * test(middleware): cover method-not-allowed * chore(exports): expose method-not-allowed Resolve #4633

authored by Taku Amano · committed by GitHub · parent 2df0b47 · Browse files · 4 files+442 added−0 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

4 files+442 added−0 removed

  • tests:+292 added−0 removed
  • other:+150 added−0 removed

4 files+442 added−0 removed

added:src/middleware/method-not-allowed/index.test.ts+292 added
1import { Hono } from '../../hono'2import { methodNotAllowed } from '.'34describe('Method Not Allowed Middleware', () => {5 it('infers the environment from the app', () => {6 const app = new Hono<{ Variables: { requestId: string } }>()7 const middleware = methodNotAllowed({8 app,9 onMethodNotAllowed: (c) => c.text(c.var.requestId, 405),10 })1112 expect(middleware).toBeTypeOf('function')13 })1415 it('returns 405 with every allowed method for an existing path', async () => {16 const app = new Hono()17 app.use(methodNotAllowed({ app }))18 app.get('/resource', (c) => c.text('GET'))19 app.post('/resource', (c) => c.text('POST'))20 app.delete('/resource', (c) => c.text('DELETE'))2122 const res = await app.request('/resource', { method: 'PUT' })2324 expect(res.status).toBe(405)25 expect(res.headers.get('Allow')).toBe('GET, HEAD, POST, DELETE')26 expect(await res.text()).toBe('Method Not Allowed')2728 const resUsingCachedRouter = await app.request('/resource', { method: 'OPTIONS' })29 expect(resUsingCachedRouter.status).toBe(405)30 expect(resUsingCachedRouter.headers.get('Allow')).toBe('GET, HEAD, POST, DELETE')31 })3233 it('does not affect an allowed method', async () => {34 const app = new Hono()35 app.use(methodNotAllowed({ app }))36 app.get('/resource', (c) => c.text('GET'))3738 const res = await app.request('/resource')3940 expect(res.status).toBe(200)41 expect(res.headers.has('Allow')).toBe(false)42 expect(await res.text()).toBe('GET')43 })4445 it('returns 404 when the path does not exist', async () => {46 const app = new Hono()47 app.use(methodNotAllowed({ app }))48 app.get('/resource', (c) => c.text('GET'))4950 const res = await app.request('/missing', { method: 'POST' })5152 expect(res.status).toBe(404)53 expect(res.headers.has('Allow')).toBe(false)54 })5556 it('matches parameterized and overlapping routes without duplicate methods', async () => {57 const app = new Hono()58 app.use(methodNotAllowed({ app }))59 app.get('/users/:id', (_c, next) => next())60 app.get('/users/me', (c) => c.text('me'))61 app.patch('/users/:id', (c) => c.text(c.req.param('id')))6263 const res = await app.request('/users/me', { method: 'POST' })6465 expect(res.status).toBe(405)66 expect(res.headers.get('Allow')).toBe('GET, HEAD, PATCH')67 })6869 it('preserves an intentional 404 from a handler registered for the request method', async () => {70 const app = new Hono()71 app.use(methodNotAllowed({ app }))72 app.get('/users/:id', (c) => c.notFound())73 app.post('/users/:id', (c) => c.text('Created'))7475 const res = await app.request('/users/123')7677 expect(res.status).toBe(404)78 expect(res.headers.has('Allow')).toBe(false)79 })8081 it('preserves an intentional 404 for HEAD when a GET route is registered', async () => {82 const app = new Hono()83 app.use(methodNotAllowed({ app }))84 app.get('/users/:id', (c) => c.notFound())85 app.post('/users/:id', (c) => c.text('Created'))8687 const res = await app.request('/users/123', { method: 'HEAD' })8889 expect(res.status).toBe(404)90 expect(res.headers.has('Allow')).toBe(false)91 })9293 it('preserves a 404 returned by the error handler', async () => {94 const app = new Hono()95 app.onError((_error, c) => c.text('Handled error', 404))96 app.use(methodNotAllowed({ app }))97 app.use('/resource', () => {98 throw new Error('boom')99 })100 app.get('/resource', (c) => c.text('GET'))101102 const res = await app.request('/resource', { method: 'POST' })103104 expect(res.status).toBe(404)105 expect(res.headers.has('Allow')).toBe(false)106 expect(await res.text()).toBe('Handled error')107 })108109 it('returns 405 for HEAD when the path does not support GET', async () => {110 const app = new Hono()111 app.use(methodNotAllowed({ app }))112 app.post('/resource', (c) => c.text('POST'))113114 const res = await app.request('/resource', { method: 'HEAD' })115116 expect(res.status).toBe(405)117 expect(res.headers.get('Allow')).toBe('POST')118 expect(await res.text()).toBe('')119 })120121 it('does not advertise explicit HEAD routes that Hono cannot dispatch', async () => {122 const app = new Hono()123 app.use(methodNotAllowed({ app }))124 app.on('HEAD', '/resource', (c) => c.text('HEAD'))125126 const headRes = await app.request('/resource', { method: 'HEAD' })127 expect(headRes.status).toBe(404)128 expect(headRes.headers.has('Allow')).toBe(false)129130 const putRes = await app.request('/resource', { method: 'PUT' })131 expect(putRes.status).toBe(404)132 expect(putRes.headers.has('Allow')).toBe(false)133 })134135 it('supports custom methods', async () => {136 const app = new Hono()137 app.use(methodNotAllowed({ app }))138 app.on('PURGE', '/cache', (c) => c.text('Purged'))139140 const res = await app.request('/cache', { method: 'POST' })141142 expect(res.status).toBe(405)143 expect(res.headers.get('Allow')).toBe('PURGE')144 })145146 it('compares request methods case-sensitively', async () => {147 const app = new Hono()148 app.use(methodNotAllowed({ app }))149 app.patch('/item', (c) => c.text('PATCH'))150151 const request = new Request('http://localhost/item', { method: 'PATCH' })152 Object.defineProperty(request, 'method', { value: 'patch' })153 const res = await app.request(request)154155 expect(res.status).toBe(405)156 expect(res.headers.get('Allow')).toBe('PATCH')157 })158159 it('works with routes mounted using app.route()', async () => {160 const api = new Hono()161 api.get('/resource', (c) => c.text('GET'))162 api.post('/resource', (c) => c.text('POST'))163164 const app = new Hono()165 app.use(methodNotAllowed({ app }))166 app.route('/api', api)167168 const res = await app.request('/api/resource', { method: 'DELETE' })169170 expect(res.status).toBe(405)171 expect(res.headers.get('Allow')).toBe('GET, HEAD, POST')172 })173174 it('works when installed in an app mounted using app.route()', async () => {175 const api = new Hono().basePath('/v1')176 api.use(methodNotAllowed({ app: api }))177 api.get('/resource', (c) => c.text('GET'))178 api.post('/resource', (c) => c.text('POST'))179180 const app = new Hono()181 app.route('/api', api)182183 const res = await app.request('/api/v1/resource', { method: 'DELETE' })184185 expect(res.status).toBe(405)186 expect(res.headers.get('Allow')).toBe('GET, HEAD, POST')187 })188189 it('ignores ALL routes when collecting allowed methods', async () => {190 const app = new Hono()191 app.use(methodNotAllowed({ app }))192 app.all('/resource', (_c, next) => next())193194 const res = await app.request('/resource', { method: 'POST' })195196 expect(res.status).toBe(404)197 expect(res.headers.has('Allow')).toBe(false)198 })199200 it('does not invoke the error handler for a 405 response', async () => {201 const app = new Hono()202 const onError = vi.fn(() => new Response('error', { status: 500 }))203 app.onError(onError)204 app.use(methodNotAllowed({ app }))205 app.get('/resource', (c) => c.text('GET'))206207 const res = await app.request('/resource', { method: 'POST' })208209 expect(res.status).toBe(405)210 expect(onError).not.toHaveBeenCalled()211 })212213 it('preserves downstream headers and lets outer middleware observe the final status', async () => {214 const app = new Hono()215 let observedStatus: number | undefined216217 app.use(async (c, next) => {218 await next()219 observedStatus = c.res.status220 })221 app.use(methodNotAllowed({ app }))222 app.use(async (c, next) => {223 await next()224 c.header('X-Downstream', 'true')225 })226 app.get('/resource', (c) => c.text('GET'))227228 const res = await app.request('/resource', { method: 'POST' })229230 expect(res.status).toBe(405)231 expect(res.headers.get('X-Downstream')).toBe('true')232 expect(observedStatus).toBe(405)233 })234235 it('replaces stale representation headers from the not-found response', async () => {236 const app = new Hono()237 app.use(methodNotAllowed({ app }))238 app.get('/resource', (c) => c.text('GET'))239 app.post('/resource', (c) => c.text('POST'))240 app.notFound((c) =>241 c.text('Missing', 404, {242 Allow: 'BOGUS',243 'Content-Length': '7',244 })245 )246247 const res = await app.request('/resource', { method: 'PUT' })248249 expect(res.status).toBe(405)250 expect(res.headers.get('Allow')).toBe('GET, HEAD, POST')251 expect(res.headers.has('Content-Length')).toBe(false)252 expect(await res.text()).toBe('Method Not Allowed')253 })254255 it('supports a custom method-not-allowed response', async () => {256 const app = new Hono()257 app.use(258 methodNotAllowed({259 app,260 onMethodNotAllowed: (c, allowedMethods) =>261 c.json({ error: 'Method Not Allowed', allowedMethods }, 405, {262 Allow: allowedMethods.join(', '),263 }),264 })265 )266 app.get('/resource', (c) => c.text('GET'))267 app.post('/resource', (c) => c.text('POST'))268269 const res = await app.request('/resource', { method: 'PUT' })270271 expect(res.status).toBe(405)272 expect(res.headers.get('Allow')).toBe('GET, HEAD, POST')273 expect(res.headers.get('Content-Type')).toMatch(/^application\/json/)274 expect(await res.json()).toEqual({275 error: 'Method Not Allowed',276 allowedMethods: ['GET', 'HEAD', 'POST'],277 })278 })279280 it('leaves a non-404 custom not-found response unchanged', async () => {281 const app = new Hono()282 app.use(methodNotAllowed({ app }))283 app.get('/resource', (c) => c.text('GET'))284 app.notFound((c) => c.text('Missing', 410))285286 const res = await app.request('/resource', { method: 'POST' })287288 expect(res.status).toBe(410)289 expect(res.headers.has('Allow')).toBe(false)290 expect(await res.text()).toBe('Missing')291 })292})
added:src/middleware/method-not-allowed/index.ts+141 added
1/**2 * @module3 * Method Not Allowed Middleware for Hono.4 */56import type { Context } from '../../context'7import { basePath, matchedRoutes } from '../../helper/route'8import type { Hono } from '../../hono'9import { METHOD_NAME_ALL } from '../../router'10import { TrieRouter } from '../../router/trie-router'11import type { Env, MiddlewareHandler } from '../../types'1213type MethodNotAllowedHandler<E extends Env> = (14 c: Context<E>,15 allowedMethods: string[]16) => Response | Promise<Response>1718type MethodNotAllowedOptions<E extends Env> = {19 // eslint-disable-next-line @typescript-eslint/no-explicit-any20 app: Hono<E, any, any>21 onMethodNotAllowed?: MethodNotAllowedHandler<E>22}2324/**25 * Method Not Allowed Middleware for Hono.26 *27 * Returns a `405 Method Not Allowed` response with an `Allow` header when the request path28 * matches a registered route but the request method is not supported.29 *30 * @param {MethodNotAllowedOptions} options - The options for the middleware.31 * @param {Hono} options.app - The Hono instance used by the application.32 * @param {MethodNotAllowedHandler} [options.onMethodNotAllowed] - Generates the response, including its `Allow` header.33 * @returns {MiddlewareHandler} The middleware handler function.34 *35 * @example36 * ```ts37 * const app = new Hono()38 *39 * app.use(methodNotAllowed({ app }))40 *41 * app.get('/hello', (c) => c.text('Hello!'))42 * app.post('/hello', (c) => c.text('Posted!'))43 *44 * // PUT /hello -> 405 Method Not Allowed45 * // Allow: GET, HEAD, POST46 * ```47 *48 * @example49 * ```ts50 * app.use(51 * methodNotAllowed({52 * app,53 * onMethodNotAllowed: (c, methods) =>54 * c.json({ error: 'Method Not Allowed' }, 405, { Allow: methods.join(', ') }),55 * })56 * )57 * ```58 */59export const methodNotAllowed = <E extends Env = Env>(60 options: MethodNotAllowedOptions<E>61): MiddlewareHandler<E> => {62 let methodRouter: TrieRouter<string[]> | undefined6364 return async function methodNotAllowed(c, next) {65 const routeIndex = c.req.routeIndex66 await next()6768 if (c.res.status !== 404) {69 return70 }7172 if (c.error) {73 return74 }7576 if (!methodRouter) {77 const methodsByPath = new Map<string, Set<string>>()7879 for (const route of options.app.routes) {80 // Hono does not distinguish middleware registered with `app.use()` from handlers81 // registered with `app.all()`, so `ALL` routes cannot contribute to the Allow header.82 if (route.method === METHOD_NAME_ALL || route.method === 'HEAD') {83 continue84 }8586 const methods = methodsByPath.get(route.path) ?? new Set<string>()87 methods.add(route.method)8889 // Hono dispatches HEAD requests to GET routes.90 if (route.method === 'GET') {91 methods.add('HEAD')92 }9394 methodsByPath.set(route.path, methods)95 }9697 methodRouter = new TrieRouter()98 for (const [path, methods] of methodsByPath) {99 methodRouter.add(METHOD_NAME_ALL, path, [...methods])100 }101 }102103 let requestPath = c.req.path104 const routes = matchedRoutes(c)105 const currentRoute = routes[routeIndex]106 const sourceRoute = options.app.routes.find((route) => route.handler === methodNotAllowed)107 if (currentRoute && sourceRoute) {108 const currentBasePathParts = basePath(c, routeIndex).split('/').filter(Boolean)109 const sourceBasePathLength = sourceRoute.basePath.split('/').filter(Boolean).length110 const mountBasePathParts = currentBasePathParts.slice(111 0,112 currentBasePathParts.length - sourceBasePathLength113 )114 if (mountBasePathParts.length > 0) {115 const mountBasePath = `/${mountBasePathParts.join('/')}`116 requestPath = c.req.path.slice(mountBasePath.length) || '/'117 }118 }119120 const allowedMethods = new Set<string>()121 for (const [methods] of methodRouter.match(METHOD_NAME_ALL, requestPath)[0]) {122 for (const method of methods) {123 allowedMethods.add(method)124 }125 }126127 if (allowedMethods.size === 0 || allowedMethods.has(c.req.method)) {128 return129 }130131 // Prevent stale headers from being carried over from the 404 response.132 c.res.headers.delete('Allow')133 c.res.headers.delete('Content-Length')134135 const methods = [...allowedMethods]136 const allow = methods.join(', ')137 c.res = options.onMethodNotAllowed138 ? await options.onMethodNotAllowed(c, methods)139 : c.text('Method Not Allowed', 405, { Allow: allow })140 }141}
modified:jsr.json+1 added
modified:package.json+8 added
229 unmodified lines
230 "types": "./dist/types/middleware/logger/index.d.ts",231 "import": "./dist/middleware/logger/index.js",232 "require": "./dist/cjs/middleware/logger/index.js"233 },234 "./method-not-allowed": {235 "types": "./dist/types/middleware/method-not-allowed/index.d.ts",236 "import": "./dist/middleware/method-not-allowed/index.js",237 "require": "./dist/cjs/middleware/method-not-allowed/index.js"238 },239 "./method-override": {240 "types": "./dist/types/middleware/method-override/index.d.ts",241 "import": "./dist/middleware/method-override/index.js",242 "require": "./dist/cjs/middleware/method-override/index.js"
289 unmodified lines
532 ],533 "logger": [534 "./dist/types/middleware/logger"535 ],536 "method-not-allowed": [537 "./dist/types/middleware/method-not-allowed"538 ],539 "method-override": [540 "./dist/types/middleware/method-override"541 ],542 "powered-by": [
164 unmodified lines