appRouter.createCaller(await createContext())
appRouter.createCaller
createContext
createTRPCContext
// /src/trpc/trpc.tsimport { initTRPC, TRPCError } from '@trpc/server';import superjson from 'superjson';import { ZodError } from 'zod';import { getServerAuthSession } from '~/auth/auth';export const createTRPCContext = async () => { console.log('Context'); return await getServerAuthSession();};const t = initTRPC.context<typeof createTRPCContext>().create({ transformer: superjson, errorFormatter({ shape, error }) { return { ...shape, data: { ...shape.data, zodError: error.cause instanceof ZodError ? error.cause.flatten() : null, }, }; },});export const createTRPCRouter = t.router;const enforceUserIsAuthed = t.middleware(({ ctx, next }) => { console.log(ctx); if (!ctx.session?.user) { throw new TRPCError({ code: 'UNAUTHORIZED' }); } return next({ ctx: { session: { ...ctx.session, user: ctx.session.user }, }, });});export const publicProcedure = t.procedure;export const protectedProcedure = t.procedure.use(enforceUserIsAuthed);
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>;