context question

Why are the context examples only showing opinionated examples with next/react auth ? Also i find it very confusing that it is not mentioned in the docs what kind of arguments the context function is called with.
N
Nick383d ago
Feel free to write up your thoughts here: https://github.com/trpc/trpc/discussions/3963
GitHub
RFC: 2023 Upgraded Documentation · trpc trpc · Discussion #3963
Preface Currently the docs have a lot of really well written content, and some which needs a little love. The biggest problem is they're often written from the perspective of APIs, rather than ...
N
Nick383d ago
We're actively working on improvements so this is very appreciated 🙂
H
haquinn383d ago
That is great and all, but do you think you can help me understand what is the proper way to type a context function? What should be the type of an object that is able to be passed to a procedure's use method ?
H
haquinn383d ago
N
Nick383d ago
t.middleware()
H
haquinn383d ago
So wait, i'm a bit confused What exactly is the difference between context and middleware?
N
Nick383d ago
Context is a place to put data and functionality that procedures need to use Middleware is a place to put behaviour which gets called before a procedure is called, and can also modify the Context
H
haquinn383d ago
So if i'm understanding this correctly, context -> middleware -> procedure
N
Nick383d ago
It might be helpful to look through the example projects as they have implementations of this Context is available to both middlewares and procedures
H
haquinn383d ago
Middleware can be specific to a procedure, but a context is router wide, is that correct?
N
Nick383d ago
So createContext will be API-wide, yes Middlewares are attached to a procedure yes Middlewares which modify context only modify the context for procedures on that base procedure
H
haquinn383d ago
I see. Last question is How do i attach a context to a router? Or do i need to attach it to the createHttpServer instead? Also another valid question that is derivative of my previous one would be: Is it possible to attach contexts to routers that are later on going to be merged together, which would result in some of the api routes not having context ?
H
haquinn383d ago
Sidenote:
H
haquinn383d ago
This image seems to suggest that contexts are api wide, regardless if i want to merge in routers that have no use for these contexts with others that actually do
N
Nick383d ago
That’s where the logic should be passed, yes. Typescript will tell you what the args and result are
H
haquinn383d ago
Is there a type for the createContext object, so i can define it elsewhere in my code and not inline of the createHttpServer?
N
Nick383d ago
All routers come from t.router which already has the Context type associated. createContext then needs writing once Hover over it in your editor and you’ll see the type
H
haquinn383d ago
H
haquinn383d ago
Ughm... i think i'm not explaining what i want clearly enough.
const createContext: TypeHere = () => {
return {};
};

export const startTRPC = () => {
createHTTPServer({
middleware: cors(),
router: appRouter,
createContext
}).listen(config.PORT);
};
const createContext: TypeHere = () => {
return {};
};

export const startTRPC = () => {
createHTTPServer({
middleware: cors(),
router: appRouter,
createContext
}).listen(config.PORT);
};
the TypeHere is what i am looking for.
N
Nick383d ago
You can either dig into that type and understand what tRPC is doing, or you can write out the bits you actually need into a factory createContext: (req, res) => makeMyContext(req.etc)
H
haquinn383d ago
Isn't there an already exported type for the createContext option of the createHTTPServer?
N
Nick383d ago
Feel free to open an issue about it, it's not a problem I've ever needed to solve The docs I think do some of this, but not using a dedicated type
H
haquinn383d ago
But i think you get where i'm coming from, right?
N
Nick383d ago
Context | tRPC
Your context holds data that all of your tRPC procedures will have access to, and is a great place to put things like database connections or authentication information.
N
Nick383d ago
I know you've seen this, but here the docs do have a separated function I appreciate it's for Next though, we should change that
H
haquinn383d ago
Well The example code section did not show how the createContext was attached to the TRPC instance And like i mentioned at the start, it was very confusing to see that the createContext function wasn't used anywhere but in the exported Context infer type, and the fact that the opts parameter was defined as CreateNextContextOptions Anyway, i think i got the info i needed. Regardless of the little pains here and there, i would say that i'm just not used to the library yet. I really do like tRPC and i feel like this is what will power the future of API interfaces. +1 star Thanks for the kind help ❤️
N
Nick383d ago
Please do share your thoughts on the RFC, we need this kind of feedback and I agree as I got tripped up in this area too 🙂
H
haquinn383d ago
By the way, i found this to be a solution to my problem with the type inference of the context function
import type { IncomingMessage, ServerResponse } from 'node:http';
import type { inferAsyncReturnType } from '@trpc/server';
import type { NodeHTTPCreateContextFnOptions } from '@trpc/server/adapters/node-http';


export const createContext = async ({
req,
res
}: NodeHTTPCreateContextFnOptions<IncomingMessage, ServerResponse>) => {
// Stuff...

return {};
};

export type Context = inferAsyncReturnType<typeof createContext>;
import type { IncomingMessage, ServerResponse } from 'node:http';
import type { inferAsyncReturnType } from '@trpc/server';
import type { NodeHTTPCreateContextFnOptions } from '@trpc/server/adapters/node-http';


export const createContext = async ({
req,
res
}: NodeHTTPCreateContextFnOptions<IncomingMessage, ServerResponse>) => {
// Stuff...

return {};
};

export type Context = inferAsyncReturnType<typeof createContext>;
More Posts
async middlewareis it possible to define an async middleware? I want to do something like this but it throws errors The type of the second route of the nested route is neverhttps://github.com/StringKe/nx-mulit-trpc-type-error/blob/main/apps/app1/src/pages/index.tsx#L12errorFormatter ignored when using appRouter.createCallerMy errorFormatter works correctly in the actual application using an adapter, e.g. ``` trpcExpress.Is there a way to define the Websocket protocol when using wsLink()I am attempting to use tRPC with Azure's Pub/Sub Websockets service it appears to require custom proThe inferred type of this node exceeds the maximum length the compiler will serialize.Hey, there I am running into this error when I have more than 12 routers in the mergeRouters functioQuickstart not workingHello there, There is a type error in the quickstart example if i'm not mistaken. I pretty much coUse TRPC function inside of a TRPC functionHi all! We have a trpc query called getProduct. I want to use this getProduct query inside of anotheSupabase with trpcWhen trying to configure trpc with supabase, getting this kind of error in the console `tRPC failed Using tRPC for uploading audio filesI want to create an api router in tRPC but am not sure if the following code is doable with tRPC. IfEnigmatic INTERNAL SERVER ERRORIm having a problem finding out about what is causing the INTERNAL SERVER ERROR from tRPC in my prodcreateProxySSGHelpers type errorHi all! Anyone know how to use createProxySSGHelpers with appropriate createContext typing?Can I force metadata with the createCaller?I have custom metadata which I check within the middleware. Im trying to write tests for this. CurreVitest error testHow can I test for specific TRPCError code with vitest? I managed to get the message but can't figurUsing generics duplicates the types instead of referring to the existing typesHi! I'm creating a backend API using TRPC, where I'm encountering a slight problem. TL;DR; when defSet custom header for fetchRequestHandlerIs this possible? currently getting cors issue. Trying to use nextjs's edge function with trpc.. ``How to enforce usequery as NonNullableI have a custom hook with infinite query. I check for undefined at the app first render and then it How to call useQuery with params inside JSXHow can i achieve this? Thanks ``` export function MemberQueryList({ list }: Props) { function Sharing EnumOn the backend: I have colocated files with types and procedures (index.ts - procedures, schemas.ts Meta - unable to create default metaTrying to follow https://trpc.io/docs/server/metadata#default-meta-chaining-and-shallow-merging I setrpc/react-query batchingHi. How do you deal with batching? If I don't put any maxURLLength then I get an error 404 since it