in packages/better-auth/src/plugins/anonymous/index.ts [184:235]
handler: createAuthMiddleware(async (ctx) => {
const setCookie = ctx.context.responseHeaders?.get("set-cookie");
/**
* We can consider the user is about to sign in or sign up
* if the response contains a session token.
*/
const sessionTokenName = ctx.context.authCookies.sessionToken.name;
/**
* The user is about to link their account.
*/
const sessionCookie = parseSetCookieHeader(setCookie || "")
.get(sessionTokenName)
?.value.split(".")[0];
if (!sessionCookie) {
return;
}
/**
* Make sure the user had an anonymous session.
*/
const session = await getSessionFromCtx<{ isAnonymous: boolean }>(
ctx,
{
disableRefresh: true,
},
);
if (!session || !session.user.isAnonymous) {
return;
}
if (ctx.path === "/sign-in/anonymous") {
throw new APIError("BAD_REQUEST", {
message:
ERROR_CODES.ANONYMOUS_USERS_CANNOT_SIGN_IN_AGAIN_ANONYMOUSLY,
});
}
const newSession = ctx.context.newSession;
if (!newSession) {
return;
}
if (options?.onLinkAccount) {
await options?.onLinkAccount?.({
anonymousUser: session,
newUser: newSession,
});
}
if (!options?.disableDeleteAnonymousUser) {
await ctx.context.internalAdapter.deleteUser(session.user.id);
}
}),