venego
venego13mo ago

Context is not fully globally accessed? [ probably newbie question ]

I create a context in the based procedure, but It's undefined in the procedure based on it. Also the opts.ctx doesn't exist before I create it, although I've used .context() upon initializing trpc, but that's no big deal. NVM I should've defined it upon server creation. Context defined by a procedure cannot be seen by another procedure?? how do I get around that?
const trpc = initTRPC.context<{
userSession: { id: string, authenticated: boolean }
}>().create();

const baseProcedure = trpc.procedure.use((opts) => {
opts.ctx = {
userSession: {
id: 'dummy',
authenticated: false
}
};

return opts.next()
});
const protectedProcedure = baseProcedure.use((opts) => {
// ctx is undefined
if (!opts.ctx.userSession.authenticated) {
throw new TRPCError(
{ code: 'UNAUTHORIZED', cause: 'because!' }
);
}
return opts.next();
});
const trpc = initTRPC.context<{
userSession: { id: string, authenticated: boolean }
}>().create();

const baseProcedure = trpc.procedure.use((opts) => {
opts.ctx = {
userSession: {
id: 'dummy',
authenticated: false
}
};

return opts.next()
});
const protectedProcedure = baseProcedure.use((opts) => {
// ctx is undefined
if (!opts.ctx.userSession.authenticated) {
throw new TRPCError(
{ code: 'UNAUTHORIZED', cause: 'because!' }
);
}
return opts.next();
});
4 Replies
Lucas
Lucas13mo ago
you should define the ctx variable by passing it as an argument to the opts.next() function you are returning like this:
const baseProcedure = trpc.procedure.use((opts) => {
return opts.next({
ctx: {
userSession: {
id: 'dummy',
authenticated: false
}
}
})
});
const baseProcedure = trpc.procedure.use((opts) => {
return opts.next({
ctx: {
userSession: {
id: 'dummy',
authenticated: false
}
}
})
});
otherwise even though you are doing opts.ctx = ..., that does nothing
Lucas
Lucas13mo ago
You can see more about how context extension works here -> https://trpc.io/docs/server/middlewares#context-extension
Middlewares | tRPC
You are able to add middleware(s) to a procedure with the t.procedure.use() method. The middleware(s) will wrap the invocation of the procedure and must pass through its return value.
venego
venego13mo ago
Thanks @Lucas Thevenet, that saved my day, I guess reading the docs starting from the top is not that practical before I finish reading it.
Lucas
Lucas13mo ago
Glad I could be of help! 👍