Skip to content

feat: add methodNotAllowed handler for 405 responses#4657

Closed
codewithkenzo wants to merge 2 commits intohonojs:mainfrom
codewithkenzo:feat/method-not-allowed-handler
Closed

feat: add methodNotAllowed handler for 405 responses#4657
codewithkenzo wants to merge 2 commits intohonojs:mainfrom
codewithkenzo:feat/method-not-allowed-handler

Conversation

@codewithkenzo
Copy link
Copy Markdown

@codewithkenzo codewithkenzo commented Feb 2, 2026

Fixes #4633

Right now Hono returns 404 when you hit a route that exists but with the wrong HTTP method. That's not quite right per the HTTP spec - it should be 405 Method Not Allowed.

This PR adds a methodNotAllowed() handler (similar to how notFound() works) so you can customize the response, and includes the Allow header listing which methods actually work for that path.

What changed

  • Added methodNotAllowed() method to customize the 405 response
  • Router now distinguishes "path doesn't exist" (404) from "path exists but wrong method" (405)
  • Default response includes the Allow header with valid methods
  • Works with basePath, nested routers via app.route(), etc.

Usage

const app = new Hono()

// Optional - customize the response
app.methodNotAllowed((c, allowedMethods) => {
  return c.json({ 
    error: 'Method not allowed',
    allowed: allowedMethods 
  }, 405)
})

app.get('/users', (c) => c.text('List users'))
app.post('/users', (c) => c.text('Create user'))

// DELETE /users -> 405 with Allow: GET, POST
// GET /nonexistent -> 404 (unchanged)

Kept it simple and followed the existing patterns. Let me know if anything needs tweaking!

@yusukebe
Copy link
Copy Markdown
Member

yusukebe commented Feb 2, 2026

We can't accept this PR. Please read the issue at #4633 in full. Closing.

@yusukebe yusukebe closed this Feb 2, 2026
@codewithkenzo codewithkenzo deleted the feat/method-not-allowed-handler branch February 2, 2026 02:19
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Return 405 Method Not Allowed when a path exists but the HTTP method is unsupported

2 participants