Authenticate Using Twitter in JavaScript  |  Firebase Authentication

Authenticate Using Twitter in JavaScript

You can let your users authenticate with Firebase using their Twitter accounts by integrating Twitter authentication into your app. You can integrate Twitter authentication either by using the Firebase SDK to carry out the sign-in flow, or by carrying out the Twitter OAuth flow manually and passing the resulting access token and secret to Firebase.

Before you begin

  1. Add Firebase to your JavaScript project.
  2. In the Firebase console, go to Security > Authentication.
  3. In the Sign-in method tab, enable the Twitter sign-in provider.
  4. Add the API key and API secret from that provider's developer console to the provider configuration:
    1. Register your app as a developer application on Twitter and get your app's OAuth API key and API secret.
    2. Make sure your Firebase OAuth redirect URI (for example, my-app-12345.firebaseapp.com/__/auth/handler) is set as your Authorization callback URL in your app's settings page on your Twitter app's config.
  5. Click Save.

Handle the sign-in flow with the Firebase SDK

If you are building a web app, the easiest way to authenticate your users with Firebase using their Twitter accounts is to handle the sign-in flow with the Firebase JavaScript SDK.
To handle the sign-in flow with the Firebase JavaScript SDK, follow these steps:

  1. Create an instance of the Twitter provider object:
   import { TwitterAuthProvider } from "firebase/auth";
   const provider = new TwitterAuthProvider();
var provider = new firebase.auth.TwitterAuthProvider();
  1. Optional: To localize the provider's OAuth flow to the user's preferred language without explicitly passing the relevant custom OAuth parameters, update the language code on the Auth instance before starting the OAuth flow.
   import { getAuth } from "firebase/auth";
   const auth = getAuth();
   auth.languageCode = 'it';
firebase.auth().languageCode = 'it';
  1. Optional: Specify additional custom OAuth provider parameters that you want to send with the OAuth request.
   provider.setCustomParameters({
        'lang': 'es'
   });
  1. Authenticate with Firebase using the Twitter provider object. You can prompt your users to sign in with their Twitter 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:
   import { getAuth, signInWithPopup, TwitterAuthProvider } from "firebase/auth";
   const auth = getAuth();
   signInWithPopup(auth, provider)
     .then((result) => {
       const credential = TwitterAuthProvider.credentialFromResult(result);
       const token = credential.accessToken;
       const secret = credential.secret;
       const user = result.user;
     }).catch((error) => {
       const errorCode = error.code;
       const errorMessage = error.message;
       const email = error.customData.email;
       const credential = TwitterAuthProvider.credentialFromError(error);
     });
   import { getAuth, signInWithRedirect } from "firebase/auth";
   const auth = getAuth();
   signInWithRedirect(auth, provider);
  1. Then, you can retrieve the Twitter provider's OAuth token by calling getRedirectResult when your page loads:
   import { getAuth, getRedirectResult, TwitterAuthProvider } from "firebase/auth";
   const auth = getAuth();
   getRedirectResult(auth)
     .then((result) => {
       const credential = TwitterAuthProvider.credentialFromResult(result);
       const token = credential.accessToken;
       const secret = credential.secret;
       const user = result.user;
     }).catch((error) => {
       const errorCode = error.code;
       const errorMessage = error.message;
       const email = error.customData.email;
       const credential = TwitterAuthProvider.credentialFromError(error);
     });

Handling account-exists-with-different-credential Errors

If you enabled the One account per email address setting in the Firebase console, when a user tries to sign in to a provider with an email that already exists for another Firebase user’s provider, the error auth/account-exists-with-different-credential is thrown. To complete the sign-in to the intended provider, the user has to sign first to the existing provider and then link to the former AuthCredential.

Popup mode

If you use signInWithPopup, you can handle auth/account-exists-with-different-credential errors with code like:

import {
  getAuth,
  linkWithCredential,
  signInWithPopup,
  TwitterAuthProvider,
} from "firebase/auth";

try {
  let result = await signInWithPopup(getAuth(), new TwitterAuthProvider());
} catch (error) {
  if (error.code === "auth/account-exists-with-different-credential") {
    let pendingCred = error.credential;
    // Save the pending credential and let the user choose another sign-in method.
  }
}

try {
  let result = await signInWithPopup(getAuth(), userSelectedProvider);
  let user = await linkWithCredential(result.user, pendingCred);
} catch (error) {
  // Handle errors.
}

Redirect mode

This error is handled in a similar way in the redirect mode, with the pending credential cached between page redirects.

Handle the sign-in flow manually

  1. Integrate Twitter authentication into your app by following the developer's documentation. You will receive an OAuth access token and an OAuth secret.
  2. In a Node.js application, send the OAuth access token and the OAuth secret to the Node.js application.
  3. Exchange the OAuth access token and OAuth secret for a Firebase credential:
   var credential = firebase.auth.TwitterAuthProvider.credential(token, secret);
  1. Authenticate with Firebase using the Firebase credential:
   import { getAuth, signInWithCredential, TwitterAuthProvider } from "firebase/auth";
   const auth = getAuth();
   signInWithCredential(auth, credential)
        .then((result) => {
          // Signed in
        })
        .catch((error) => {
          // Handle errors.
        });

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 Twitter sign-in

To avoid displaying your Firebase subdomain during sign-in, set up a custom domain with Firebase Hosting. Follow the steps in Set up your domain for Hosting.

Next steps

After a user signs in for the first time, a new user account is created and linked. To maintain the auth status of your user, set an observer on the Auth object. This allows you to manage users based on their unique user ID in your Firebase Realtime Database and Cloud Storage.

You can allow users to sign in using multiple authentication providers by linking auth provider credentials to an existing user account.

To sign out a user, call signOut:

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