h3 icon indicating copy to clipboard operation
h3 copied to clipboard

Nested route only works with double slashs at end???????

Open silvercent011 opened this issue 1 year ago • 6 comments

Environment

h3 - 1.11.1 node - 18

Reproduction

import { createApp, createRouter, defineEventHandler, useBase } from "h3";

export const app = createApp();

const router = createRouter();

const apiRouter = createRouter();

apiRouter.get(
  "/",
  defineEventHandler((event) => {
    console.log("Hello from router!");
    return { message: "Hello from router!" };
  })
);

router.use("/api/**", useBase("/api", apiRouter.handler));

app.use(router);

Describe the bug

The nested router, only works if the path have two slashes at end of url, http://localhost:3000/api//, without double slash, throw a 404 error.

Additional context

No response

Logs

No response

silvercent011 avatar Mar 18 '24 02:03 silvercent011

Would you provide a minimal reproduction instead of just showing the code? Although you seem to have just copied and modified the code from documentation, runnable reproduction is much helpful for maintainers. 🙌

You can use StackBlitz, for example.

One of benefits of providing it is that we could folk your code and share fixed version if it's just a mistake. Otherwise, we will dig into the issue.

nozomuikuta avatar Mar 18 '24 04:03 nozomuikuta

https://stackblitz.com/edit/stackblitz-starters-krifhq?file=src%2Fapp.ts

silvercent011 avatar Mar 18 '24 05:03 silvercent011

Thank you for providing the reproduction!! Now it's much easier to debug! 🙏

As far as I checked, there seems to be a bug in h3 routing. The root cause would exist in useBase of h3, or https://github.com/unjs/radix3/issues/84 might be related.

At the moment, one workaround is to stop using top-level router and let api router look up its routes.

https://stackblitz.com/edit/stackblitz-starters-ygfkoc?file=src%2Fapp.ts

nozomuikuta avatar Mar 18 '24 05:03 nozomuikuta

ok, thanks for the support @NozomuIkuta :)

Should I close the issue or leave it open for resolution of the bug/documentation/or similar?

silvercent011 avatar Mar 18 '24 06:03 silvercent011

My pleasure. Would you keep it open for governance so that author can recognize this issue?

nozomuikuta avatar Mar 18 '24 06:03 nozomuikuta

Yep!

silvercent011 avatar Mar 18 '24 06:03 silvercent011

This issue has been resolved in rou3.

h3@1 uses an older version of rou3 (previously named radix3), but the upcoming h3@2 addresses this by upgrading to the latest rou3.

kricsleo avatar Apr 23 '25 11:04 kricsleo

in h3 v2 nested app support is much better:

import { H3, serve, redirect, withBase } from "h3";

const nestedApp = new H3().get("/test", () => "/test (sub app)");

const app = new H3()
  .get("/", (event) => redirect(event, "/api/test"))
  .all("/api/**", withBase("/api", nestedApp.handler));

serve(app);

pi0 avatar Jun 04 '25 21:06 pi0