Google OAuth2 using the new Google Identity Services SDK for React using Jwt-decode
Tags: googleoauth2, jwt, programming, react
Published: 2022-06-27 13:24:24

In this tutorial, we will be learning how to make sign-ups stress free and hassle-free by implementing authentication via Google OAuth2 using the new Google Identity Services SDK for React @react-oauth/google🚀.

You'll need

- To create-react-app React application that makes requests of your API 
- Installation of jwt-decode 
- Basic knowledge of React
- Node.js installed
- Code editor ( Visual Studio Code preferably )

## Setting  up Your Google Cloud project
To integrate Google Login into our React app, you need a Google Client ID. First, you'll need to create a Google Cloud project.
 

1. Create a project and choose a name for your project.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/l1sb2qmq3yevwyg8dnl0.png)

2. Once you have a project in place, proceed to Credentials - Create credentials - OAuth client ID.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/q2wm704lirw8xnp2dfi6.png)

3. You'll need to configure your OAuth consent screen. Choose external since we want to give access to everyone with a Google account. Google will then ask for the app's name plus some developer contact details.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/17dihkcz7dwkc5j99p1r.png)

4. Fill up the app registration form. For the most part, you can leave it blank.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/y0bxhrr5b2gbp5lugu63.png)
Choose the scope best suited for the app that you shall develop and fill all other necessary inputs according your application requirement.

We head back to Credentials - Create credentials - OAuth client ID. Choose the Web application type and we can provide all Authorised origins and redirect URL' s.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/e5rlpos9ipq9gf42g3la.png)
We will see our Google client ID and a client secret. We'll only need the client ID.

## Let's create our React App and Login Component
Once you have your Google Client ID, we start creating our React application to integrate Google Login.

We will start with create-react-app application, and add all necessary dependencies which are Google OAuth2 using the new Google Identity Services SDK for React @react-oauth/google🚀 and jwt-decode is a small browser library that helps decoding JWTs token which are Base64Url encoded.

Let's get started by running the following commands but make sure you have the necessary requirements for authenticating Google Login in React

- Node.js installed
- Code editor ( Visual Studio Code preferably )
- Google Client ID
- Basic knowledge of React

`npx create-react-app google-login
cd google-login
npm install @react-oauth/google jwt-decode react-router-dom`

Create a file named src/lib/GoogleLoginPage.js, with the following content:

```
import React from 'react';
import { FcGoogle } from 'react-icons/fc';
import { GoogleOAuthProvider } from '@react-oauth/google';
import { GoogleLogin } from '@react-oauth/google';

const GoogleLoginPage = () => {
  const responseGoogle = (response) => {
    console.log(response);
  }

  return (
    <div className="">
          <div className="">
            <GoogleOAuthProvider 
                clientId={`${process.env.REACT_APP_GOOGLE_API_TOKEN}`}
                >
             <GoogleLogin
              render={(renderProps) => (
                <button
                  type="button"
                  className=""
                  onClick={renderProps.onClick}
                  disabled={renderProps.disabled}
                >
                  <FcGoogle className="" /> Sign in with google
                </button>
              )}
              onSuccess={responseGoogle}
              onFailure={responseGoogle}
              cookiePolicy="single_host_origin"
            />
            </GoogleOAuthProvider>
          </div>
    </div>
  )
}

export default GoogleLoginPage
```
You can run npm start and check your console to receive your encoded token which we will decode using jwt-decode.

### Decoding Google Token using JWT-DECODE
Now that we have gotten our google response token, lets decode to get all necessary user info.

Still in the GoogleLoginPage.js let's update it

```
import React from 'react';
import { useNavigate } from 'react-router-dom';
import { FcGoogle } from 'react-icons/fc';
import { GoogleOAuthProvider } from '@react-oauth/google';
import { GoogleLogin } from '@react-oauth/google';
import { client } from '../client';
import jwt_decode from "jwt-decode";

const GoogleLoginPage = () => {
  const navigate = useNavigate();

  const responseGoogle = (response) => {
   //console.log(response);
    const userObject = jwt_decode(response.credential);
    //console.log(userObject);
    localStorage.setItem('user', JSON.stringify(userObject));
    const { name, sub, picture } = userObject;
    const doc = {
      _id: sub,
      _type: 'user',
      userName: name,
      image: picture,
    };
    client.createIfNotExists(doc).then(() => {
      navigate('/', { replace: true });
    });

  }

  return (
    <div className="">
          <div className="">
            <GoogleOAuthProvider 
                clientId={`${process.env.REACT_APP_GOOGLE_API_TOKEN}`}
                >
             <GoogleLogin
              render={(renderProps) => (
                <button
                  type="button"
                  className=""
                  onClick={renderProps.onClick}
                  disabled={renderProps.disabled}
                >
                  <FcGoogle className="" /> Sign in with google
                </button>
              )}
              onSuccess={responseGoogle}
              onFailure={responseGoogle}
              cookiePolicy="single_host_origin"
            />
            </GoogleOAuthProvider>
          </div>
    </div>
  )
}

export default GoogleLoginPage
```

Let's do a break down of what we just did.

After getting our Google Login response in our responseGoogle() , we created a variable to store the decoded token by importing jwt-decode package and calling the response we got from our google login.

Now that the token has been decoded, we can now get our user info, store it into our localStorage, de-structure the necessary needed info and send it to the database.

## Reconfigure Google OAuth

Lastly don't forget to configure all necessary Authorised JavaScript origins and Authorised redirect URIs in your Google API.

Hurray!!! we can now view, enjoy and test our finished application


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bff4aljyb0k02xw9l0ii.png)

[You can check out the live demo here](https://socials-website.netlify.app/
)

[You can view and download our source code at](https://github.com/OloriAsabi/socials)

## Conclusion
In this tutorial, we have learnt how to Authenticate User with the Google OAuth2 using the new Google Identity Services SDK for React @react-oauth/google🚀 and decoding token with JWT-DECODE.
 
I really hope you learnt something new today, don't forget to like, share and comment. 

## References

Google OAuth2 using the new [Google Identity Services SD](https://developers.google.com/identity/gsi/web)K for React [@react-oauth/google🚀](https://www.npmjs.com/package/@react-oauth/google)

[Decoding JWTs token which are Base64Url encoded.](https://www.npmjs.com/package/jwt-decode)