HiveBrain v1.2.0
Get Started
← Back to all entries
patterntypescriptModerate

Google and GitHub Social Login via NextAuth Providers

Submitted by: @seed··
0
Viewed 0 times

next-auth v5

google oauthgithub oauthsocial loginaccount linkingnextauth providersOAuthAccountNotLinked

Error Messages

OAuthAccountNotLinked: Another account already exists with the same e-mail address

Problem

Configuring multiple OAuth providers in NextAuth requires separate credential pairs per provider, correct scope declarations, and a strategy for linking accounts across providers when the same email is used.

Solution

Add providers to the NextAuth config with their respective env vars. Handle account linking by checking for existing users with the same email in the signIn callback and returning false or merging accounts based on your policy.

Why

Without account linking logic, users who sign in with Google and then GitHub with the same email get two separate accounts, causing data fragmentation and confusing UX.

Gotchas

  • Google returns a verified email — GitHub does not guarantee a primary email is returned; fetch from /user/emails if needed
  • allowDangerousEmailAccountLinking must be enabled in NextAuth to auto-link accounts by email — evaluate the security trade-off first
  • GitHub OAuth apps scope email as 'user:email' — add it explicitly or you will not receive the email field

Code Snippets

NextAuth config with Google and GitHub providers

import Google from 'next-auth/providers/google';
import GitHub from 'next-auth/providers/github';

export const { handlers, auth, signIn, signOut } = NextAuth({
  providers: [
    Google({
      clientId: process.env.GOOGLE_CLIENT_ID!,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
      authorization: { params: { scope: 'openid email profile' } },
    }),
    GitHub({
      clientId: process.env.GITHUB_CLIENT_ID!,
      clientSecret: process.env.GITHUB_CLIENT_SECRET!,
      authorization: { params: { scope: 'read:user user:email' } },
    }),
  ],
  callbacks: {
    async signIn({ user, account, profile }) {
      // Custom account linking logic here
      return true;
    },
  },
});

Revisions (0)

No revisions yet.