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
https://www.better-auth.com/docs/concepts/session-management#customizing-session-response
This would't work?
Session Management | Better Auth
Better Auth session management.
You can look into the customSession funtion.
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.
When you use
session()->put()
in Laravel, it will also store it in the database or redis, depending on which store you are usingis there a workaround to cache the customsession data? (im using sveltekit btw)
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
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.
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?