middleware
middleware copied to clipboard
Hono env context in @hono/trpc-server createContext does not have type bindings
Using the example from the trpc server middleware for hono docs, in the createContext example the env is typed as Context<any, any, {}> is there a way to get the type safe bindings same as when using the hono routes directly so that var1 in the example below is typesafe?
import { trpcServer } from "@hono/trpc-server";
import { initTRPC } from "@trpc/server";
import { Hono } from "hono";
import { z } from "zod";
type Bindings = {
DB: D1Database;
};
type HonoContext = {
env: Bindings;
};
const t = initTRPC.context<HonoContext>().create();
const publicProcedure = t.procedure;
const router = t.router;
const app = new Hono<{ Bindings: Bindings }>();
export const appRouter = router({
usersCount: publicProcedure.query(async ({ input, ctx }) => {
const result = await ctx.env.DB.prepare("SELECT count(*) from user;").all();
return result?.results[0]?.count;
}),
});
app.use(
"/trpc/*",
trpcServer({
router: appRouter,
createContext: (_opts, c) => ({
// c is the hono context
var1: c.env.DB, // This is not typesafe
var2: c.req.header("X-VAR2"),
}),
}),
);
export type AppRouter = typeof appRouter;
May be related but I'm seeing similar issue with @hono/zod-validator where the bindings defined on the app is not present in the hook callback's context parameter passed to the zValidator() function.
In case anyone is looking for a quick fix, you can do this instead:
app.use("/trpc/*", async (c, next) =>
trpcServer({
router: appRouter,
createContext: () => ({
BUCKET: c.env.BUCKET,
}),
})(c, next)
)