tRPC Context object empty

Hey guys, I wanted to try to implement context using tRPC. I followed the docs line by line but I keep getting an empty object when I return the ctx in my procedure. Here is my code: context.ts
export async function createContext(opts: CreateNextContextOptions) {

return {
token: "secret-hash",
};
}

export type Context = inferAsyncReturnType<typeof createContext>;
export async function createContext(opts: CreateNextContextOptions) {

return {
token: "secret-hash",
};
}

export type Context = inferAsyncReturnType<typeof createContext>;
` trpc.ts
const t = initTRPC.context<Context>().create();

const isAuthed = t.middleware(async ({ next, ctx }) => {
if (!ctx) {
throw new TRPCError({
code: "UNAUTHORIZED",
});
}
return next({
ctx: {
session: ctx,
},
});
});
export const protectedProcedure = t.procedure.use(isAuthed);
const t = initTRPC.context<Context>().create();

const isAuthed = t.middleware(async ({ next, ctx }) => {
if (!ctx) {
throw new TRPCError({
code: "UNAUTHORIZED",
});
}
return next({
ctx: {
session: ctx,
},
});
});
export const protectedProcedure = t.procedure.use(isAuthed);
router.ts
print: protectedProcedure
.input(
z.object({
name: z.string(),
})
)
.mutation(async (opts) => {
return opts.ctx; // {}
}),
print: protectedProcedure
.input(
z.object({
name: z.string(),
})
)
.mutation(async (opts) => {
return opts.ctx; // {}
}),
I'd appreciate any help I could get
1 Reply
sumatoken
sumatokenOP16mo ago
I fixed. I knew the function wasn't actually called anywhere so typescript gave me a hint when I tried to build the project. Here is what I had to do in /api/trpc/[trpc].ts:
export default trpcNext.createNextApiHandler({
router: appRouter,
createContext: createContext, // calling the ctx function
});
export default trpcNext.createNextApiHandler({
router: appRouter,
createContext: createContext, // calling the ctx function
});
Want results from more Discord servers?
Add your server