Skip to content

When serveStatic and methodNotAllowed are used together, methods other than GET cannot be handled correctly #5223

Description

@na-trium-144

What version of Hono are you using?

4.13.1

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

Node.js

What steps can reproduce the bug?

The documentation includes examples of serveStatic middleware being used with both get() and use().
But in both cases methodNotAllowed does not work as expected.

with get:

const app = new Hono()
app.use(methodNotAllowed(app));
app.get("/api", (c) => c.text("ok"));
app.get("/*", serveStatic());

with use:

const app = new Hono()
app.use(methodNotAllowed(app));
app.get("/api", (c) => c.text("ok"));
app.use("/*", serveStatic());

What is the expected behavior?

  • return 200 on GET /api,
  • return 200 on GET existing file,
  • return 404 on GET non-existent file,
  • return 405 on POST /api,
  • return 405 on POST existing file,
    • or maybe 404 is also accepted in this case?
  • return 404 on POST non-existent file.

What do you see instead?

with get(serveStatic):

  • return 405 on POST /api,
  • return 405 on POST existing file,
  • return 405 on POST non-existent file.

with use(serveStatic),

  • return 405 on POST /api,
  • return 200 on POST existing file,
  • return 404 on POST non-existent file.

Additional information

I think the solution would be:

  • modify serveStatic so it returns 404 or 405 when request method is neither GET or HEAD, and
  • document the requirement to use serveStatic with use() rather than get(), (though its slightly counter-intuitive as serveStatic should handle only GET,) particularly when you are using methodNotAllowed together.

Alternatively,

  • ignore wildcard path in methodNotAllowed middleware, just as .all() route is currently ignored. This feels more generic but I don't know if this is always the expected behavior.
    • This results in 404 on POST existing file, but I think it is at least better than 405 on POST non-existent file.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions