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 },
},
});
});
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 },
},
});
});
3 Replies
Kseikyo
Kseikyo15mo ago
If I comment the check for a session, I can confirm it is passed down correctly to my mutation which uses the protectedProcedure. Also, changing the check for if (typeof ctx === "undefined") { will throw the UNAUTHORIZED error.
caducodes
caducodes14mo ago
Hey, I'm having the same issue on my project and it was working fine two weeks ago. The last significant change that I've made was to update Prisma from 5.1.1 to 5.3.1. I've downgrade it but it was not related. I've tried to change the provider from Google to Github but still the same error. Did you manage to find out a solution?
Kseikyo
Kseikyo14mo ago
Not really, I ended up not using the middleware and checking for the session data with the public procedure.
Want results from more Discord servers?
Add your server