Google Login With React
This article will teach you how to login users using Google in the frontend using React.
Last Updated: February 6, 2022
react
authorization
In continuation with my authorization series this video will show you how to add a Google Sign in button to your React Website and connect it to our Nest.js backend.
Get Started
Install the 'react-google-login' plugin by typing in npm install react-google-login
to your React project. Then where you want to login the user you can add the component provided by this library:
<GoogleLogin clientId={`${process.env.NEXT_PUBLIC_GOOGLE_CLIENT_ID}`} buttonText="Login with Google" onSuccess={async (response) => { // todo: write this function } onFailure={(response) => { alert("Error while logging in w/Google 2") }} cookiePolicy={"single_host_origin"} />
This component will handle the Google sign in. You must use the Google Client Id credential from Google Cloud Console retrieved in this tutorial. The onSuccess
callback will be called when the component has successfully gotten an access token from Google refering to the user that has signed in.
Connecting to our backend
Now we must create a function that handles our Google Access token and sends it to the backend to get a access and refresh token that we can use with our server. This function looks like the following:
// googleLogin.ts import {GoogleLoginResponse, GoogleLoginResponseOffline} from "react-google-login"; export default async ( response: GoogleLoginResponse | GoogleLoginResponseOffline ): Promise<{ accessToken: string; refreshToken: string; } | undefined> => { if ("accessToken" in response) { try { const token = response.accessToken; const result = await fetch("http://localhost:8080/auth/google/login", { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify({token}) }); const json = await result.json(); return {accessToken: json.accessToken, refreshToken: json.refreshToken}; } catch (e) { return undefined; } } else { return undefined; } }
This function simply makes a request to our existing Nest.js api to sign in the user. This function will also return undefined if no user corresponds with the Google access token.
Finishing up Component
Now we can add our onSuccess callback to look like:
onSuccess={async (response) => { const tokens = await googleLogin(response); if (!tokens) { alert("Error while logging in w/Google 1 ") } else { // put login logic (i.e. navigating to dashboard page, fetching user from backend // using the new access token, etc } }}
Inside of the else clause is where you could fetch the user from the backend using the new access token, save the refresh token in localstorage, etc.
Conclusion
Thank you for reading this article and if you enjoyed it share it on social media, or leave a comment below. As always the code is on Github (link is at the top of article).
Comments
Loading...