How to Implement Google Login in a React Capacitor App for Android

Lin Gash
2 min readSep 14, 2024

--

In this tutorial, we’ll use the @codetrix-studio/capacitor-google-auth library to implement Google login.

Create Client IDs in Google Developer Console

First, you need to create client credentials for both web and Android in the google developer console. This will give you the Client ID for both platforms.

For the Android app, you’ll need to provide a package name and SHA-1 key:

You can find the package name in the appid field of the capacitor.config.json file. And for the SHA-1 key, run the signingreport task in Gradle. This will display the MD5, SHA-1, and SHA-256 fingerprints of your app.

Update capacitor.config.json

Add the GoogleAuth plugin to the capacitor.config.json file. Make sure to use your Web Client ID for clientID and Android Client ID for androidClientId .

"GoogleAuth": {
"scopes": ["profile", "email"],
"clientId": "123456789000-cphs2re1de3nubom7as5m4b8ii9nmq72.apps.googleusercontent.com",
"androidClientId": "223456789000-cphs2re1de3nubom7as5m4b8ii9nmq72.apps.googleusercontent.com"
}

Add Client ID to strings.xml

In your Android project, go to the res/values/strings.xml file and add your Web Client ID as shown below:

 <string name="server_client_id">123456789000-cphs2re1de3nubom7as5m4b8ii9nmq72.apps.googleusercontent.com</string>

Create a Google Service Class

We will handle the Google login logic in a separate file for better organization. Here’s an example of how to do that.

import { GoogleAuth } from "@codetrix-studio/capacitor-google-auth";
import config from "../config";

export class GoogleService {
private static instance: GoogleService;

constructor() {
if (GoogleService.instance) {
return GoogleService.instance;
}
this.init();
GoogleService.instance = this;
}

private init() {
GoogleAuth.initialize({
clientId: config.google.clientKey, // Replace with your own web client key
scopes: ['profile', 'email'],
});
}

async login() {
try{
const response = await GoogleAuth.signIn();
console.log("response: " ,response);
return response.authentication.idToken;
}catch(err){
return null;
}
}

logout(){
GoogleAuth.signOut();
}
}

Use the Google Service in Your Code

You can now use the GoogleService class in your application like this:

const GL = new GoogleService();
await GL.login();

--

--

Lin Gash
Lin Gash

Written by Lin Gash

Programmer who is in love with Cosmos, Astrophysics, Science

No responses yet