From 5cec48dbd79d6fe4c02e7e5a35e7d4ef2feef94b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A9l=20Solano?= Date: Mon, 15 Dec 2025 23:38:58 +0100 Subject: [PATCH] fix: properly merge updated data in account cookie (#6758) --- .../better-auth/src/api/routes/account.ts | 34 ++++++++++--------- .../better-auth/src/oauth2/link-account.ts | 5 ++- 2 files changed, 22 insertions(+), 17 deletions(-) diff --git a/packages/better-auth/src/api/routes/account.ts b/packages/better-auth/src/api/routes/account.ts index 19ab259957..93f11f949b 100644 --- a/packages/better-auth/src/api/routes/account.ts +++ b/packages/better-auth/src/api/routes/account.ts @@ -566,22 +566,24 @@ export const getAccessToken = createAuthEndpoint( ctx.context, ); newTokens = await provider.refreshAccessToken(refreshToken); - const updatedAccount = await ctx.context.internalAdapter.updateAccount( - account.id, - { - accessToken: await setTokenUtil(newTokens.accessToken, ctx.context), - accessTokenExpiresAt: newTokens.accessTokenExpiresAt, - refreshToken: await setTokenUtil( - newTokens.refreshToken, - ctx.context, - ), - refreshTokenExpiresAt: newTokens.refreshTokenExpiresAt, - }, - ); - const storeAccountCookie = - ctx.context.options.account?.storeAccountCookie; - if (storeAccountCookie && updatedAccount) { - await setAccountCookie(ctx, updatedAccount); + const updatedData = { + accessToken: await setTokenUtil(newTokens.accessToken, ctx.context), + accessTokenExpiresAt: newTokens.accessTokenExpiresAt, + refreshToken: await setTokenUtil(newTokens.refreshToken, ctx.context), + refreshTokenExpiresAt: newTokens.refreshTokenExpiresAt, + }; + let updatedAccount: Record | null = null; + if (account.id) { + updatedAccount = await ctx.context.internalAdapter.updateAccount( + account.id, + updatedData, + ); + } + if (ctx.context.options.account?.storeAccountCookie) { + await setAccountCookie(ctx, { + ...account, + ...(updatedAccount ?? updatedData), + }); } } const tokens = { diff --git a/packages/better-auth/src/oauth2/link-account.ts b/packages/better-auth/src/oauth2/link-account.ts index 072cd89240..08bee50d7a 100644 --- a/packages/better-auth/src/oauth2/link-account.ts +++ b/packages/better-auth/src/oauth2/link-account.ts @@ -104,7 +104,10 @@ export async function handleOAuthUserInfo( }).filter(([_, value]) => value !== undefined), ); if (c.context.options.account?.storeAccountCookie) { - await setAccountCookie(c, updateData); + await setAccountCookie(c, { + ...account, + ...updateData, + }); } if (Object.keys(updateData).length > 0) {