How do I control what data goes into .session_data cookie

Hi everyone! I've been integrating Better Auth with Payload CMS and have a question about controlling the data in the .data_session cookie. I've successfully used the customSession plugin to control what user data is returned from getSession:
plugins: [
customSession(async ({ user, session }) => {
// My code to filter user fields
return {
user: fieldsToSign,
session
}
})
]
plugins: [
customSession(async ({ user, session }) => {
// My code to filter user fields
return {
user: fieldsToSign,
session
}
})
]
However, this doesn't seem to affect what gets stored in the .data_session cookie itself. I've added some extra fields to my user object that I don't want to expose if someone base64 decodes the cookie. Is there a way to control specifically what user data gets serialized into the .data_session cookie? Or is this functionality planned for a future release? Thanks in advance!
1 Reply
Livog
LivogOP6d ago
I've written a custom adapter for Payload CMS which works great (as far as I tested), so if I need to I could fix it at that level if possible. Found the solution:
hooks: {
after: createAuthMiddleware(async (ctx) => {
const newSession = ctx.context?.newSession
if (!ctx.context.newSession) return

if (newSession && newSession.user) {
const config = await payloadConfig
const userCollection = config.collections.find((c) => Boolean(c.auth))

if (!userCollection) {
throw new Error('User collection not found')
}

const filteredUser = getFieldsToSign({
collectionConfig: userCollection,
email: newSession.user.email,
// @ts-ignore
user: newSession.user
})

const filteredSessionData = {
...newSession,
user: filteredUser
}
await setCookieCache(ctx, filteredSessionData as any)
}
})
},
hooks: {
after: createAuthMiddleware(async (ctx) => {
const newSession = ctx.context?.newSession
if (!ctx.context.newSession) return

if (newSession && newSession.user) {
const config = await payloadConfig
const userCollection = config.collections.find((c) => Boolean(c.auth))

if (!userCollection) {
throw new Error('User collection not found')
}

const filteredUser = getFieldsToSign({
collectionConfig: userCollection,
email: newSession.user.email,
// @ts-ignore
user: newSession.user
})

const filteredSessionData = {
...newSession,
user: filteredUser
}
await setCookieCache(ctx, filteredSessionData as any)
}
})
},

Did you find this page helpful?