middleware icon indicating copy to clipboard operation
middleware copied to clipboard

Hono env context in @hono/trpc-server createContext does not have type bindings

Open tsatsujnr139 opened this issue 1 year ago • 2 comments

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?

image

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;

tsatsujnr139 avatar Aug 16 '24 10:08 tsatsujnr139

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.

limzykenneth avatar Aug 24 '24 18:08 limzykenneth

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)
  )

abielzulio avatar Dec 03 '24 09:12 abielzulio