Include relationship in session.user object?

Hey there 👋 I'm looking to perform a check in a Next.js layout that sees how many related posts records exist for a user before redirecting or granting access. Now, I could just denormalize the count of these records into a column on the user record, but maybe there is another way.
import { customSession } from "better-auth/plugins";

export const auth = betterAuth({
plugins: [
customSession(async ({ user, session }) => {
const roles = findUserRoles(session.session.userId);
return {
roles,
user: {
...user,
newField: "newField",
},
session
};
}),
],
});
import { customSession } from "better-auth/plugins";

export const auth = betterAuth({
plugins: [
customSession(async ({ user, session }) => {
const roles = findUserRoles(session.session.userId);
return {
roles,
user: {
...user,
newField: "newField",
},
session
};
}),
],
});
I could do this in two requests by fetching this relationship within customSession, but since this check occurs in the root of my application, doubling requests is not an option. What is recommended when a relationship is needed alongside the normal session data?
5 Replies
Alex Booker
Alex Booker3mo ago
Ah, does customSession run after Better Auth hits the database? Your concern is that if you add your query in there, the internal query for the user becomes redundant and inefficient?
Json 🧈
Json 🧈OP3mo ago
Yes, this is right. I think Better-Auth could allow for specifying relations on the user record so we can get more useful info with a single request. Maybe once/if fumadb releases. https://x.com/fuma_nama/status/1931602536537973228
Fuma Nama (@fuma_nama)
After seeing how better-auth deal with databases and having to deal with it in my own libraries I'm thinking to make a fumadb package that's dedicated for libraries to interact with your own database, thoughts?
X
Alex Booker
Alex Booker3mo ago
You could consider session caching and then invalidate the cache when a post record for the user is created
Json 🧈
Json 🧈OP3mo ago
Interesting idea. Thanks 👍
chris
chris3mo ago
how do you invalidate the cache?

Did you find this page helpful?