Twitter Login in Ionic 4

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

Why adding Twitter Authentication into your ionic framework app will benefit you and your users?

  • 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.

Authentication options

Authentication is a key component for your app, and there are some different approaches that you can take.

The handcrafted way (using your own API/Backend)

If you already have an API or backend that handles user authentication, or if you are one of those who like to have strict control over the 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 some production apps we use Loopback. Basically is a platform that enables you to easily build custom API’s for your backend needs. It comes with token based authentication and an Angular SDK that works smoothly in your Ionic apps. You can learn more about how to integrate Loopback to your Ionic App in: Building a complete mobile app with Ionic 3.

The Social way

Also, you can choose to provide authentication using well known social networks such as Facebook, Instagram, Twitter, Google, etc. We think that nowadays this is the best way to authenticate your users so we have created a set of tutorials to help you with this task.

The BaaS way

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

Firebase is a service that will help you build your app’s backend with ease. It’s 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. It is a popular tool that helps you build apps fast, without managing infrastructure. Firebase is built on Google infrastructure and scales automatically, for even the largest apps, so you don’t need to worry about scaling your own servers. You can read the following tutorial to learn how to Add Firebase authentication to your Ionic App.

Each option has it’s benefits, 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 ionic framework app.

If you need help developing your Ionic 4 application, I suggest you to take a look at Ionic 4 Full Starter App - The most complete Ionic 4 Template. It will save you lots of development and design time. Check some of the authentication screens available in the template.

Ionic 4 authentication
Ionic 4 log in
Auth in Ionic 4

Twitter Authentication in Ionic Framework

There are different ways to integrate Twitter authentication into your Ionic 4 app. However, only the way covered in this post uses the native approach which uses Twitter app 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 APIS and SDKS is simple, you need a piece (typically a Cordova plugin) that connects native APIS and SDKS with the javascript environment where the hybrid apps run. In this case we are going to use a cordova plugin to interact with the Twitter API.

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

Ionic Twitter Authentication

For this Ionic 4 example app you will need:

  • An Ionic app where you will integrate this login. You can either use a 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 Plugin to interact with the native Twitter App.

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

Our Ionic 4 demo app will look like this:

Get a Twitter Fabric API key

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.

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.

Create your Twitter app

In this section I will help you creating 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.

Install Twitter Connect Plugin

After you have your Fabric API key, and your Twitter App Consumer API keys, it’s time to install the cordova plugin into your Ionic 4 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 in this Ionic 4 tutorial:

  • Created an Ionic 4 app (or used a existing one)
  • Created a Fabric Account
  • Created a Twitter app (or used a existing one)
  • Installed Twitter Connect Plugin into your Ionic framework app

Add Twitter Log In and Log Out

Now we will go straight to the code so open your Ionic 4 project with your preferred code editor. Personally we use 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 NativeStorage to save the user data the first time they log in.

NativeStorage

NativeStorage 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 LocalStorage 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 4 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 4 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 functionalities

At this point you should have an Ionic 4 application with Twitter log in and log out functionalities working. To test the native implementation you need to test the app on a real device or in an emulator because cordova isn't available in the browser. If you are new to Ionic 4 development you can check how to Run your Ionic 4 app in different environments.

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

Did you know that we recently released Ionic 4 Full Starter App? It's an ionic 4 template that you can use to jump start your Ionic app development and save yourself hundreds of hours of design and development.

It is also ready to be a Progressive Web App and has a score of 100 in lighthouse. Try it on your phone as a PWA to see the magic!

Next Steps

After having Twitter authentication working in your Ionic v4 App you can focus on:

As you know we also sell beautiful ionic templates that you will find super useful as they save you hours of development, time and effort, while giving your projects a great design from scratch.

Why don’t you give a chance to our Ionic templates and apply this new knowledge?