Context is not available, context storage middleware

const app = new Hono<Binds>()

app.use(contextStorage());

app.use(async (c, next) => {
c.set("dev", c.env.ENV === "DEV");
await next();
});

//app.use('*', extractAuthedUserMiddleare);

const routes = app
.route("/template", new TemplatesController().routes())

export default app;
export type AppType = typeof routes;

export const client = hc<AppType>('/');
export type ClientType = typeof client;
const app = new Hono<Binds>()

app.use(contextStorage());

app.use(async (c, next) => {
c.set("dev", c.env.ENV === "DEV");
await next();
});

//app.use('*', extractAuthedUserMiddleare);

const routes = app
.route("/template", new TemplatesController().routes())

export default app;
export type AppType = typeof routes;

export const client = hc<AppType>('/');
export type ClientType = typeof client;
6 Replies
SPS | Shootmail
SPS | ShootmailOP2mo ago
In TemplatesController, I call TemplatesService that initializes db in the constructor.
ambergristle
ambergristle4w ago
hi @SPS | Shootmail! to inform the hono app/context type about variables you've set in middleware, you can either add them to the Variables property of your app type, or declare a ContextVariableMap
ambergristle
ambergristle4w ago
Context - Hono
Web framework built on Web Standards for Cloudflare Workers, Fastly Compute, Deno, Bun, Vercel, Node.js, and others. Fast, but not only fast.
ambergristle
ambergristle4w ago
using either of these approaches will categorically type the context though, so if you need to make it clear that the value is guaranteed to be set, but only after a given middleware has been executed, you could manually type handlers
SPS | Shootmail
SPS | ShootmailOP4w ago
Thanks for replying. Yes i use context variable map. My concern was how to init the db using env vars outside of the route methods. I misunderstood the context storage. I thought, the context storage will be available outside the route chain but that's not the case. So i am setting db in variables in a middleware and accessing it in the controllers. But this was, if i implement the MVC architecture, all the methods of the model layer are dependent on the variable that contains the db. Probably i can use a dependency injection framework like tsyringe but that looks like overkill to me.
ambergristle
ambergristle4w ago
gotcha. what runtime are you deploying on?

Did you find this page helpful?