venegoV
tRPC3y ago
6 replies
venego

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();
});
Was this page helpful?