Replies: 1 comment
-
|
Hi @egemrai! I'm Dosu and I'm helping the better-auth team. Calling Instead, use databaseHooks: {
session: {
create: {
before: async (session, ctx) => {
// Query existing sessions for this user
const existingSessions = await ctx.context.adapter.findMany({
model: "session",
where: [{ field: "userId", value: session.userId }]
});
// You can also identify the client via request headers:
const userAgent = ctx?.request?.headers.get("user-agent");
if (existingSessions.length >= MAX_SESSIONS) {
throw new APIError("BAD_REQUEST", {
message: "Session limit reached",
});
}
return { data: session };
}
}
}
}The Even better: Better Auth has a built-in Multi Session plugin designed exactly for this use case — limiting sessions per device: import { multiSession } from "better-auth/plugins"
export const auth = betterAuth({
plugins: [
multiSession({
maximumSessions: 1 // Allow only one session per client
})
]
})This handles the per-client session limiting logic out of the box without needing custom hooks. Would you like more details on configuring the Multi Session plugin for your specific use case? To reply, just mention @dosu. Share context across your team and agents. Try Dosu. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
I want to allow only a single login per client using the same authentication method.
Since Better Auth recommends client-side sign-in, I cannot fully enforce this rule on the server side. Because of that, I’m trying to handle it inside the auth.ts configuration.
In the code below, when I use 'session', I can access the user who is currently signing in and query the database to retrieve all session data. However, these session records are not stored per individual client. So if I set a maximum client limit (for example 5 sessions), it affects all clients globally—even if a specific client hasn’t signed in, it still gets blocked from logging in.
On the other hand, when I use getSession() instead of 'session' and check if 'session_' exists, I get the behavior I want: if there is already an active session on that client, it prevents a new login.
My question is: how appropriate is it to use auth.api.getSession() inside a hook? I have only tested this in a single function and in a development environment so far. I’m wondering if this approach could cause issues in other functions or in production.
Beta Was this translation helpful? Give feedback.
All reactions