Database Hooks `before.create` Has Undefined Context

How is the context populated in the database before create hook? Taken from example here https://www.better-auth.com/docs/concepts/database#1-before-hook Code snippet below:
databaseHooks: {
session: {
create: {
before: async (session, context) => {
// context is always undefined here

return {
data: session
}
},
}
}
},
databaseHooks: {
session: {
create: {
before: async (session, context) => {
// context is always undefined here

return {
data: session
}
},
}
}
},
Database | Better Auth
Learn how to use a database with Better Auth.
5 Replies
Ping
Ping3w ago
It depends on how a given session was created, in some cases there can be no ctx.
Bruh
BruhOP3w ago
Yeah I see the parameter type as GenericEndpointContext | undefined. I'm trying to get the context during signup with oauth in the /callback/:id path.
Ping
Ping3w ago
I see, I'll look into the source code and see if I can add ctx.
Bruh
BruhOP3w ago
Sounds good, thank you.
umang
umang2w ago
chiming in here, as I have a similar issue: i'm trying to access the context object and use internalAdapter.deleteSessions to manually revoke other session. But context is always coming back as null. code for reference:
databaseHooks: {
session: {
create: {
after: async( session, context ) => {
const allSessions = await context?.context.internalAdapter.listSessions(session.userId);
const sessionIdsToDelete = allSessions ? allSessions.map(s => s.id).filter(id => id !== session.id) : undefined;
if( sessionIdsToDelete ) {
await context
context?.context.internalAdapter.deleteSessions(sessionIdsToDelete);
}
}
}
}
},
databaseHooks: {
session: {
create: {
after: async( session, context ) => {
const allSessions = await context?.context.internalAdapter.listSessions(session.userId);
const sessionIdsToDelete = allSessions ? allSessions.map(s => s.id).filter(id => id !== session.id) : undefined;
if( sessionIdsToDelete ) {
await context
context?.context.internalAdapter.deleteSessions(sessionIdsToDelete);
}
}
}
}
},

Did you find this page helpful?