// src/server/api/trpc.ts
const createInnerTRPCContext = ({ auth }: AuthContext) => {
return {
auth,
prisma,
};
};
export const createTRPCContext = async ({
req,
res,
}: CreateNextContextOptions) => {
return createInnerTRPCContext({
auth: getAuth(req),
});
};
import { initTRPC, TRPCError } from "@trpc/server";
import superjson from "superjson";
import { ZodError } from "zod";
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;
export const publicProcedure = t.procedure;
const enforceUserIsAuthed = t.middleware(({ ctx, next }) => {
if (!ctx.auth.userId) {
throw new TRPCError({ code: "UNAUTHORIZED" });
}
return next({
ctx: {
// infers the `session` as non-nullable
auth: ctx.auth,
},
});
});
export const protectedProcedure = t.procedure.use(enforceUserIsAuthed);
// src/server/api/trpc.ts
const createInnerTRPCContext = ({ auth }: AuthContext) => {
return {
auth,
prisma,
};
};
export const createTRPCContext = async ({
req,
res,
}: CreateNextContextOptions) => {
return createInnerTRPCContext({
auth: getAuth(req),
});
};
import { initTRPC, TRPCError } from "@trpc/server";
import superjson from "superjson";
import { ZodError } from "zod";
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;
export const publicProcedure = t.procedure;
const enforceUserIsAuthed = t.middleware(({ ctx, next }) => {
if (!ctx.auth.userId) {
throw new TRPCError({ code: "UNAUTHORIZED" });
}
return next({
ctx: {
// infers the `session` as non-nullable
auth: ctx.auth,
},
});
});
export const protectedProcedure = t.procedure.use(enforceUserIsAuthed);