empty session in custom plugin hook
I wanna hook into the organization endpoints but the session property is null. I'm authenticated and the cookie is present in the request headers too. Am I missing something?
import type { BetterAuthPlugin } from "better-auth";
import { posthog } from "@.../posthog";
import { createAuthMiddleware } from "better-auth/plugins";
export const posthogPlugin = () =>
({
id: "posthogPlugin",
hooks: {
after: [
{
matcher: ({ path }) => {
if (path === "/organization/create") {
return true;
}
return false;
},
handler: createAuthMiddleware(async (ctx) => {
console.log("hello from handler");
console.log("ctx.context.session", ctx);
if (!ctx.context.session) {
return;
}
console.log("organization_create", ctx.context.session);
posthog.capture({
distinctId: ctx.context.session.user.id,
event: "organization_create",
});
}),
},
],
},
}) satisfies BetterAuthPlugin;
1 Reply
Update: getSessionFromCtx did the job
import type { BetterAuthPlugin } from "better-auth";
import { posthog } from "@.../posthog";
import { createAuthMiddleware } from "better-auth/plugins";
import { getSessionFromCtx } from "better-auth/api";
export const posthogPlugin = () =>
({
id: "posthogPlugin",
hooks: {
after: [
{
matcher: (context) => context.path.startsWith("/organization/create"),
handler: createAuthMiddleware(async (ctx) => {
const session = await getSessionFromCtx(ctx);
if (!session) {
return;
}
posthog.capture({
distinctId: session.user.id,
event: "organization_create",
});
}),
},
],
},
}) satisfies BetterAuthPlugin;