NomadN
tRPC11mo ago
35 replies
Nomad

Weird data type when extending context in fetch adapter

Environment:
* pnpm
* Vite react SPA
* Node v22.11.0
* tRPC server and client version: 11.0.0-rc.828
* Using tRPC with tanstack query (and the new integration approach)

I realise that "weird" is a really bad descriptor, but I honestly don't know what else to call it.

I'm using the fetch adapter with CF workers and needed cloudflare's env in my context, I added this like such:
// context.ts
import { FetchCreateContextFnOptions } from "@trpc/server/adapters/fetch";

export const createContext = async ({
  req,
  resHeaders,
  env,
}: FetchCreateContextFnOptions & { env: Env }) => {
  return { req, resHeaders, env };
};

export type Context = Awaited<ReturnType<typeof createContext>>;

// workers index
import {
  FetchCreateContextFnOptions,
  fetchRequestHandler,
} from "@trpc/server/adapters/fetch";
import { createContext } from "./context";
import { appRouter } from "./router";

export default {
  fetch(request, env) {
    const url = new URL(request.url);

    if (url.pathname.startsWith("/api")) {
      return fetchRequestHandler({
        endpoint: "/api",
        req: request,
        router: appRouter,
        // add env to the context along with defaults
        createContext: (opts: FetchCreateContextFnOptions) =>
          createContext({ ...opts, env }),
      });
    }

    return env.ASSETS.fetch(request);
  },
} satisfies ExportedHandler<Env>;


Now this works wonders, I get access to the cloudflare env in my procedures via context and can use KV bindings from there, very nice! Unfortunately the type from the client is very odd, specifically it considers the data from my query to be of type: (() => never) | undefined

As in the following:
const query = useQuery(trpc.kvQuery.queryOptions())
query.data
//      ^ (() => never) | undefined


Now, this purely from a type pespective, the actual value is there during runtime and works fine. But obviously as soon as the code gets type checked it throws a fit because it thinks I'm trying ot access val on that type.

Any help is greatly appreciated!
Solution
Well, in case anyone sees this I managed to figure it out. When starting a new CF project with the react framework template it creates an additional tsconfig (to the three existing ones from vite). This config (tsconfig.worker.json) references the following types:
"types": [
  "@cloudflare/workers-types/2023-07-01",
  "./worker-configuration.d.ts",
  "vite/client"
]

and the first two also need to be referenced in tsconfig.app.json for the files in the src directory to pick up on it. Adding those two removes the issue and allows the types to be inferred correctly 😄
Was this page helpful?