Add Google Login to your React Apps in 10 mins
Sivanesh Shanmugam

Sivanesh Shanmugam @sivaneshs

About: A full-stack developer who loves to work with React.js, Express, Node.js, Redux, Javascript, PWA (Progressive Web Apps), Service workers, HTML, CSS, custom plugins in Babel, ESLint.

Location:
Madurai
Joined:
Mar 13, 2020

Add Google Login to your React Apps in 10 mins

Publish Date: Jun 27 '20
204 39

Alt Text

As a client developer, Creating apps with authentication might be a tedious process. As we need to handle authentication in the server and maintain the code. It does have some multiple cases to be maintained based on authentication mechanisms. (Basic, OAuth, etc) This blog helps you create a standalone backend less authentication for your react app. (or additionally) you can add server configurations too to authenticate with your server.

Why OAuth?

There are many reasons to use OAuth.

  • It is secure.
  • It doesn't require any credentials from the user. So no need of remembering multiple passwords.
  • Websites can also get essential information about users without spending much time in forms.

And specifically in our case, we don't need a server to authenticate or to get initial details of the user. 😉

I found a package which is called as react-google-login. Which provides simple mechanisms to add the Google login. You can either directly use their GoogleLogin component or you can use custom buttons. They also provide custom hooks like useGoogleLogin and useGoogleLogout so it will be easy for hooks lovers. (Both methods are described below)

The documentation they provided for this repository is awesome. But it's missing in some ways which are addressed in this blog. Like in detail, this blog helps in creating your application in the Google developer console and access clientId. The initial access_token obtained by this package will last for only one hour (For security reasons). And we need to iterate the process to access the new access_token using refresh_token. So you can make a production-ready application.

Steps

  • We need to create an application in the Google developer console. It provides clientId is used to identify your application for authentication details. Follow the below steps to get the client ID.
    1. Go to the Credentials page. ( if you are new, then create a project and follow these steps)
    2. Click Create credentials > OAuth client ID.
    3. Select the Web application type.
    4. Name your OAuth 2.0 client and click Create
  • Make sure you provided your domain and redirect URL. So that Google identifies the origin domain to which it can provide authentication. Alt Text

You can also add your local route for development. Now authentication setup in Google developer console is ready.

Lets code

Alt Text

Let's start with code. View my repo for accessing all code snippets. View Demo.

In your CRA install react-google-login package



npm i react-google-login


Enter fullscreen mode Exit fullscreen mode

Create a Login component that acts as a login button.

Alt Text

Similarly, create a Logout component

Alt Text

And add both in the required location of your app. Mine is in App.js

Alt Text

Now running your application will show profileObj in the console after logging in.

Congrats 🎉 You successfully made it 😃.

But after 1 hour your tokenId gets expired and hence it won't be used to access data or authenticate users. And hence we need to generate new tokenId. To make things work we need to add some additional cases in the Login component.

Alt Text

refreshTokenSetup function will take care of handling new tokenIds

Alt Text

This function checks for expires_in timestamp or our custom time (before the token expires) and calls reloadAuthResponse which is a util function provided by the library and it handles refresh_token and obtains new tokenId.

And Yeah 😃 Google login is added to your application successfully 🎉. So now you can access the user's name, photo URL, email, google Id, etc.

Additional

The above way uses the Google Login default button. You can also use your custom button using render prop.

Alt Text

We can also implement the same functionality using React Hooks. ❤️

LoginHooks.js

Alt Text

LogoutHooks.js

Alt Text

Server-side verification

If you wish to add Server side verification, Send the tokenId from client to server once onSuccess in Login component called.

So while handling authenticated routes, All requests from the client need to send the tokenId of the user in the header as Bearer token. At Server, once token received it must be verified either this tokenId

  • belongs to the current application.
  • Has it expired

You can do them manually but google suggests using their authentication library (Minimal effort required).

In the Server side (Here Node.js is used).

Install Google's official supported library google-auth-library package which is used to authenticate and verify OAuth apps.

Alt Text

Here, With our GOOGLE_CLIENT_ID sent it verifies whether this token belongs to our application or not. And it parses them and provides profile details in the getPayload function. And you can use them to access user data.

Any queries feel free to comment or chat with me personally in my social media accounts below.

I love to be connected with developers. 😃

Twitter | LinkedIn | GitHub

Comments 39 total

  • Ivan Chavez Escamilla
    Ivan Chavez EscamillaSep 21, 2020

    Great tutorial!
    One thing though, I believe the last image is the same as the one for LogoutHooks.
    There's no image for the Server Side verification code

  • Nick Trierweiler
    Nick TrierweilerSep 26, 2020

    This article is great! Thanks for sharing your example and this writeup! I personally would prefer code snippets over images but I am happy that you also shared the source code and I was able to get this working without too much trouble.

    There is a confused sentence above which could use refactoring. "To make things work we need to make things work we have to add some additional cases in the Login component."

    For others following this tutorial who get a failure message because of cookies try changing cookiePolicy={'single_host_origin'} to cookiePolicy='http://localhost:8000/' or whatever your localhost is. Adding the address in google wasn't enough. If I am mistaken please comment and I will try that too!

    • Sivanesh Shanmugam
      Sivanesh ShanmugamOct 26, 2020

      Thanks for your Feedback ❤ Sorry for the late response. And I changed that confused sentence.

  • olsard
    olsardOct 26, 2020

    Great! Thanks for sharing.
    There is a little issue with google icon in /public folder.
    It could be moved into /src instead

    import GoogleIcon from '../assets/icons/google.svg';
    <img src={GoogleIcon} alt="google login" className="icon" />

  • leoigel
    leoigelNov 26, 2020

    i got this error :
    Uncaught qw {message: "Missing required parameter 'client_id'", xM: true, stack: "gapi.auth2.ExternallyVisibleError: Missing require…tXYzGQD7-oxLsteJNmIlmx3Ysqg/cb=gapi.loaded_0:1:15"}

    • anoopvm
      anoopvmApr 5, 2022

      I ended up with this because of wrong case. I used clientid instead of "clientId"

  • Kiana-Alize Diaz
    Kiana-Alize DiazDec 6, 2020

    Hi under what file would we place server side verification?

  • Pratik Patil
    Pratik PatilJan 12, 2021

    The article is Awesome but I would like a little help. we already have a logout button and how can I add this to it without making any change to the existing logout code which gets executed onClick of that button

  • sathishkumar18594
    sathishkumar18594Jan 13, 2021

    Thanks for this article!!

    I'm getting "Failed to retrieve certificates: request to googleapis.com/oauth2/v1/certs failed, reason: self signed certificate in certificate chain" error message when I send google's token id to my mock API for further validations.

    Also noticed the token id does not have valid signature.

  • АнонимFeb 23, 2021

    [deleted]

    • Sivanesh Shanmugam
      Sivanesh ShanmugamFeb 23, 2021

      Yeah, I found them after some hours of debugging and found this helpful code. Thanks for your advice I'll follow them in forthcoming blogs. But actually, It's not your code. I copied the snippet from github.com/anthonyjgrove/react-goo... which he posted two months before your comment on the thread.

      I don't know the reason why you did copy the same code and posted it in the same thread, and claiming for a reference. 😂

  • Anton Istomin
    Anton IstominFeb 24, 2021

    Nice article. But it got me thinking: what about non-pure setTimeout and whether we can (or have to) extract it using redux-saga?

  • namansamra
    namansamraMar 9, 2021

    hi I have a query like if i have a database and then user tries to login with google then how can I find the user from the database .

    • Sivanesh Shanmugam
      Sivanesh ShanmugamMar 9, 2021

      With the token obtained, you can extract the user's information in which you can get email, Google user ID etc. With that I think you can find the user.

  • Jules Grenier
    Jules GrenierMar 31, 2021

    This is exactly what I was looking for!! Thank you so much! ❤️🦄

  • Manish Kumar
    Manish KumarApr 24, 2021

    Hi Sivanesh, This Article is very helpful for me, I was using this same code for google auth setup but I am getting one error - Token is getting expired after 1 hour. I have used refersh token setup also , but didn't get success . Error - "Uncaught exception 'Google_Auth_Exception' with message 'Token used too late, 1410345101 > 1410341783: " Can you please help me on this... Thanks @sivaneshs

  • Kalin Panmanee
    Kalin PanmaneeMay 24, 2021

    I'm trying to finish coding on the server side verification part but still struggle with a this problem. "TypeError: jwt.split is not a function " . Does anyone can help with this issue? By the way, I already got the token ID.

  • Akash Shyam
    Akash ShyamJul 15, 2021

    Great article! An absolute life saver. Could you expand a bit about using google login with our backend API. So in most applications, you have a custom contact form plus the social logins. I'd like to save the data like email, password etc to my backend(Mongoose + NodeJS).

    I could directly just send an API call to the backend in the onSuccess method and register the user in my DB. Is this the correct approach?

  • Michelle Ann Terrazas
    Michelle Ann TerrazasAug 3, 2021

    Thank you so much for this, it helped me immensely with my task for my project last week! :)

  • Dilip-Valiya99
    Dilip-Valiya99Aug 6, 2021

    refreshTokenSetup function is not working b'coz if someone will refresh page after login then setTimeOut() will be cleared also refreshTokenSetup function is only run after on success can we call it after expiry time of oath token?

  • Congying
    CongyingSep 8, 2021

    Thanks, it works fine for me. But I'm wondering how to get user info in another react components. Thanks in advance.

    • Sivanesh Shanmugam
      Sivanesh ShanmugamSep 9, 2021

      You can add it in a React context and use it anywhere inside your components.

  • Pratik Wadekar
    Pratik WadekarOct 14, 2021

    Can someone help me know how do I persist the login with react-google-login?

  • Himanshu Khaitan
    Himanshu KhaitanOct 20, 2021

    Hey! I am stuck with a mern stack auth problem. Can you help..?
    I am really stuck with auth stuff

  • chayagolo1
    chayagolo1Nov 4, 2021

    Hi
    This is amazing and works as wxpected in http.
    But when i changed the http protocol to https i got this error:
    "redirect_uri_mismatch".
    how can i resolve it?
    thank you so much!!

  • Sudharsan Srinivasan
    Sudharsan SrinivasanNov 7, 2021

    This is just perfect article for someone like me who is really new to UI world.
    Sivanesh shamnugam is the my saviour today.

  • codeuiandy
    codeuiandyNov 15, 2021

    Thanks @sivaneshs this was very helpfull and save me the time of debuging and all

  • Rahul More
    Rahul MoreNov 21, 2021

    How can i loader the google login button Until google send any response?

  • sd-roop
    sd-roopNov 24, 2021

    Thank you Shivanesh. On Logging in, I get a failure "popup_closed_by_user". Please advise.

  • joedotnot
    joedotnotDec 17, 2021

    Can you do other articles for login with Facebook, Github, Twitter, etc :)

  • Pragati Varshney
    Pragati VarshneyJan 4, 2022

    Hey,
    Its a great article for beginners like me.
    But, I am facing a challenge with log out, cookies and local storage are not getting cleared on log out and when I try to login the second time it auto-logins.
    can you please guide me how to fix or what could have gone wrong?

  • Hamza Ali
    Hamza AliJul 18, 2022

    Hey brother you teach tremendously,
    bur i am facing an issue whenever I click on the sign i link Model box will open but in the console there is an error like this one

    Login failed: res: {error: 'idpiframe_initialization_failed', details: 'You have created a new client application that use…i/web/guides/gis-migration) for more information.'}

    and when I click on loin with google button it show a pop up of my system emails & when i select on the email it loads couple or seconds and then pop up automatically shutdown and gives an error in the console like this

    Login failed: res: {error: 'popup_closed_by_user'}
    error: "popup_closed_by_user"
    [[Prototype]]: Object

  • Wary
    WaryJan 11, 2023

    The package react-google-login was deprecated!

  • Manoj Kumar
    Manoj KumarMar 2, 2023

    I'm happy with this article sir thanks to you

  • keiru
    keiruAug 22, 2023

    Thanks,
    But I got this error.
    {error: 'popup_closed_by_user'}
    Why?

Add comment