How to have databaseHooks event whenever user logs in?

This is my auth code. My goal is to save the date when user logged in.
import { betterAuth } from "better-auth";
import { MongoClient } from "mongodb";
import { mongodbAdapter } from "better-auth/adapters/mongodb";
import { admin } from "better-auth/plugins"
import Logins from "@/models/Logins";


const client = new MongoClient(process.env.MONGO_URI || "");
const db = client.db();

export const auth = betterAuth({
database: mongodbAdapter(db),
emailAndPassword: {
enabled: true
},
plugins: [
admin(),
],
user: {
additionalFields: {
purchases: {
type: "string[]",
defaultValue: [],
}
}
},
databaseHooks: {
user: {
update: {
after: async (user, ctx) => {
const id = user.id
const ip = ctx?.request?.headers.get("x-forwarded-for") || ctx?.request?.headers.get("remote-addr")
try {
const newLogin = await Logins.create({
userId: id,
ip: ip,
});
if (newLogin) {
console.log("Login saved successfully:", newLogin);
}

} catch (error) {
console.error("Error saving login:", error);

}

},
},
}
}
});
import { betterAuth } from "better-auth";
import { MongoClient } from "mongodb";
import { mongodbAdapter } from "better-auth/adapters/mongodb";
import { admin } from "better-auth/plugins"
import Logins from "@/models/Logins";


const client = new MongoClient(process.env.MONGO_URI || "");
const db = client.db();

export const auth = betterAuth({
database: mongodbAdapter(db),
emailAndPassword: {
enabled: true
},
plugins: [
admin(),
],
user: {
additionalFields: {
purchases: {
type: "string[]",
defaultValue: [],
}
}
},
databaseHooks: {
user: {
update: {
after: async (user, ctx) => {
const id = user.id
const ip = ctx?.request?.headers.get("x-forwarded-for") || ctx?.request?.headers.get("remote-addr")
try {
const newLogin = await Logins.create({
userId: id,
ip: ip,
});
if (newLogin) {
console.log("Login saved successfully:", newLogin);
}

} catch (error) {
console.error("Error saving login:", error);

}

},
},
}
}
});
Solution:
solved it myself, turns out that I had to use session instead of user
Jump to solution
5 Replies
karlito1501
karlito1501OP3w ago
When I log in, it doesn't trigger it so I'm guessing update is wrong
Solution
karlito1501
karlito15013w ago
solved it myself, turns out that I had to use session instead of user
DN_Dev
DN_Dev2w ago
Create or update with session?
Husain
Husain2w ago
Btw, did you try to use jwt? I'm stuck somewhere with that. Need some perspective
karlito1501
karlito1501OP2w ago
I used create nope

Did you find this page helpful?