How to avoid multiple database calls when populating user info in the session callback #9321
Unanswered
ChrisB1123
asked this question in
Help
Replies: 2 comments
-
Hi @ChrisB1123 did you ever find a solution for this? |
Beta Was this translation helpful? Give feedback.
0 replies
-
Since you are using Prisma, you should use the prisma adapter to handle this for you (docs), it uses next-auth v5 (beta); and make sure to extend the session with the user id from the jwt (docs). So the auth config would look something like this: import NextAuth from "next-auth"
import { PrismaAdapter } from "@auth/prisma-adapter"
import { PrismaClient } from "@prisma/client"
globalThis.prisma ??= new PrismaClient()
export const { handlers, auth } = NextAuth({
adapter: PrismaAdapter(globalThis.prisma),
session: { strategy: "jwt" },
// add the user id to the session
callbacks: {
jwt({ token, user }) {
if (user) { // User is available during sign-in
token.id = user.id
}
return token
},
session({ session, token }) {
session.user.id = token.id
return session
},
},
...
}) If you want to stick to a |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Goal
Populate my session object with a user's ID from my database while using JWT session strategy.
Background
I didn't mind using database sessions, which I guess would solve this issue, but I get this error when doing so:
I don't believe it's possible to turn off Edge Functions here? So I switched to a JWT strategy.
Problem
Since the JWT strategy only populates the session with what you get from the Provider, I need to connect to my database to fetch the userId whenever the session is populated.
I have this set up and working fine, however if I put a console.log in my API route, it's getting called 3 times in production, and more in development. I'd like to just make this call once (or just make the call to the database once, if Prisma can memoise the call in some way)
This is my auth config:
and here is my API route:
Stack
Beta Was this translation helpful? Give feedback.
All reactions