When using routing i have to define the binding for each of the routes when i instance Hono? #2257
Replies: 3 comments
-
You don't need it. If you define the Bindings or Variables, they are used all route as the same. Creating and using instances is for routing purposes; only one instance actually handles the request. |
Beta Was this translation helpful? Give feedback.
-
@yusukebe it's true that the bindings are used in all routes. However(might be limitation of typescript), the binding types are not correctly inferred. You can find the type mismatch in below example: First define a binding /CustomBinding.ts
export type HonoBindings = {
SOME_ENVIRONMENT_VARIABLE: string;
}; Use above binding for the main app /app.ts
const app = new Hono<{ Bindings: HonoBindings }>(); In a separate route, the binding of SOME_ENVIRONMENT_VARIABLE is missing const childRouter = new Hono()
childRouter.get("/", c => {
console.log(c.env.SOME_ENVIRONMENT_VARIABLE) //This will give type error: 'c.env' is of type 'unknown'
return "Hello World"
}) |
Beta Was this translation helpful? Give feedback.
-
Please add the type definition to the const childRouter = new Hono<{ Bindings: HonoBindings }>() |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Im checking your guide https://hono.dev/guides/best-practices#building-a-larger-application
I wan to use routing because i want to create one api for all my liteweight requests of catalogs data, my question its if i need to add the bindings in each of the app = new Hono() of each route or is there any way to inherit context/bindings to each route from main router?
and other thing if i create an env on the main router can i use it on child routes?
Beta Was this translation helpful? Give feedback.
All reactions