ctx.user.session.email possibly null | undefined

get: protectedProcedure
.input(z.object({ id: z.string() }))
.query(async ({ ctx, input }) => {
const texts = await ctx.prisma.text.findMany({
where: {
userEmail: ctx.session.user.email,
}
})
}),
get: protectedProcedure
.input(z.object({ id: z.string() }))
.query(async ({ ctx, input }) => {
const texts = await ctx.prisma.text.findMany({
where: {
userEmail: ctx.session.user.email,
}
})
}),
It's a protected procedure and the only sign-in methods I plan to have is Google and standard Email/Password where in both cases a user will always have an email so how can I convince typescript that this is typesafe? Other than something like String(ctx.session.user.email) or ctx.session.user.email ?? ""
7 Replies
stunaz
stunaz15mo ago
just add an exclamation pointctx.session.user.email!
Unknown User
Unknown User15mo ago
Message Not Public
Sign In & Join Server To View
mattddean
mattddean15mo ago
I think if you make email the email column non-nullable in your database, then regenerate the prisma client, it should be inferred as non-optional
outis99
outis9915mo ago
Well it works but eslint throws a warning for it so I removed the warning in my eslint That's the weird thing it is non-nullable in my schema but whatever the other solution works
Yiannis
Yiannis15mo ago
Is the middleware checking the whole session or just the user id?
jingleberry
jingleberry15mo ago
It depends on where the type is coming from. IIRC you can override the Session type provided by NextAuth (which I assume you're using) So take a look at if anything is attempting to add email to the Session object and see if you can make it nonnull. Alternatively ctx.session.user.email ?? undefined works too because prisma happily accepts undefined (if you read that error message closely)
stunaz
stunaz15mo ago
i do have the exact same problem. especially using session?.user.id