Authenticate Using GitHub with JavaScript

You can let your users authenticate with Firebase using their GitHub accountsby integrating GitHub authentication into your app. You can integrate GitHubauthentication either by using the Firebase SDK to carry out the sign-in flow,or by carrying out the GitHub OAuth 2.0 flow manually and passing the resultingaccess token to Firebase.

Before you begin

  1. Add Firebase to your JavaScript project.
  2. In theFirebase console, open theAuth section.
  3. On theSign in method tab, enable theGitHub provider.
  4. Add theClient ID andClient Secret from that provider's developer console to the provider configuration:
    1. Register your app as a developer application on GitHub and get your app's OAuth 2.0Client ID andClient Secret.
    2. Make sure your FirebaseOAuth redirect URI (e.g.my-app-12345.firebaseapp.com/__/auth/handler) is set as yourAuthorization callback URL in your app's settings page on yourGitHub app's config.
  5. ClickSave.

Handle the sign-in flow with the Firebase SDK

If you are building a web app, the easiest way to authenticate your userswith Firebase using their GitHub accounts is to handle the sign-in flow withthe Firebase JavaScript SDK. (If you want to authenticate a user in Node.jsor other non-browser environment, you must handle the sign-in flow manually.)

To handle the sign-in flow with the Firebase JavaScript SDK, follow thesesteps:

  1. Create an instance of the GitHub provider object:

    Web

    import{GithubAuthProvider}from"firebase/auth";constprovider=newGithubAuthProvider();

    Web

    varprovider=newfirebase.auth.GithubAuthProvider();
  2. Optional: Specify additional OAuth 2.0 scopes that you want to request from the authentication provider. To add a scope, calladdScope. For example:

    Web

    provider.addScope('repo');

    Web

    provider.addScope('repo');
    See theauthentication provider documentation.
  3. Optional: Specify additional custom OAuth provider parameters that you want to send with the OAuth request. To add a custom parameter, callsetCustomParameters on the initialized provider with an object containing the key as specified by the OAuth provider documentation and the corresponding value. For example:

    Web

    provider.setCustomParameters({'allow_signup':'false'});

    Web

    provider.setCustomParameters({'allow_signup':'false'});
    Reserved required OAuth parameters are not allowed and will be ignored. See the authentication provider reference for more details.
  4. Authenticate with Firebase using the GitHub provider object. You can prompt your users to sign in with their GitHub accounts either by opening a pop-up window or by redirecting to the sign-in page. The redirect method is preferred on mobile devices.
    • To sign in with a pop-up window, callsignInWithPopup:

      Web

      import{getAuth,signInWithPopup,GithubAuthProvider}from"firebase/auth";constauth=getAuth();signInWithPopup(auth,provider).then((result)=>{// This gives you a GitHub Access Token. You can use it to access the GitHub API.constcredential=GithubAuthProvider.credentialFromResult(result);consttoken=credential.accessToken;// The signed-in user info.constuser=result.user;// IdP data available using getAdditionalUserInfo(result)// ...}).catch((error)=>{// Handle Errors here.consterrorCode=error.code;consterrorMessage=error.message;// The email of the user's account used.constemail=error.customData.email;// The AuthCredential type that was used.constcredential=GithubAuthProvider.credentialFromError(error);// ...});

      Web

      firebase.auth().signInWithPopup(provider).then((result)=>{/** @type {firebase.auth.OAuthCredential} */varcredential=result.credential;// This gives you a GitHub Access Token. You can use it to access the GitHub API.vartoken=credential.accessToken;// The signed-in user info.varuser=result.user;// IdP data available in result.additionalUserInfo.profile.// ...}).catch((error)=>{// Handle Errors here.varerrorCode=error.code;varerrorMessage=error.message;// The email of the user's account used.varemail=error.email;// The firebase.auth.AuthCredential type that was used.varcredential=error.credential;// ...});
      Also notice that you can retrieve the GitHub provider's OAuth token which can be used to fetch additional data using the GitHub APIs.

      This is also where you can catch and handle errors. For a list of error codes have a look at theAuth Reference Docs.

    • To sign in by redirecting to the sign-in page, callsignInWithRedirect: Follow thebest practices when using `signInWithRedirect`.

      Web

      import{getAuth,signInWithRedirect}from"firebase/auth";constauth=getAuth();signInWithRedirect(auth,provider);

      Web

      firebase.auth().signInWithRedirect(provider);
      Then, you can also retrieve the GitHub provider's OAuth token by callinggetRedirectResult when your page loads:

      Web

      import{getAuth,getRedirectResult,GithubAuthProvider}from"firebase/auth";constauth=getAuth();getRedirectResult(auth).then((result)=>{constcredential=GithubAuthProvider.credentialFromResult(result);if(credential){// This gives you a GitHub Access Token. You can use it to access the GitHub API.consttoken=credential.accessToken;// ...}// The signed-in user info.constuser=result.user;// IdP data available using getAdditionalUserInfo(result)// ...}).catch((error)=>{// Handle Errors here.consterrorCode=error.code;consterrorMessage=error.message;// The email of the user's account used.constemail=error.customData.email;// The AuthCredential type that was used.constcredential=GithubAuthProvider.credentialFromError(error);// ...});

      Web

      firebase.auth().getRedirectResult().then((result)=>{if(result.credential){/** @type {firebase.auth.OAuthCredential} */varcredential=result.credential;// This gives you a GitHub Access Token. You can use it to access the GitHub API.vartoken=credential.accessToken;// ...}// The signed-in user info.varuser=result.user;// IdP data available in result.additionalUserInfo.profile.// ...}).catch((error)=>{// Handle Errors here.varerrorCode=error.code;varerrorMessage=error.message;// The email of the user's account used.varemail=error.email;// The firebase.auth.AuthCredential type that was used.varcredential=error.credential;// ...});
      This is also where you can catch and handle errors. For a list of error codes have a look at theAuth Reference Docs.

Handling account-exists-with-different-credential Errors

If you enabled theOne account per email address setting in theFirebase console,when a user tries to sign in a to a provider (such as GitHub) with an email that alreadyexists for another Firebase user's provider (such as Google), the errorauth/account-exists-with-different-credential is thrown along with anAuthCredential object (GitHub access token). To complete the sign in to theintended provider, the user has to sign first to the existing provider (Google) and then link to theformerAuthCredential (GitHub access token).

Popup mode

If you usesignInWithPopup, you can handleauth/account-exists-with-different-credential errors with code like the followingexample:

import{getAuth,linkWithCredential,signInWithPopup,GitHubAuthProvider,}from"firebase/auth";try{//Step1:UsertriestosigninusingGitHub.letresult=awaitsignInWithPopup(getAuth(),newGitHubAuthProvider());}catch(error){//Step2:User's email already exists.if(error.code==="auth/account-exists-with-different-credential"){//ThependingGitHubcredential.letpendingCred=error.credential;//Step3:Savethependingcredentialintemporarystorage,//Step4:Lettheuserknowthattheyalreadyhaveanaccount//butwithadifferentprovider,andletthemchooseanother//sign-inmethod.}}//...try{//Step5:Signtheuserinusingtheirchosenmethod.letresult=awaitsignInWithPopup(getAuth(),userSelectedProvider);//Step6:LinktotheGitHubcredential.//TODO:implement`retrievePendingCred`foryourapp.letpendingCred=retrievePendingCred();if(pendingCred!==null){//Asyouhaveaccesstothependingcredential,youcandirectlycallthe//linkmethod.letuser=awaitlinkWithCredential(result.user,pendingCred);}//Step7:Continuetoapp.}catch(error){//...}

Redirect mode

This error is handled in a similar way in the redirect mode, with the difference that the pendingcredential has to be cached between page redirects (for example, using session storage).

Handle the sign-in flow manually

You can also authenticate with Firebase using a GitHub account by handling thesign-in flow by calling the GitHub OAuth 2.0 endpoints:

  1. Integrate GitHub authentication into your app by following the developer's documentation. At the end of the GitHub sign-in flow, you will receive an OAuth 2.0 access token.
  2. If you need to sign in on a Node.js application, send the OAuth access token to the Node.js application.
  3. After a user successfully signs in with GitHub, exchange the OAuth 2.0 access token for a Firebase credential:

    Web

    import{GithubAuthProvider}from"firebase/auth";constcredential=GithubAuthProvider.credential(token);

    Web

    varcredential=firebase.auth.GithubAuthProvider.credential(token);
  4. Authenticate with Firebase using the Firebase credential:

    Web

    import{getAuth,signInWithCredential}from"firebase/auth";// Sign in with the credential from the user.constauth=getAuth();signInWithCredential(auth,credential).then((result)=>{// Signed in// ...}).catch((error)=>{// Handle Errors here.consterrorCode=error.code;consterrorMessage=error.message;// The email of the user's account used.constemail=error.customData.email;// ...});

    Web

    // Sign in with the credential from the user.firebase.auth().signInWithCredential(credential).then((result)=>{// Signed in// ...}).catch((error)=>{// Handle Errors here.consterrorCode=error.code;consterrorMessage=error.message;// The email of the user's account used.constemail=error.email;// ...});

Authenticate with Firebase in a Chrome extension

If you are building a Chrome extension app, see the Offscreen Documents guide.

Customizing the redirect domain for GitHub sign-in

On project creation, Firebase will provision a unique subdomain for your project:https://my-app-12345.firebaseapp.com.

This will also be used as the redirect mechanism for OAuth sign in. That domain would need to be allowed for all supported OAuth providers. However, this means that users may see that domain while signing in to GitHub before redirecting back to the application:Continue to: https://my-app-12345.firebaseapp.com.

To avoid displaying your subdomain, you can set up a custom domain withFirebase Hosting:

  1. Follow steps 1 through 3 inSet up your domain forHosting. When you verify your domain ownership,Hosting provisions an SSL certificate for your custom domain.
  2. Add your custom domain to the list of authorized domains in theFirebase console:auth.custom.domain.com.
  3. In the GitHub developer console or OAuth setup page, whitelist the URL of the redirect page, which will be accessible on your custom domain:https://auth.custom.domain.com/__/auth/handler.
  4. When you initialize the JavaScript library, specify your custom domain with theauthDomain field:
    varconfig={apiKey:'...',//Changedfrom'PROJECT_ID.firebaseapp.com'.authDomain:'auth.custom.domain.com',databaseURL:'https://PROJECT_ID.firebaseio.com',projectId:'PROJECT_ID',storageBucket:'PROJECT_ID.firebasestorage.app',messagingSenderId:'SENDER_ID'};firebase.initializeApp(config);

Next steps

After a user signs in for the first time, a new user account is created andlinked to the credentials—that is, the user name and password, phonenumber, or auth provider information—the user signed in with. This newaccount is stored as part of your Firebase project, and can be used to identifya user across every app in your project, regardless of how the user signs in.

  • In your apps, the recommended way to know the auth status of your user is toset an observer on theAuth object. You can then get the user'sbasic profile information from theUser object. SeeManage Users.

  • In yourFirebase Realtime Database andCloud StorageSecurity Rules, you can get the signed-in user's unique user ID from theauth variable, and use it to control what data a user can access.

You can allow users to sign in to your app using multiple authenticationproviders bylinking auth provider credentials to anexisting user account.

To sign out a user, callsignOut:

Web

import{getAuth,signOut}from"firebase/auth";constauth=getAuth();signOut(auth).then(()=>{// Sign-out successful.}).catch((error)=>{// An error happened.});

Web

firebase.auth().signOut().then(()=>{// Sign-out successful.}).catch((error)=>{// An error happened.});

Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2025-12-17 UTC.