hono icon indicating copy to clipboard operation
hono copied to clipboard

Routing support for wildcard parameters

Open ruimaciel opened this issue 7 months ago • 5 comments

What is the feature you are proposing?

Currently Hono's routing provides support for a number of parameters. However, there is no first-class support for usecases such as:

  1. a request is routed by prefix,
  2. hono sets a parameter by stripping the prefix from the request path,
  3. the route handler passes the parameter (i.e., request's path with the prefix stripped) to a subrequest and/or origin server.

This type of usecase happens frequently when using Cloudflare Workers. Currently, the best way to address this usecase is to manually put together the parameter, similar to:

app.get('/someprefix/*', async (c, next) => {
  const path = getPathFromURL(c.req.url)
  const parameter = path.replace(/^\/someprefix\//, ''))
  // do things
})

This works ok, but it leads to a subpar developer experience. I suppose that this could be done with regex parameters too.

Ideally, Hono would do this for us. It would be great if Hono provided support for wildcard parameters, where anything matching a wildcard would be conveniently provided through a parameter, similar to:

app.get('/someprefix/:parameter*', async (c, next) => {
  // do things
})

This topic was briefly touched in #591 , but so far without a response.

Would it be possible to implement wildcard parameters?

ruimaciel avatar May 23 '25 14:05 ruimaciel

I think you can implement wildcard parameter by regexp patameter

Image

app.get('/posts/:path{.+}', async (c) => {
 return c.text(c.req.param("path"))
})

EdamAme-x avatar May 23 '25 17:05 EdamAme-x

One thing to add is that there is a way to implement this type of wildcard routing without compromising performance. @yusukebe What do you think?

app.get('/someprefix/:parameter*', async (c, next) => {
  // do things
})

EdamAme-x avatar May 23 '25 17:05 EdamAme-x

Image https://www.typescriptlang.org/play/?#code/MYewdgzgLgBKYDcCmAnKB1AlgGwCbAEMVcAFIggWwBUQAlJAcwFEAPABzJUpgF4YAKNkSgAuGNBSYwDAJS8AfDADeAKBjqYKJFACuKMDCFoAdFrbYCwJPwD0-EcYDUMgDoAqACQ2ANDABEHgCMSk4Avn4yKqEqKvAQINhIxtggDPzwyGhYeITEnJQ09Mzs+RT8fiKYuBGRcQlJKWkZqBg4+ESk5NR0jKwcXeUiQlAAFm41seDxicmp6eCZrTkdpYW9JQN+0ARQmMA1QA

EdamAme-x avatar May 23 '25 17:05 EdamAme-x

Hi @ruimaciel

As @EdamAme-x said, it can support a wildcard parameter with regexp like the following:

app.get('/posts/:path{.+}', async (c) => {
 return c.text(c.req.param("path"))
})

yusukebe avatar May 27 '25 10:05 yusukebe

@EdamAme-x

Indeed, supporting /:parameter* will decrease the user's confusion. But, hmm. In my opinion, it's okay whether we do it or not.

yusukebe avatar May 27 '25 10:05 yusukebe

Regarding this issue, this can be done with a regexp like /posts/:path{.+}. So it does not need to remain open. Closing.

yusukebe avatar Jun 20 '25 23:06 yusukebe