Skip to content

Add configurable route existence check before authentication middleware execution #4701

@BelovedYaoo

Description

@BelovedYaoo

What version of Hono are you using?

4.11.9

What runtime/platform is your app running on? (with version if possible)

Node 20.19.4 (but not important)

What steps can reproduce the bug?

  1. Set up a Hono app with authentication middleware
  2. Add some routes with authentication
  3. Make requests to non-existent paths
import { Hono } from 'hono'
import { jwt } from 'hono/jwt'

const app = new Hono()

// Authentication middleware
app.use('*', jwt({ secret: 'my-secret' }))

// Actual route
app.get('/protected', (c) => c.text('Protected content'))

// Request to non-existent path still triggers JWT validation
// GET /non-existent-route

What is the expected behavior?

When accessing non-existent routes:

  1. The server should first check if the route exists
  2. If route doesn't exist, return 404 immediately
  3. Authentication middleware should only run for valid routes

What do you see instead?

  1. Authentication middleware runs for ALL requests, even to non-existent routes
  2. This causes unnecessary CPU-intensive authentication processing
  3. Only after authentication does the framework return 404 for invalid routes

Additional information

Security Impact:

  • Creates a potential DoS vulnerability where attackers can spam random URLs to trigger expensive auth checks

  • Particularly problematic for JWT/OAuth/other crypto-heavy authentication

Performance Impact:

  • Wastes server resources validating authentication for invalid routes

  • Can significantly impact performance under high traffic

Suggested Solutions:

  1. Add global config option:
new Hono({ checkRouteBeforeAuth: true })
  1. Provide route validation middleware:
app.use(routeValidator()) // Checks route existence
app.use(authMiddleware)  // Then authenticates
  1. Expose routing inspection API for custom solutions

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions