Skip to content

Have multiple notFound handlers #4173

Open
@kevinsimper

Description

@kevinsimper

What is the feature you are proposing?

Hi 😄

I am getting pretty far in my Hono server development and like it really! I tried to implement multiple notFound handlers and it seems like you can only have one handler. Tried to make a small example underneath.

import { Hono } from "hono";
import { serve } from "@hono/node-server";

const app = new Hono();

// API routes
const api = new Hono();
api.get("/users/:id", (c) => c.json({ id: c.req.param("id") }));

// Admin routes
const admin = new Hono();
admin.get("/dashboard", (c) => c.text("Admin Dashboard"));

// Mount sub-applications
app.route("/api", api);
app.route("/admin", admin);

// Problem: Only the last notFound handler is used globally
api.notFound((c) => {
  return c.json({ error: "API endpoint not found" }, 404);
});

admin.notFound((c) => {
  return c.html("<h1>Admin page not found</h1>", 404);
});

app.notFound((c) => {
  return c.text("Page not found", 404);
});

// Current behavior:
// GET /api/nonexistent -> "Page not found" (not the API-specific handler)
// GET /admin/nonexistent -> "Page not found" (not the admin-specific handler)
// GET /nonexistent -> "Page not found"

// Desired behavior:
// GET /api/nonexistent -> { "error": "API endpoint not found" }
// GET /admin/nonexistent -> <h1>Admin page not found</h1>
// GET /nonexistent -> "Page not found"

serve(app, (info) => {
  console.log(`Listening on http://localhost:${info.port}`); // Listening on http://localhost:3000
});

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