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
Nick410d 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
Nick410d ago
We're actively working on improvements so this is very appreciated 🙂
V
Vilian410d 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 ?
V
Vilian410d ago
N
Nick410d ago
t.middleware()
V
Vilian410d ago
So wait, i'm a bit confused What exactly is the difference between context and middleware?
N
Nick410d 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
V
Vilian410d ago
So if i'm understanding this correctly, context -> middleware -> procedure
N
Nick410d 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
V
Vilian410d ago
Middleware can be specific to a procedure, but a context is router wide, is that correct?
N
Nick410d 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
V
Vilian410d 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 ?
V
Vilian410d ago
Sidenote:
V
Vilian410d 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
Nick410d ago
That’s where the logic should be passed, yes. Typescript will tell you what the args and result are
V
Vilian410d 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
Nick410d 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
V
Vilian410d ago
V
Vilian410d 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
Nick410d 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)
V
Vilian410d ago
Isn't there an already exported type for the createContext option of the createHTTPServer?
N
Nick410d 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
V
Vilian410d ago
But i think you get where i'm coming from, right?
N
Nick410d 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
Nick410d 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
V
Vilian410d 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
Nick410d 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 🙂
V
Vilian410d 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