Skip to content

Commit

Permalink
try trpc sentry middleware
Browse files Browse the repository at this point in the history
  • Loading branch information
d-ivashchuk committed Mar 27, 2024
1 parent 68b46a3 commit ae0e9bc
Showing 1 changed file with 22 additions and 9 deletions.
31 changes: 22 additions & 9 deletions src/server/api/trpc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import { initTRPC, TRPCError } from "@trpc/server";
import superjson from "superjson";
import { ZodError } from "zod";
import * as Sentry from "@sentry/nextjs";

import { getServerAuthSession } from "~/server/auth";
import { db } from "~/server/db";
Expand Down Expand Up @@ -87,15 +88,8 @@ export const createTRPCRouter = t.router;
*/
export const publicProcedure = t.procedure;

/**
* Protected (authenticated) procedure
*
* If you want a query or mutation to ONLY be accessible to logged in users, use this. It verifies
* the session is valid and guarantees `ctx.session.user` is not null.
*
* @see https://trpc.io/docs/procedures
*/
export const protectedProcedure = t.procedure.use(({ ctx, next }) => {
/** Reusable middleware that enforces users are logged in before running the procedure. */
const enforceUserIsAuthed = t.middleware(({ ctx, next }) => {
if (!ctx.session || !ctx.session.user) {
throw new TRPCError({ code: "UNAUTHORIZED" });
}
Expand All @@ -106,3 +100,22 @@ export const protectedProcedure = t.procedure.use(({ ctx, next }) => {
},
});
});

const sentryMiddleware = t.middleware(
//@ts-expect-error this does not break even though types are mismatched
Sentry.Handlers.trpcMiddleware({
attachRpcInput: true,
}),
);

const finalMiddleware = sentryMiddleware.unstable_pipe(enforceUserIsAuthed);

/**
* Protected (authenticated) procedure
*
* If you want a query or mutation to ONLY be accessible to logged in users, use this. It verifies
* the session is valid and guarantees `ctx.session.user` is not null.
*
* @see https://trpc.io/docs/procedures
*/
export const protectedProcedure = t.procedure.use(finalMiddleware);

0 comments on commit ae0e9bc

Please sign in to comment.