In this Ionic framework tutorial we are going to show you - step by step - how to integrate Twitter Sign In to your Ionic applications. This will enable an easy and elegant way for your users to log in to your mobile and web apps.

Benefits of adding Twitter Authentication to your Ionic app

  • Improve conversions: Help people log into your app quickly without having to remember another username and password.
  • One login across every device: Make it easy for people to log in and access their info across multiple platforms and devices.
  • Build a trusted relationship: Give people control over the info they share with your app.
  • Access profile info: like picture, gender, age, name, without having to ask for it.

At IonicThemes we are big fans of Learning by example, that's why all our ionic tutorials include a complete and free Ionic code example that you can reuse in your own projects.

We strive to create the best content for Ionic Framework, both tutorials and templates to help the Ionic community succeed. We work towards empowering developers to achieve a free life through coding. That's what motivates us at IonicThemes everyday.

In this post you will learn how to add Twitter login to your Ionic app. As an example we are going to build a simple Ionic app that allows users to log in using their Twitter account. Once they log in, they will see a screen with their basic profile information.

Important! This tutorial uses Twitter Fabric to get the Twitter API key. Fabric was recently acquired by Firebase so the implementation explored on this post is now deprecated. While we update this post, please refer to our updated Ionic Firebase authentication tutorial that also explains how to add Twitter login to your Ionic app.

Authentication is an essential part of most applications, and there are different approaches and strategies that you can take. The approach taken for any project depends on its particular application requirements. Let's explore some of these approaches.

Using your own API or Backend

If you already have an API or backend that handles user authentication, or if you like to have tight control over your backend implementation, then this may be your option.

Mobile apps require a different authentication strategy than web apps or websites. You don't have sessions so you have to go with the token based authentication. For our production apps we use and recommend NestJS.

NestJS is basically a Node.js framework that enables you to easily build efficient and scalable server-side applications. The architecture is heavily inspired by Angular so if you are familiar with Angular, you will find very enjoyable to work with Nest. Implementing Authentication using Nest is very straightforward. Learn how to integrate NestJS to your Ionic App.

Using a Backend As A Service

If you don't want to take care of your own infrastructure and backend implementation, then there are a few BaaS (Backend as aService) options.

Firebase is a very popular service that will help you building the backend for your Ionic Framework application. Firebase is a popular tool that helps you build apps fast, without managing infrastructure. It's also a powerful Database as a Service (DBaaS) solution which provides a scalable NoSQL cloud database to store and sync data for client and server side development.

Firebase is built on top of Google infrastructure and allows you to scale automatically, so you don't need to worry about scaling your own servers. You can read the following tutorial to learn how to handle Firebase authentication in Ionic apps.

Using Social Providers

You can choose to provide authentication using well known social networks such as Facebook, Instagram, Twitter, Google, Github, etc.

We think that in these days, this is the best way to authenticate your users because it's easier and faster for them and also for you. Also, remember that providing a good user experience is a key factor, so providing a one click authentication will definitely add up to a good UX (unless you are building a banking application).

We have created a set of detailed Ionic Authentication tutorials to help you adding this functionality to your Ionic app.

So to define the scope of this post, in this tutorial we will explore how to add Twitter authentication to your Ionic app.

Each authentication option has its pros and cons, and of course you can mix them together and have an even more complete solution and experience for your users. It's very common to see different ways of authenticating users within an app.

Update! From April 2020 onwards, if you want to publish your Ionic application on the Apple App Store, you also need to add Sign in with Apple. Why? Because they say so and they control their market (not happy with this? Build a PWA!).

The Apple guidelines states: "Apps that exclusively use a third-party or social login service (such as Facebook Login, Google Sign-In, Sign in with Twitter, Sign In with LinkedIn, Login with Amazon, or WeChat Login) to set up or authenticate the user's primary account with the app must also offer Sign in with Apple as an equivalent option." But, it also says: "Sign in with Apple is not required if: Your app exclusively uses your company's own account setup and sign-in systems."

If you need help building your Ionic App, you can check Ionic 6 Full Starter App.

It will save you hundreds of hours of development and design and it already has lots of useful features that you will love such as Twitter Login. These are some of the authentication screens available in the template.

Ionic twitter authentication
Ionic twitter authentication
Ionic twitter authentication

There are different ways to integrate Twitter authentication into your Ionic app. However, not all of them use the native approach which uses the Twitter Application to perform the login instead of opening a popup requesting users to enter their credentials to login to Twitter before granting access to your app.

The way it works for hybrid apps to use native API's and SDK's is very simple. We need a piece (typically a Cordova plugin) that connects native API's and SDK's with the javascript environment where the ionic app runs. For this example ionic app we are going to use a cordova plugin to interact with the Twitter API.

We will use the Twitter Connect Plugin to perform Twitter authentication on iOS and Android. You will not only get the name of the logged user, but also stuff like their full name, followers, and picture.

For this Ionic example app you will need:

  • An Ionic app where you will integrate this functionality. You can either use a Ionic blank app, or an existing one.
  • Fabric API key.
  • Register a Twitter App and get the Twitter Consumer Key and Twitter Consumer Secret
  • The Twitter Connect Pluginto interact with the native Twitter App.

Don't worry, in this twitter authentication with Ionic tutorial we will guide you through all these steps.

Our Ionic demo app will look like this:

Ionic twitter login
Ionic twitter login
Ionic twitter login

Using Twitter's Fabric SDK, you can enable Single Sign On with your Android and iOS apps. To use Fabric, you will need to create an account.

What is Fabric?

Twitter launched Fabric as a modular SDK in 2014 to allow developers to pick and choose different tools to improve their apps. In 2017 Google acquired Fabric with the plan to integrate it with Firebase. Apparently, today you still need to create a Fabric account in order to install the Twitter Connect Plugin because the FABRIC_API_KEY is a required parameter.

twitter authentication tutorial

After creating the account just go to this link and log in with your new Fabric account. You don't need to do the onboarding process. The only thing we really need from Fabric is the API key, so try not to get messed with other options.

Scroll down to Add Your API Key section and you will see the following code with your app API KEY.

twitter api key

Before we start, I want to remember you that you can download for free the code of this ionic project by clicking the GET THE CODE button from the beginning of the page.

In this section I will show how to create your Twitter app in order to get the consumer key and consumer secret.

  • Go to your Twitter Application Management
  • To create an app, you need a Twitter developer account. If you don't have you can create one.
  • Follow the steps to Create a new app or use an existing one.
  • When creating the app make sure to set Callback URL=twittersdk:// and to enable Sign in with Twitter.

Once you you have your Fabric API key, and your Twitter App Consumer API keys, it's time to install the cordova plugin into your Ionic app.

Execute the following command on the terminal changing the variables Fabric API Key, Twitter Consumer Key and Twitter Consumer Secret with your own values. (Also remove the <>)

ionic cordova plugin add twitter-connect-plugin --variable FABRIC_KEY=<Fabric API Key> --variable TWITTER_KEY=<Twitter Consumer Key> --variable TWITTER_SECRET=<Twitter Consumer Secret> --save

npm install --save @ionic-native/twitter-connect

What we have done so far:

  • Created an Ionic app (or used a existing one)
  • Created a Fabric Account
  • Created a Twitter app (or used a existing one)
  • Installed Twitter Connect Plugin in our Ionic framework app

Now we will go straight to the code so open your Ionic app with your preferred code editor. Personally I use and recommend atom.

We don't want to ask users to log in each time they open the app because it would be annoying. To solve this we will use Native Storage to save the user data the first time they log in.

Native Storage

Native Storage is a Cordova plugin which provides persistent storage of primitives native in Android, iOS and Windows. It's created because of the non-persistent property of Local Storage in the WebView of Android and iOS. In iOS stored data from LocalStorage can be removed by the OS, when running out of memory.

To install native storage plugin just run the following commands in your ionic project:

$ ionic cordova plugin add cordova-plugin-nativestorage --save$ npm install --save @ionic-native/native-storage

To know if the user is already logged in, we will add the following code to check this in the platform.ready() in app.component.ts.

export class AppComponent {
  constructor(
    private platform: Platform,
    private splashScreen: SplashScreen,
    private statusBar: StatusBar,
    private nativeStorage: NativeStorage,
    private router: Router
  ) {
    this.initializeApp();
  }

  initializeApp() {
    this.platform.ready().then(() => {
      //Here we will check if the user is already logged in
      //because we don't want to ask users to log in each time they open the app
      this.nativeStorage.getItem('twitter_user')
      .then(data => {
        //user is previously logged and we have his data
        //we will let him access the app
        this.router.navigate(["/user"]);
        this.splashScreen.hide();
      }, err => {
        this.router.navigate(["/login"]);
        this.splashScreen.hide();
      })
      this.statusBar.styleDefault();
    });
  }
}

Ionic Twitter Log In

The best way to show you how to add log in functionality to your Ionic Framework App is with a real example of the code, here you can see some Typescript code that handles the all the twitter authentication for your ionic app.

import { Component } from '@angular/core';
import { TwitterConnect } from '@ionic-native/twitter-connect/ngx';
import { Router } from '@angular/router';
import { NativeStorage } from '@ionic-native/native-storage/ngx';
import { LoadingController } from '@ionic/angular';

@Component({
selector: 'app-login',
templateUrl: './login.page.html',
styleUrls: ['./login.page.scss'],
})
export class LoginPage {

  constructor(
    private tw: TwitterConnect,
    private nativeStorage: NativeStorage,
    public loadingController: LoadingController,
    private router: Router
  ) { }

  async doTwLogin() {
    const loading = await this.loadingController.create({
      message: 'Please wait...'
    });
    this.presentLoading(loading);
    this.tw.login()
    .then( res => {
      // Get user data
      // There is a bug which fires the success event in the error event.
      // The issue is reported in https://github.com/chroa/twitter-connect-plugin/issues/23
      this.tw.showUser()
      .then(user =>{
        console.log(user);
        loading.dismiss();
      }, err =>{
        console.log(err);
        // default twitter image is too small https://developer.twitter.com/en/docs/accounts-and-users/user-profile-images-and-banners
        var profile_image = err.profile_image_url_https.replace('_normal','');
        this.nativeStorage.setItem('twitter_user', {
          name: err.name,
          userName: err.screen_name,
          followers: err.followers_count,
          picture: profile_image
        })
        .then(() => {
           this.router.navigate(["/user"]);
           loading.dismiss();
        }, (error) => {
          console.log(error);
          loading.dismiss();
        })
      })
    }, err => {
      loading.dismiss();
    })
  }

  async presentLoading(loading) {
    return await loading.present();
  }
}

Ionic Twitter Log Out

To perform Twitter log out we will call the tw.logout() method that will invalidate the token generated at log in. Also, we will remove from the native storage the data from the logged user.

import { Component, OnInit } from '@angular/core';
import { UserModel } from './user.model';
import { TwitterConnect } from '@ionic-native/twitter-connect/ngx';
import { Router } from '@angular/router';
import { NativeStorage } from '@ionic-native/native-storage/ngx';
import { LoadingController } from '@ionic/angular';

@Component({
  selector: 'app-user',
  templateUrl: './user.page.html',
  styleUrls: ['./user.page.scss'],
})
export class UserPage implements OnInit {

  user: UserModel = new UserModel();

  constructor(
    private tw: TwitterConnect,
    private nativeStorage: NativeStorage,
    public loadingController: LoadingController,
    private router: Router
  ) { }

  async ngOnInit() {
    const loading = await this.loadingController.create({
      message: 'Please wait...'
    });
     await loading.present();
     this.nativeStorage.getItem('twitter_user')
    .then(data => {
      this.user = {
        name: data.name,
        userName: data.userName,
        picture: data.picture,
        followers: data.followers
      };
      loading.dismiss();
    }, error => {
      console.log(error);
      loading.dismiss();
    });
  }

  doTwLogout() {
    this.tw.logout().then(response => {
      this.nativeStorage.remove('twitter_user');
      this.router.navigate(["/login"]);
    }, error => {
      console.log(error);
    });
  }
}

Testing the implementation

At this point you should have an Ionic application with Twitter log in and log out functionalities. To test the native implementation you need to test the application in a real device or in an emulator because Cordova isn't available on the browser.

If you are new to Ionic development you can check how to Run your Ionic app in different environments.

Remember you can download all the source code of this Ionic tutorial by clicking the GET THE CODE button from the beginning of this page.

Did you know that we recently released Ionic 6 Full Starter App - PRO version? It's an Ionic PWA template that you can use to jump start your PWA development and save yourself hundreds of hours of design and development. Try it on your phone as a PWA.

ionic 5 starter

Authentication is an essential part of most applications, and there are different approaches and strategies that you can take. The approach taken for any project depends on its particular application requirements. Let's explore some of these approaches.

In this post we explained how to add Twitter Sign In to an Ionic Framework application. We built a demo app that you can download and use for free to build your own Ionic application.

To add the log in functionality we used Twitter Connect Cordova plugin. It enables a native log in both in iOS and Android apps.

If you have any issues or questions about this tutorial please leave a comment below.

If you want to keep learning Ionic Framework, I suggest you the following tutorials:

At IonicThemes we are big fans of Learning by example, that's why all our ionic tutorials include a complete and free ionic code example that you can reuse in your ionic projects.

We strive to create the best content for Ionic Framework, both tutorials and templates to help the Ionic community succeed. We work towards empowering developers to achieve a free life through coding. That's what motivates us at IonicThemes everyday.

Also, you can check out our detailed and professional Ionic Starter App crafted with love and dedication to help you create better apps and supercharge your productivity.