hono icon indicating copy to clipboard operation
hono copied to clipboard

Configure base path from context header

Open rajsite opened this issue 4 months ago • 1 comments

What is the feature you are proposing?

I'm in a context where I'm creating re-usable Hono apps that can be used on different base path endpoints such as /apps/myapp1 and /apps/myapp2 but the app is not aware of that path until a request comes in. The environment includes the base path for the app as a header on incoming http requests, i.e. X-BASE-PATH: /apps/myapp1. The current basePath method is configured on a Hono app without a context.

I'd like a way to configure the base class for routing using some information from the context. Something like:

const api = new Hono().basePath(c => c.req.header('X-BASE-PATH'))
api.get('/book', (c) => c.text('List Books')) // if `X-BASE-PATH: /apps/myapp1` then GET /apps/myapp1/book

rajsite avatar Oct 24 '25 21:10 rajsite

I'm not sure if this applies to your use case, but it is possible to change the path of the request using getPath option.

import { Hono } from "hono";

const app = new Hono({
  getPath: (request) => {
    const basePath = request.headers.get("X-Base-Path");
    const pathname = new URL(request.url).pathname;
    if (basePath === "/apps/myapp2") {
      return "/apps/myapp1" + pathname;
    }
    return pathname;
  },
});

app.get("/apps/myapp1/books", (c) => {
  return c.text("List Books");
});

export default app;

https://hono.dev/docs/api/routing#routing-with-hostname

ryuapp avatar Oct 25 '25 16:10 ryuapp