How to log sign-in, sign-out, and errors?

Hi, How can I log user logins, logouts, errors, and other actions in the Better Auth library? I’m using it in a Next.js. Is there a built-in way to handle logging, or do I need to implement custom event tracking? Thank you
4 Replies
codecret | Software Engineer
if you are using server components use auth instance, if you are using client component use authClient instance
jirik9
jirik9OP4w ago
So the best way to achieve this is to handle logging manually in server actions? For example, I can use:
const response = await auth.api.signInEmail({
body: { email, password },
});
console.log(response); // log the response
const response = await auth.api.signInEmail({
body: { email, password },
});
console.log(response); // log the response
hooks: {
after: createAuthMiddleware(async (ctx) => {
console.log('After hook - context:', ctx)
}),
},
hooks: {
after: createAuthMiddleware(async (ctx) => {
console.log('After hook - context:', ctx)
}),
},
I also tried using the after hooks in auth.ts, but it didn’t seem to work. Has anyone successfully implemented logging using these hooks? So, Better Auth doesn’t have a built-in logging system?
codecret | Software Engineer
you can use authClient from client components , here is the implementation
async function onSubmit(event: React.SyntheticEvent) {
event.preventDefault();
setIsLoading(true);
await authClient.signIn.username(
{
username,
password,
},
{
onSuccess: (_data) => {
toast({
variant: "default",
title: "Sign In Successfully",
duration: 2000,
});
router.push("/dashboard");
},
onError: (ctx) => {
toast({
variant: "destructive",
title: ctx.error?.message || "An error occurred",
duration: 2000,
});
},
}
);

setIsLoading(false);
}
async function onSubmit(event: React.SyntheticEvent) {
event.preventDefault();
setIsLoading(true);
await authClient.signIn.username(
{
username,
password,
},
{
onSuccess: (_data) => {
toast({
variant: "default",
title: "Sign In Successfully",
duration: 2000,
});
router.push("/dashboard");
},
onError: (ctx) => {
toast({
variant: "destructive",
title: ctx.error?.message || "An error occurred",
duration: 2000,
});
},
}
);

setIsLoading(false);
}
additionally you can setup a middleware to only check for the existence of a session cookie to handle redirection.
import { NextRequest, NextResponse } from "next/server";
import { getSessionCookie } from "better-auth/cookies";

export async function middleware(request: NextRequest) {
const sessionCookie = getSessionCookie(request, {
// Optionally pass config if cookie name, prefix or useSecureCookies option is customized in auth config.
cookieName: "session_token",
cookiePrefix: "better-auth",
useSecureCookies: true,
});

if (!sessionCookie) {
return NextResponse.redirect(new URL("/", request.url));
}

return NextResponse.next();
}

export const config = {
matcher: ["/dashboard"], // Specify the routes the middleware applies to
}
import { NextRequest, NextResponse } from "next/server";
import { getSessionCookie } from "better-auth/cookies";

export async function middleware(request: NextRequest) {
const sessionCookie = getSessionCookie(request, {
// Optionally pass config if cookie name, prefix or useSecureCookies option is customized in auth config.
cookieName: "session_token",
cookiePrefix: "better-auth",
useSecureCookies: true,
});

if (!sessionCookie) {
return NextResponse.redirect(new URL("/", request.url));
}

return NextResponse.next();
}

export const config = {
matcher: ["/dashboard"], // Specify the routes the middleware applies to
}

Did you find this page helpful?