tRPCttRPC
Powered by
venegoV
tRPC•3y 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
opts.ctx
doesn't exist before I create it, although I've used
.context()
.context()
upon initializing
trpc
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();
});
tRPCJoin
Move Fast & Break Nothing. End-to-end typesafe APIs made easy.
5,015Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

context question
VilianVVilian / ❓-help
3y ago
Context is not being passed correctly
CodexCCodex / ❓-help
2y ago
is context cached?
JavascriptMickJJavascriptMick / ❓-help
3y ago