[GH-ISSUE #5428] Problem of connection with social providers #18872

Closed
opened 2026-04-15 17:33:39 -05:00 by GiteaMirror · 4 comments
Owner

Originally created by @MoFerhat on GitHub (Oct 20, 2025).
Original GitHub issue: https://github.com/better-auth/better-auth/issues/5428

Hi,

I'm currently migrating from NextAuth to Better-Auth and trying to understand the documentation.
With NextAuth, when a new user registers with a provider, for example Google, we do this:

callbacks: {
async jwt({ token, trigger, session, user, account, profile, isNewUser }) {

if (isNewUser && account.provider === 'google') {
      console.log('🟢 First Google Login Detected')
      // do something
    }
}
}

I tried this with Better Auth :

hooks: {
  after: createAuthMiddleware(async ctx => {  
    if (ctx.path.startsWith('/sign-in')) {
      const newSession = ctx.context.newSession
      const GoogleProvider = ctx.context.socialProviders[0].id === 'google'
      if (newSession && GoogleProvider) {
        console.log('🟢 First Google Login Detected')
      } else {
        console.log('🟣 NOT FIRST GOOGLE LOGIN')
      }
    }
  })
}

The console displays 🟣 NOT FIRST GOOGLE LOGIN whenever signIn.social() is called,

Originally created by @MoFerhat on GitHub (Oct 20, 2025). Original GitHub issue: https://github.com/better-auth/better-auth/issues/5428 Hi, I'm currently migrating from NextAuth to Better-Auth and trying to understand the documentation. With NextAuth, when a new user registers with a provider, for example Google, we do this: ``` callbacks: { async jwt({ token, trigger, session, user, account, profile, isNewUser }) { if (isNewUser && account.provider === 'google') { console.log('🟢 First Google Login Detected') // do something } } } ``` I tried this with Better Auth : ``` hooks: { after: createAuthMiddleware(async ctx => { if (ctx.path.startsWith('/sign-in')) { const newSession = ctx.context.newSession const GoogleProvider = ctx.context.socialProviders[0].id === 'google' if (newSession && GoogleProvider) { console.log('🟢 First Google Login Detected') } else { console.log('🟣 NOT FIRST GOOGLE LOGIN') } } }) } ``` The console displays 🟣 NOT FIRST GOOGLE LOGIN whenever signIn.social() is called,
GiteaMirror added the locked label 2026-04-15 17:33:40 -05:00
Author
Owner

@dosubot[bot] commented on GitHub (Oct 20, 2025):

Hi @MoFerhat! I'm Dosu and I’m helping the better-auth team.

Better Auth doesn't have a built-in equivalent to NextAuth's isNewUser flag, which is why your current hook always logs "NOT FIRST GOOGLE LOGIN". The ctx.context.newSession property only indicates a new session, not whether the user is new, and ctx.context.socialProviders lists available providers, not the one just used or if it's the user's first time.

The closest event to a first-time login is when Better Auth provisions a user via the provisionUser function—this happens when a user authenticates and doesn't already exist in your system. However, this isn't exposed as a flag in hooks or middleware by default (source).

To replicate isNewUser, you’ll need to implement a custom check. The typical approach is to check in your user database (or adapter) whether the user already has a linked account for the provider (e.g., Google) during the provisioning or sign-in process. If not, you know it’s their first login with that provider.

For example, in your user provisioning logic or a custom middleware, you could:

// Pseudocode for user provisioning or sign-in handler
const user = await findUserByProviderAccount(providerId, providerAccountId);
if (!user) {
  // First time login with this provider
  // Do your custom logic here
  console.log('🟢 First Google Login Detected');
  // Optionally, create the user and link the provider account
} else {
  // Existing user
  console.log('🟣 NOT FIRST GOOGLE LOGIN');
}

You can place this logic in your custom user adapter, in the function that handles user creation/account linking, or in a middleware that runs after authentication. This way, you can reliably detect and handle first-time social logins.

To reply, just mention @dosu.


How did I do? Good | Irrelevant | Incorrect | Verbose | Hallucination | Report 🐛 | Other  Chat with Dosu Join Discord Share on X

<!-- gh-comment-id:3421918716 --> @dosubot[bot] commented on GitHub (Oct 20, 2025): <!-- Greeting --> Hi @MoFerhat! I'm [Dosu](https://go.dosu.dev/dosubot) and I’m helping the better-auth team. <!-- Answer --> Better Auth doesn't have a built-in equivalent to NextAuth's isNewUser flag, which is why your current hook always logs "NOT FIRST GOOGLE LOGIN". The ctx.context.newSession property only indicates a new session, not whether the user is new, and ctx.context.socialProviders lists available providers, not the one just used or if it's the user's first time. The closest event to a first-time login is when Better Auth provisions a user via the provisionUser function—this happens when a user authenticates and doesn't already exist in your system. However, this isn't exposed as a flag in hooks or middleware by default ([source](https://github.com/better-auth/better-auth/pull/5283)). To replicate isNewUser, you’ll need to implement a custom check. The typical approach is to check in your user database (or adapter) whether the user already has a linked account for the provider (e.g., Google) during the provisioning or sign-in process. If not, you know it’s their first login with that provider. For example, in your user provisioning logic or a custom middleware, you could: ```ts // Pseudocode for user provisioning or sign-in handler const user = await findUserByProviderAccount(providerId, providerAccountId); if (!user) { // First time login with this provider // Do your custom logic here console.log('🟢 First Google Login Detected'); // Optionally, create the user and link the provider account } else { // Existing user console.log('🟣 NOT FIRST GOOGLE LOGIN'); } ``` You can place this logic in your custom user adapter, in the function that handles user creation/account linking, or in a middleware that runs after authentication. This way, you can reliably detect and handle first-time social logins. <!-- Dosu Comment Footer --> *To reply, just mention [@dosu](https://go.dosu.dev/dosubot).* --- <sup>How did I do? [Good](https://app.dosu.dev/response-feedback/68cdce2b-b309-4421-8049-7d00e53957b7?feedback_type=great_response) | [Irrelevant](https://app.dosu.dev/response-feedback/68cdce2b-b309-4421-8049-7d00e53957b7?feedback_type=irrelevant_answer) | [Incorrect](https://app.dosu.dev/response-feedback/68cdce2b-b309-4421-8049-7d00e53957b7?feedback_type=incorrect_sources) | [Verbose](https://app.dosu.dev/response-feedback/68cdce2b-b309-4421-8049-7d00e53957b7?feedback_type=too_verbose) | [Hallucination](https://app.dosu.dev/response-feedback/68cdce2b-b309-4421-8049-7d00e53957b7?feedback_type=hallucination) | [Report 🐛](https://app.dosu.dev/response-feedback/68cdce2b-b309-4421-8049-7d00e53957b7?feedback_type=bug_report) | [Other](https://app.dosu.dev/response-feedback/68cdce2b-b309-4421-8049-7d00e53957b7?feedback_type=other)</sup>&nbsp;&nbsp;[![Chat with Dosu](https://dosu.dev/dosu-chat-badge.svg)](https://app.dosu.dev/cdda13d9-dd27-4d31-b09a-5d8bec92de21/ask?utm_source=github)&nbsp;[![Join Discord](https://img.shields.io/badge/join-5865F2?logo=discord&logoColor=white&label=)](https://go.dosu.dev/discord-bot)&nbsp;[![Share on X](https://img.shields.io/badge/X-share-black)](https://twitter.com/intent/tweet?text=%40dosu_ai%20helped%20me%20solve%20this%20issue!&url=https%3A//github.com/better-auth/better-auth/issues/5428)
Author
Owner

@MoFerhat commented on GitHub (Oct 20, 2025):

@dosu

When you log in (or first log in), better-auth already creates the account, so you never know if it's your first login or not.

Here's what I tried :

hooks: {
  after: createAuthMiddleware(async ctx => {
    const newSession = ctx.context.newSession

    if (newSession) {
      const provider = ctx?.params.id 
      const existingAccount = await prisma.account.findFirst({
        where: {
          providerId: provider,
          userId: newSession.user.id
        }
      })

      if (existingAccount) { 
        console.log('🟣 NOT FIRST GOOGLE LOGIN')
      } else { 
        console.log('🔵FIRST GOOGLE LOGIN !!!!!!!!!!')
      }
    }
  })
}
<!-- gh-comment-id:3423423947 --> @MoFerhat commented on GitHub (Oct 20, 2025): @dosu When you log in (or first log in), better-auth already creates the account, so you never know if it's your first login or not. Here's what I tried : ``` hooks: { after: createAuthMiddleware(async ctx => { const newSession = ctx.context.newSession if (newSession) { const provider = ctx?.params.id const existingAccount = await prisma.account.findFirst({ where: { providerId: provider, userId: newSession.user.id } }) if (existingAccount) { console.log('🟣 NOT FIRST GOOGLE LOGIN') } else { console.log('🔵FIRST GOOGLE LOGIN !!!!!!!!!!') } } }) } ```
Author
Owner

@dosubot[bot] commented on GitHub (Oct 20, 2025):

You're right—Better Auth creates or links the provider account during the authentication flow, so by the time your after hook runs, the account already exists and your database check will always find it.

Instead, Better Auth exposes an internal isRegister flag during the OAuth2 callback that indicates if the user was just registered (i.e., first login with the provider). This flag is attached to ctx.context.returned before after hooks run, so you can check it in your middleware. For example:

hooks: {
  after: createAuthMiddleware(async ctx => {
    const result = ctx.context.returned;
    // Defensive: result may be undefined or shaped differently depending on endpoint/plugin
    if (result && typeof result === 'object' && 'isRegister' in result) {
      if (result.isRegister) {
        console.log('🔵 FIRST GOOGLE LOGIN !!!!!!!!!!');
      } else {
        console.log('🟣 NOT FIRST GOOGLE LOGIN');
      }
    }
  })
}

Just make sure to check the structure of ctx.context.returned for your specific flow, as it can vary depending on the endpoint or plugin implementation. This approach is the closest equivalent to NextAuth's isNewUser flag in Better Auth and should reliably detect first-time social logins with Google or other providers.

Reference: OAuth2 callback and isRegister flag in Better Auth

To reply, just mention @dosu.


How did I do? Good | Irrelevant | Incorrect | Verbose | Hallucination | Report 🐛 | Other  Chat with Dosu Join Discord Share on X

<!-- gh-comment-id:3423430189 --> @dosubot[bot] commented on GitHub (Oct 20, 2025): <!-- Answer --> You're right—Better Auth creates or links the provider account during the authentication flow, so by the time your after hook runs, the account already exists and your database check will always find it. Instead, Better Auth exposes an internal isRegister flag during the OAuth2 callback that indicates if the user was just registered (i.e., first login with the provider). This flag is attached to ctx.context.returned before after hooks run, so you can check it in your middleware. For example: ```ts hooks: { after: createAuthMiddleware(async ctx => { const result = ctx.context.returned; // Defensive: result may be undefined or shaped differently depending on endpoint/plugin if (result && typeof result === 'object' && 'isRegister' in result) { if (result.isRegister) { console.log('🔵 FIRST GOOGLE LOGIN !!!!!!!!!!'); } else { console.log('🟣 NOT FIRST GOOGLE LOGIN'); } } }) } ``` Just make sure to check the structure of ctx.context.returned for your specific flow, as it can vary depending on the endpoint or plugin implementation. This approach is the closest equivalent to NextAuth's isNewUser flag in Better Auth and should reliably detect first-time social logins with Google or other providers. Reference: [OAuth2 callback and isRegister flag in Better Auth](https://github.com/better-auth/better-auth/blob/d113f99410c8d16348275df8e5fcd71680b062af/packages/better-auth/src/plugins/generic-oauth/index.ts) <!-- Dosu Comment Footer --> *To reply, just mention [@dosu](https://go.dosu.dev/dosubot).* --- <sup>How did I do? [Good](https://app.dosu.dev/response-feedback/419037c1-8fe7-4125-96ed-a26147b99fc4?feedback_type=great_response) | [Irrelevant](https://app.dosu.dev/response-feedback/419037c1-8fe7-4125-96ed-a26147b99fc4?feedback_type=irrelevant_answer) | [Incorrect](https://app.dosu.dev/response-feedback/419037c1-8fe7-4125-96ed-a26147b99fc4?feedback_type=incorrect_sources) | [Verbose](https://app.dosu.dev/response-feedback/419037c1-8fe7-4125-96ed-a26147b99fc4?feedback_type=too_verbose) | [Hallucination](https://app.dosu.dev/response-feedback/419037c1-8fe7-4125-96ed-a26147b99fc4?feedback_type=hallucination) | [Report 🐛](https://app.dosu.dev/response-feedback/419037c1-8fe7-4125-96ed-a26147b99fc4?feedback_type=bug_report) | [Other](https://app.dosu.dev/response-feedback/419037c1-8fe7-4125-96ed-a26147b99fc4?feedback_type=other)</sup>&nbsp;&nbsp;[![Chat with Dosu](https://dosu.dev/dosu-chat-badge.svg)](https://app.dosu.dev/cdda13d9-dd27-4d31-b09a-5d8bec92de21/ask?utm_source=github)&nbsp;[![Join Discord](https://img.shields.io/badge/join-5865F2?logo=discord&logoColor=white&label=)](https://go.dosu.dev/discord-bot)&nbsp;[![Share on X](https://img.shields.io/badge/X-share-black)](https://twitter.com/intent/tweet?text=%40dosu_ai%20helped%20me%20solve%20this%20issue!&url=https%3A//github.com/better-auth/better-auth/issues/5428)
Author
Owner

@MoFerhat commented on GitHub (Oct 21, 2025):

Hi @ping-maxwell

Do you have a solution to detect a new user when they log in (or register, I don't know what to call it) with Google for example? I can't find anything in the documentation.

UPDATE : Finally I found the solution with databaseHooks

<!-- gh-comment-id:3427718093 --> @MoFerhat commented on GitHub (Oct 21, 2025): Hi @ping-maxwell Do you have a solution to detect a new user when they log in (or register, I don't know what to call it) with Google for example? I can't find anything in the documentation. _UPDATE_ : Finally I found the solution with **databaseHooks**
Sign in to join this conversation.
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: github-starred/better-auth#18872