How would I create a “pre-“ middleware? #2552
-
Beta Was this translation helpful? Give feedback.
Replies: 4 comments 2 replies
-
What runtime would you be running this in? Because it can differ |
Beta Was this translation helpful? Give feedback.
-
Yes you have access to the entire context in your middleware. The types issue you are having is because there is no types set on your context variables you can fix this by adding this // https://hono.dev/api/context#set-get
type Variables = {
message: string
}
const app = new Hono<{ Variables: Variables }>() Or you can add it globally // https://hono.dev/api/context#contextvariablemap
declare module 'hono' {
interface ContextVariableMap {
result: string
}
} |
Beta Was this translation helpful? Give feedback.
-
Hi! Recently, I've been thinking about this matter and started using a simple factory pattern. First, you can write the import { Hono } from 'hono'
type Variables = {
client: Client
}
export const createAppWithDB = () => {
const app = new Hono<{
Variables: Variables
}>()
app.use((c) => {
const client = initClient()
c.set('client', client)
})
return app
} Then, you can use the If we feel this way is good, we can add this simple factory pattern to our documents and advocate it. |
Beta Was this translation helpful? Give feedback.
-
Okay, I solved my own problem here thanks to your tips above 🎉 - thank you! What wasn't clear to me is that when I want to access both Environment Variables and session variables I need to specify that in the Hono instantiation:
I don't think this is entirely evident in either the For instance the following code example is incomplete, isn't it? You'd still need to include https://hono.dev/getting-started/cloudflare-workers#using-variables-in-middleware Perhaps each example should have a vanilla JS and Typescript JS example (or just Typescript since you could always infer the vanilla JS by stripping away the types)? E.g. - vanilla;
Typescript:
Really loving the simplicity of Hono but I think this rough-ish edge took me by surprise. 🙇🏻♂️ |
Beta Was this translation helpful? Give feedback.
Okay, I solved my own problem here thanks to your tips above 🎉 - thank you!
What wasn't clear to me is that when I want to access both Environment Variables and session variables I need to specify that in the Hono instantiation:
I don't think this is entirely evident in either the
var
docs or theenv
docs and I may be wrong here, but I don't think the Typescript aspects this are obvious even if you are a Typescript veteran.For instance the following code example is incomplete, isn't it? You'd s…