How to store custom data in session?

Is there a way to store custom data in session that is not directly related to the core Better Auth logic like storing user preferences without persisting them into the database? Similar to Laravel's session()->put('foo', 'bar'), if that reference makes it clearer what I'd like to achieve.
7 Replies
FalconiZzare
FalconiZzare2mo ago
You can look into the customSession funtion.
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
};
}),
],
});
https://www.better-auth.com/docs/concepts/session-management#customizing-session-response This will not necessarily need storing the newField to the database. However customSession function doesn't support caching.
Session Management | Better Auth
Better Auth session management.
eoshorizon_
eoshorizon_2mo ago
When you use session()->put() in Laravel, it will also store it in the database or redis, depending on which store you are using
boosh
boosh2mo ago
is there a workaround to cache the customsession data? (im using sveltekit btw)
Netrifier
Netrifier2mo ago
I don't think this is possible because cookies have a maximum amount of data that they can store(4kb) and caching custom data can sometimes make the cookie too large
Allan
AllanOP2mo ago
Thx for the feedback. I hoped to store session data in Redis or other KV-store that does not need persistence. But when I think about it now, then it would also make sense to have additional column "data" as JSON field in sessions table. Is there a way to extend sessions table and ability to store data there, similarly to Laravel's session()->put()? Or do I need to handle these inserting to database manually and enriching sessions response using https://www.better-auth.com/docs/concepts/session-management#customizing-session-response?
Session Management | Better Auth
Better Auth session management.
Allan
AllanOP2mo ago
I was able to add "data" field to session, but I haven't yet found a way how to edit that during the session, for example when user edits the preferred language. Does Better Auth expose session editing methods?
session: {
additionalFields: {
data: {
type: "string",
required: false,
defaultValue: "{}",
},
},
},
session: {
additionalFields: {
data: {
type: "string",
required: false,
defaultValue: "{}",
},
},
},

Did you find this page helpful?