Google API + Firebase Auth

Here is a quick way to get Google APIs running with a Firebase Auth. If you have worked with Firebase Auth, you know that it is very simple to authenticate a new user with many providers, Github, Facebook, etc. Firebase even has a handy method for getting the results from the auth redirect and return a access token.

// Sign in using a redirect.
firebase.auth().getRedirectResult().then(function(result) {
if (result.credential) {
// This gives you a Google Access Token.
var token = result.credential.accessToken;
var user = result.user;

The problem is that this token will expire and if you are going to make any api request with the token you need a way to refresh it. Also if you are using the onAuthStateChanged(...) method you will not get an access token from the AuthProvider used to when creating the user with.

So a solution is to use the the Service Provider directly and pass those credentials to sign the user in to Firebase with firebase.auth().signInWithCredentia(…).

Add the Google API Script and load APIs.

var script = document.createElement('script');
script.type = 'text/javascript';
script.src = '';
script.onload = (e) => {
// init google api...
// bind this to your single page app...

In the onload callback we can now load any of the Google APIs we would like to use, passing in our credentials from the Google Developer Console.

Load Google APIs

}).then(() => {
// Kick off your app!

Authenticate Firebase User with Google Response

We can now check to see if the Google user is already signed in and if so get the auth response and login the user into Firebase. When using firebase.auth().signInWithCredential(…) Firebase will return the already existing user or create a new user with an unique id.

var googleUser = gapi.auth2.getAuthInstance().currentUser.get()
var isSignedIn = gapi.auth2.getAuthInstance().isSignedIn.get()
if (isSignedIn) {
// get the credentials from the google auth response
var idToken = googleUser.getAuthResponse().id_token;
var creds = firebase.auth.GoogleAuthProvider.credential(idToken);
   // auth in the user 
firebase.auth().signInWithCredential(creds).then((user) => {
      // you can use (user) or googleProfile to setup the user
var googleProfile = googleUser.getBasicProfile()
if (user) {
// do something with this user

I created an example using Vue, Vuex. You can checkout the demo here and download the project on Github.