Skip to content

feat: add 'methodNotAllowed' handler for '405 Method Not Allowed' responses#4637

Open
silvioprog wants to merge 1 commit intohonojs:mainfrom
silvioprog:feat/method-not-allowed-handler
Open

feat: add 'methodNotAllowed' handler for '405 Method Not Allowed' responses#4637
silvioprog wants to merge 1 commit intohonojs:mainfrom
silvioprog:feat/method-not-allowed-handler

Conversation

@silvioprog
Copy link
Copy Markdown

Summary

Adds an opt-in app.methodNotAllowed() handler that returns 405 Method Not Allowed responses when a path exists but the HTTP method is not supported. This improves HTTP semantics by properly distinguishing between routes that don't exist (404) and routes that exist but don't support the requested method (405).

Changes

  • Added MethodNotAllowedHandler and MethodNotAllowedResponse types
  • Added methodNotAllowed() method to HonoBase class
  • Implemented #findAllowedMethods() helper to detect allowed methods for a path
  • Updated #dispatch() to check for method not allowed when no route matches
  • Added comprehensive test suite covering various scenarios
  • Exported types from main index

Behavior

  • Opt-in: Feature is disabled by default (returns 404 as before)
  • When enabled: Returns 405 with Allow header listing permitted methods
  • Backward compatible: Existing behavior unchanged when handler is not set

Example Usage

const app = new Hono()

app.get('/hello', (c) => c.text('Hello'))

// Enable method not allowed handling
app.methodNotAllowed((c, allowedMethods) => {
  return c.text('405 Method Not Allowed', 405, {
    Allow: allowedMethods.join(', ').toUpperCase(),
  })
})

// POST /hello will now return 405 with Allow: GET
// GET /hello will return 200
// GET /nonexistent will return 404 (path doesn't exist)

Testing

  • Added tests
  • All tests pass (bun run test)
  • Code formatted (bun run format:fix)
  • Linting passes (bun run lint:fix)
  • TSDoc added to public APIs

Related

Closes #4633

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

1 participant