Skip to content

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

Merged
yusukebe merged 3 commits into
nextfrom
feat/method-not-allowed-middleware
Aug 3, 2026
Merged

feat(middleware): add method-not-allowed middleware#5132
yusukebe merged 3 commits into
nextfrom
feat/method-not-allowed-middleware

Conversation

@usualoma

Copy link
Copy Markdown
Member

#4633

Introduce an opt-in methodNotAllowed middleware. It returns 405 Method Not Allowed with an Allow header when the path exists for another method.

Compared with the implementation discussed in the issue, this version:

  • accepts { app, onMethodNotAllowed? } to support custom responses
  • assigns the response to c.res instead of throwing an HTTPException, allowing outer middleware to observe the final status without invoking onError
  • follows Hono's routing behavior for HEAD/GET, custom methods, and case-sensitive method matching
  • supports middleware installed in sub-apps composed with app.route()
  • preserves error-handler 404 responses and removes stale representation headers when replacing a 404

Why assign the response to c.res instead of throwing an HTTPException?

This follows the existing response-transforming middleware pattern used by trailingSlash, etag, and prettyJSON, which replace c.res after await next().

A 405 Method Not Allowed response here is a normal routing outcome derived from a downstream 404 Not Found, rather than an exceptional failure. Assigning it to c.res preserves normal middleware unwinding, lets outer middleware observe the final 405 status, and avoids invoking the application's onError handler.

The author should do the following, if applicable

  • Add tests
  • Run tests
  • bun run format:fix && bun run lint:fix to format the code
  • Add TSDoc/JSDoc to document the code

@usualoma

Copy link
Copy Markdown
Member Author

Hi @yusukebe,
Could you please leave a review?

@github-actions

This comment has been minimized.

@codecov

codecov Bot commented Jul 17, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 79.37%. Comparing base (3bc96ba) to head (187f170).

Additional details and impacted files
@@            Coverage Diff             @@
##             next    #5132      +/-   ##
==========================================
+ Coverage   79.28%   79.37%   +0.08%     
==========================================
  Files         154      155       +1     
  Lines       10863    10909      +46     
  Branches     2267     2279      +12     
==========================================
+ Hits         8613     8659      +46     
  Misses       2250     2250              

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@yusukebe yusukebe added the v4.13 label Jul 18, 2026

@yusukebe yusukebe left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM!

@yusukebe

yusukebe commented Aug 3, 2026

Copy link
Copy Markdown
Member

Hey @usualoma !

I think this is perfect! Great. Thanks!

@yusukebe
yusukebe changed the base branch from main to next August 3, 2026 20:46
@yusukebe
yusukebe force-pushed the feat/method-not-allowed-middleware branch from be135ab to 187f170 Compare August 3, 2026 21:04
@github-actions

This comment has been minimized.

@github-actions

This comment has been minimized.

@github-actions

github-actions Bot commented Aug 3, 2026

Copy link
Copy Markdown

Bundle size check

main (734755a) #5132 (4790646) +/-
Bundle Size (B) 19,032B 19,042B 10B
Bundle Size (KB) 18.59K 18.6K 0.01K

Compiler Diagnostics (tsc)

main (734755a) #5132 (4790646) +/-
Files 83 83 0
Lines 59,439 59,440 1
Identifiers 60,614 60,621 7
Symbols 105,939 106,532 593
Types 159,727 163,063 3,336
Instantiations 413,958 414,023 65
Memory used 167,880K 169,401K 1,521K
I/O read 0.01s 0.01s 0s
I/O write 0s 0s 0s
Parse time 0.36s 0.34s -0.02s
Bind time 0.15s 0.14s -0.01s
Check time 1.36s 1.4s 0.04s
Emit time 0s 0s 0s
Total time 1.87s 1.88s 0.01s

Compiler Diagnostics (typescript-go)

main (734755a) #5132 (4790646) +/-
Files 215 215 0
Lines 147,087 147,088 1
Identifiers 121,968 121,974 6
Symbols 188,307 189,100 793
Types 259,012 262,348 3,336
Instantiations 621,523 621,588 65
Memory used 160,784K 161,844K 1,060K
Memory allocs 1,776,777 1,781,249 4,472
Config time 0.001s 0.001s 0s
BuildInfo read time 0s 0s 0s
Parse time 0.09s 0.093s 0.003s
Bind time 0s 0s 0s
Check time 0.486s 0.424s -0.062s
Emit time 0.004s 0.005s 0.001s
Changes compute time 0.024s 0.024s 0s
Total time 0.658s 0.58s -0.078s

Reported by octocov

@github-actions

github-actions Bot commented Aug 3, 2026

Copy link
Copy Markdown

HTTP Performance Benchmark

Framework Runtime Average Ping Query Body
hono (origin/main) bun 35,288.97 50,188.42 30,566.03 25,112.46
hono (current) bun 35,888.50 47,950.41 33,010.61 26,704.48
Change +1.70% -4.46% +8.00% +6.34%

@yusukebe
yusukebe merged commit 1f707c5 into next Aug 3, 2026
37 of 38 checks passed
@yusukebe
yusukebe deleted the feat/method-not-allowed-middleware branch August 3, 2026 21:10
yusukebe added a commit that referenced this pull request Aug 3, 2026
* perf(hono-base): avoid rest parameter in `fetch` (#5113)

* perf(context): iterate the header record with for..in (#5118)

* perf(url): replace regex tests with indexOf (#5121)

* perf(context): skip Headers creation when there are no headers to merge (#5122)

* perf(urls): refactor `tryDecodeURIComponent` (#5158)

* chore(benchmarks): correct src path on Windows, add json and middleware cases (#5173)

The default src path was computed with `URL.pathname`, which yields
`/C:/sources/hono/src` on Windows and, after `pathToFileURL`, the broken
path `C:\C:\sources\hono\src`. `fileURLToPath` is correct on all platforms.

Also adds two cases:

- `json GET /user` isolates the `c.json()` response path, which was
  previously only measured inside `body POST /json` mixed with request
  body parsing.
- `middleware GET /mw/hello` covers the multi-handler `compose` dispatch
  path, which none of the existing cases exercised.

* perf(context): drop the throwaway `env` field initializer (#5174)

`env: E['Bindings'] = {}` allocated an object on every `Context`
construction that `#dispatch` immediately overwrote with the real env,
so the allocation was wasted on every request.

The initializer only ever mattered for `new Context(req)` without
options, which now gets its `{}` from the constructor's `else` branch.
Semantics are unchanged, including `env` being `undefined` when
`options.env` is `undefined`.

* perf(request): allocate `#validatedData` lazily (#5175)

The constructor allocated `#validatedData = {}` on every `HonoRequest`,
so every request paid for the validator feature whether or not any
validator ran.

It is now created on the first `addValidatedData()` call. `valid()`
reads through optional chaining and still returns `undefined` for
targets that were never validated, as before.

* perf(request): probe the body cache without allocating (#5176)

`#cachedBody` used `Object.keys(bodyCache)[0]` to find any already
cached body, allocating a fresh array on every body read (`req.json()`,
`req.text()`, ...) just to read one element.

A `for ... in` loop that returns on its first iteration gives the same
first-key-by-insertion-order result with no allocation. `bodyCache` is a
plain object literal, so there are no enumerable prototype keys to
consider.

* chore(benchmarks): stabilize measurements by forcing mitata batching (#5183)

* perf(hono-base): restore the rest parameter in `fetch` (#5184)

* perf(context): restore the `env` field initializer (#5186)

* feat: add first-class QUERY method support (#5070)

* feat(etag): support conditional requests for the QUERY method (#5111)

* feat(cors): allow QUERY by default as a first-class method (#5115)

* feat(cache): add first-class support for QUERY requests (#5119)

* feat(cache): support QUERY requests

* fix(cache): report unavailable QUERY hashing

* fix(cache): include request method in cache keys

* docs(cache): show QUERY-compatible registration

* feat(jsx): add React-compatible overloads to useRef (#5063)

* feat(jsx): add React-compatible overloads to useRef

Adds overloads so that useRef returns a non-nullable ref when given a
non-null initial value, matching React's API.

- useRef<T>(initialValue: T): MutableRefObject<T>
- useRef<T>(initialValue: T | null): RefObject<T>
- useRef<T = undefined>(): MutableRefObject<T | undefined>

This is a type-only change; the runtime implementation is unchanged.

Closes #5056

* feat(jsx)!: align RefObject and useRef with React 19

- `RefObject<T>` now has non-null mutable `current`
- `MutableRefObject<T>` becomes a deprecated alias
- `useRef` overloads match React 19; zero-arg form removed in favor of
  `useRef(undefined)`
- `createRef`, `forwardRef`, `useImperativeHandle` updated to use
  `RefObject<T | null>` for nullable refs

BREAKING CHANGE: `RefObject<T>` was `{ current: T | null }`; nullable
refs should now be typed as `RefObject<T | null>`. `useRef()` with no
argument no longer type-checks; pass `undefined` explicitly.

* ci: apply automated fixes

* refactor(jsx): remove MutableRefObject alias

hono/jsx has never exposed MutableRefObject before, and React 19 marks
it as deprecated. Per PR discussion, drop the alias entirely instead of
keeping a deprecated re-export.

---------

Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>

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

* feat(middleware): add method-not-allowed

* test(middleware): cover method-not-allowed

* chore(exports): expose method-not-allowed

Resolve #4633

* feat(jwt,jwk): add a configurable WWW-Authenticate realm (#5141)

* feat(jwt): add a realm option and escape challenge values

The 401 challenge hardcoded `ctx.req.url` as the `realm`. RFC 6750 describes
realm as a stable, human-readable name for the protection space, so reflecting
the full URL produces a different realm for every path and query string.
bearer-auth already exposes a `realm` option; jwt had no equivalent and its
`unauthorizedResponse()` helper is private, leaving no way to override it.

`realm` and `error_description` are also interpolated into a quoted-string
without escaping, so a `"` in either truncates the header. Both are now escaped
the way bearer-auth does it.

The default is unchanged to stay backward compatible.

Refs #4989

* feat(jwk): add a realm option and escape challenge values

Mirrors the preceding jwt change; jwk carries an identical copy of
`unauthorizedResponse()` with the same hardcoded realm and unescaped
interpolation.

Refs #4989

* test(jwt,jwk): cover realm configuration and quote escaping

Asserts the configured realm reaches the WWW-Authenticate header for both the
missing-credentials and invalid-token paths, that embedded double quotes are
escaped, and that the default is still the request URL.

The realm and escaping cases fail without the preceding commits; the default
cases guard against regressing existing behavior.

* add a test

---------

Co-authored-by: Yusuke Wada <yusuke@kamawada.com>

* feat(utils/headers): add HTTP fields newly registered with IANA (#5153)

* fix(jsx): allow a function component to return an array (#5179)

* fix(jsx): allow a function component to return an array

A function component returning an array threw "str.search is not a
function" during server-side rendering. The return value did not match
any branch in JSXFunctionNode.toStringToBuffer() and fell through to
escapeToBuffer(), which expects a string.

Handle arrays with childrenToStringToBuffer(), the same path already
used for array children. JSX.ElementType is also added so that the
type layer accepts components returning any renderable value, matching
what hono/jsx/dom already supports at runtime.

* fix(jsx): accept an array return in the type layer

The runtime already renders a function component that returns an array,
but the type layer still rejected it. Add `Child[]` to the call
signature of `FC`, and define `JSX.ElementType` with the same return
type.

Without `JSX.ElementType`, TypeScript checks the return type against
`JSX.Element` and reports TS2786. Both types now accept exactly the same
set of return values, so nothing beyond arrays becomes newly valid.

* fix(jsx): render an array resolved from a promise

An async function component returning an array produced escaped,
comma-joined text instead of markup, because the resolved array reached
the string buffer as-is and was stringified by `String()`. Wrap a
resolved array in a fragment so it is rendered like any other node.

`Child` now carries `Promise<string | Child[]>`, which surfaced the same
hole for children: a child promise resolving to an array took the same
path. Both call sites share `resolveArrayToFragment()`, which also
attaches the suspended context, so the promise branch of
`JSXFunctionNode` no longer needs its own `then()` chain.

* fix(jsx): scope promised arrays to component results

* fix(jsx-renderer): accept array component results

* fix(jsx): preserve callbacks in component arrays

* refactor(jsx): remove obsolete suspended context state

---------

Co-authored-by: Taku Amano <taku@taaas.jp>

* feat(reg-exp-router): throw UnsupportedPathError during route registration (#5171)

* fix(reg-exp-router): make wildcard sibling order in the regexp deterministic

compareKey() was inconsistent when comparing the only wildcard with
the tail wildcard, so their order relied on the insertion order
normalized by the path-length sort in the matcher build.

* fix(reg-exp-router): capture params on a label node created by an unnamed wildcard

A param like /w/:id/y registered together with /w/*/x reused the label
node created by the unnamed wildcard, which has no var index assigned,
so the param value was lost.

* feat(reg-exp-router): throw UnsupportedPathError when adding routes

Insert paths into per-method tries incrementally in add() so that
unsupported path combinations are detected at registration time
instead of at the first match.

- Static paths are inserted as real nodes (character by character,
  with no pattern interpretation), but branches without a dynamic
  terminal are excluded from the regexp, so the generated matchers
  stay identical to the previous implementation.
- Conflict checks no longer depend on the insertion order: wildcard
  nodes coexist with anything, and a single-character pattern like
  /:x{a} coexists with single-character literals.
- Node#insert is now a loop instead of recursion with array spreads,
  making registration plus the first match roughly 20% faster.

* test(reg-exp-router): cover method-specific path validation

* fix(compress): set Vary: Accept-Encoding on negotiated responses (#5137)

* fix(compress): set Vary: Accept-Encoding on compressed responses

The compress middleware negotiates gzip/deflate from the request's
Accept-Encoding header but never advertises Vary: Accept-Encoding on the
response. A shared cache can then store the compressed body and serve it
to a client that did not send a compatible Accept-Encoding, breaking that
client. Add Accept-Encoding to the response's Vary header when compressing,
appending to any existing Vary value and avoiding duplicates.

* fix(compress): set Vary: Accept-Encoding on identity responses too

Move the Vary handling ahead of the encoding negotiation so that a response
left uncompressed — because Accept-Encoding was absent or offered nothing the
middleware supports — is also marked as varying on Accept-Encoding. RFC 9110
lists Accept-Encoding "or lack thereof" as a determining factor, so without
this a shared cache can reuse the identity response for a client that does
accept gzip.

The helper now takes the Context and writes through ctx.header(), which
recreates the response when a handler returned a fetch() response. On Node
that recreation inherits the immutable header guard from the original
response, so the write can still throw; fall back to rebuilding the response
around a fresh Headers instance in that case.

* refactored

* remove the node.js test

* ci: apply automated fixes

---------

Co-authored-by: Yusuke Wada <yusuke@kamawada.com>
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>

---------

Co-authored-by: Igor Savin <iselwin@gmail.com>
Co-authored-by: haki <165590443+shellhaki@users.noreply.github.com>
Co-authored-by: James Ross <james@jross.me>
Co-authored-by: Taku Amano <taku@taaas.jp>
Co-authored-by: asahi <166529527+ashunar0@users.noreply.github.com>
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
Co-authored-by: Arham Amin <132888838+arhxam@users.noreply.github.com>
Co-authored-by: Hiroki Akahoshi <64849251+akahoshi1421@users.noreply.github.com>
Co-authored-by: natsuki ueda <63272932+natsuki-engr@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants