My NextAuth session callback fetches the database too often

So.. I have this web app built with nextjs, the auth is done with next-auth (authjs). I have a session callback in which I set a few user properties such as default_team_id, verified, and id. I am facing too many queries. More than 10k queries in a week of development. The session queries the database on every router refresh or navigation.
const authOptions: NextAuthConfig = {
providers: [
Credentials({
name: "Credentials",
credentials: {
email: { label: "Email", type: "email" },
password: { label: "Password", type: "password" }
},
async authorize(credentials): Promise<SessionUser | null | any> {
if (!credentials || !credentials.email || !credentials.password) {
return
}
try {
const user = (
await db.execute("SELECT * FROM user WHERE email = ?;", [
credentials.email,
])
).rows[0]
if (user) {
const matches = await bcrypt.compare(
credentials.password as string,
user.password
)
if (matches) {
return {
id: user.id,
name: user.name,
email: user.email,
image: user.image
}
}
}
} catch (e) {
throw new Error("Error Authorizing")
}
return null
},
}),
],
callbacks: {
async session({ session }) {
if (!session || !session.user) return session
// get user info
const user = (
await db.execute("SELECT * FROM user WHERE email = ?", [
session.user.email
])
).rows[0]
return user ? {
user: {
...session.user,
verified: user.verified === 1,
id: user.id,
default_team_id: user.default_team_id
},
expires: session.expires
} : null
},
},
}
const authOptions: NextAuthConfig = {
providers: [
Credentials({
name: "Credentials",
credentials: {
email: { label: "Email", type: "email" },
password: { label: "Password", type: "password" }
},
async authorize(credentials): Promise<SessionUser | null | any> {
if (!credentials || !credentials.email || !credentials.password) {
return
}
try {
const user = (
await db.execute("SELECT * FROM user WHERE email = ?;", [
credentials.email,
])
).rows[0]
if (user) {
const matches = await bcrypt.compare(
credentials.password as string,
user.password
)
if (matches) {
return {
id: user.id,
name: user.name,
email: user.email,
image: user.image
}
}
}
} catch (e) {
throw new Error("Error Authorizing")
}
return null
},
}),
],
callbacks: {
async session({ session }) {
if (!session || !session.user) return session
// get user info
const user = (
await db.execute("SELECT * FROM user WHERE email = ?", [
session.user.email
])
).rows[0]
return user ? {
user: {
...session.user,
verified: user.verified === 1,
id: user.id,
default_team_id: user.default_team_id
},
expires: session.expires
} : null
},
},
}
I appreciate any help. 🙏
No description
0 Replies
No replies yetBe the first to reply to this messageJoin
Want results from more Discord servers?
Add your server