middleware icon indicating copy to clipboard operation
middleware copied to clipboard

Dynamic routes with OpenAPI Hono not working under certain conditions

Open constantins2001 opened this issue 1 year ago • 4 comments

Issue Summary

When using the following code to set up a route, the route appears in the Swagger documentation but results in a 404 error when accessed:

const app = new OpenAPIHono<WorkerHonoContext>();
app.route("/api/v1/users/", usersHono);

export const usersHono = new OpenAPIHono<WorkerHonoContext>();
registerUserWebsocketRoute(usersHono);

export const UserWebsocketRoute = createRoute({
    tags: ["User"],
    summary: "User Websocket",
    method: "post",
    path: "{userId}/websocket",
    request: {
        cookies: CookiesSchema,
        params: ParamsSchema,
        headers: HeadersSchema,
    },
    responses: {
        "1001": { description: "WebSocket has been upgraded" },
        "400": ZodErrorResponseConfig,
        "429": ZodErrorResponseConfig,
    },
});

userHono.openapi(UserWebsocketRoute, async (c) => {
    ...
});

Expected Behavior

The route should be accessible, as it is correctly displayed in the Swagger documentation.

Actual Behavior

Attempting to access this route returns a 404 error.

Solution

The route becomes accessible if the following adjustments are made:

  1. Update the subrouter registration:

    app.route("/api/v1/users", usersHono);
    
  2. Adjust the path format in the UserWebsocketRoute:

    path: "/{userId}/websocket",
    

Additional Context

It seems that the trailing slash in the route definition (/api/v1/users/) and the missing leading slash in UserWebsocketRoute's path may be causing the routing issue.

constantins2001 avatar Nov 06 '24 18:11 constantins2001

I'm experiencing this too!

bgub avatar Apr 17 '25 18:04 bgub

@constantins2001 You should write path: "/{userId}/websocket" in createRoute.

yusukebe avatar Apr 17 '25 23:04 yusukebe

@constantins2001 You should write path: "/{userId}/websocket" in createRoute.

That's the solution I provided in the issue, but that's still strange behavior ^^

constantins2001 avatar Apr 18 '25 09:04 constantins2001

@constantins2001

The slash at the beginning is needed for the path. It’s an expected behavior.

yusukebe avatar Apr 18 '25 09:04 yusukebe