Theo's Typesafe CultTTC
Theo's Typesafe Cult3y ago
5 replies
Less

Context on middleware always undefined

I'm trying to use trpc with next-auth using the GoogleProvider. I can sign in just fine, publicProcedures work, but all protectedProcedures will throw UNAUTHORIZED, even though when using the useSession hook on the same component, it returns the correct data.

I can also see the session on prisma studio.

export const createTRPCContext = async (opts: CreateNextContextOptions) => {
  const { req, res } = opts;

  // Get the session from the server using the getServerSession wrapper function
  const session = await getServerAuthSession({ req, res });
  console.log("session createTRPCContext", session); //logs the session just fine

  return createInnerTRPCContext({
    session,
  });
};

...

const enforceUserIsAuthed = t.middleware(({ ctx, next }) => {
  // always throws on the use of protectedProcedure
  if (!ctx.session || !ctx.session.user) {
    throw new TRPCError({
      code: "UNAUTHORIZED",
      cause: JSON.stringify(ctx), // cause is undefined on stacktrace
      message: "You must be logged in to perform this action.",
    });
  }
  return next({
    ctx: {
      // infers the `session` as non-nullable
      session: { ...ctx.session, user: ctx.session.user },
    },
  });
});
Was this page helpful?