In this tutorial, we will learn how to implement Google Authentication in a web application using React and Node.js. Google Authentication allows users to log in to your website using their Google credentials. This tutorial will guide you through the process in seven steps.
To implement Google Authentication, you need to obtain a Google Client ID. Follow these steps to generate your own Client ID:
In your React application, you need to install the "@react-oauth/google" library, which provides a way to implement social login, including Google Authentication. Run the following query to install the library:
Command : npm install @react-oauth/google
To use Google Authentication in your React application, import the GoogleLogin component from the "@react-oauth/google" package. Add the following line of code to the top of your React component file:
Code : import { GoogleLogin } from "@react-oauth/google";
Next, use the GoogleLogin component as a parent for your Google login button. Pass the Google Client ID as a prop to the component. The GoogleLogin component has two callback functions: onResolve and onReject. The onResolve function is called when the login is successful, and you can make your login API call inside this function. The onReject function is called when something goes wrong with the authentication.
React Code :
<GoogleLogin
clientId={GOOGLE_CLIENT_ID}
onResolve={(response) => {
handleGoogleLogin(
response.data.email,
response.data.access_token,
response.data.name,
response.data.picture
);
}}
onReject={(error) => {
console.log(error);
}}
>
<img src={googleIcon} alt="" />
</GoogleLogin>
In the handleGoogleLogin function, you can handle the response received from Google after a successful login. Extract the necessary information from the response, such as the email, access token, name, and avatar image. You can then make a POST request to your backend API to verify the login and retrieve a JWT token.
React Code :
function handleGoogleLogin(email, token, name, avatarImg) {
postRequest({
url: "Your API URL",
data: { email, token, name, avatarImg },
})
.then((response) => {
console.log(response.data);
if (response.data.success) {
dispatch(userData(response.data.userData));
dispatch(setLogin(true));
toast.success(toCapitalCase(response.data.message));
navigate(-1);
} else {
toast.error(toCapitalCase(response.data.message));
}
})
.catch((e) => toast.error(e.message));
}
In your Node.js server, create a function to verify the Google token. This function uses the Google API to validate the access token received from the frontend. If the token is valid, it returns true; otherwise, it returns false. Here's an example function.
async function verifyGoogleToken(token) {
try {
const response = await axios.get(
`https://www.googleapis.com/oauth2/v3/tokeninfo?access_token=${token}`
);
const { sub, email } = response.data;
console.log("Token verified. User ID:", sub);
console.log("User email:", email);
return true;
} catch (error) {
console.error("Error verifying token:", error.message);
return false;
}
}
After verifying the Google token in your Node.js backend, you can pass the user information received from the frontend (email, token, etc.) to your API's body. Call the verifyGoogleToken function and check if the token is valid. If the token is valid, you can generate a JWT token and send it back to the frontend.
const privateKey = process.env.privateKey;
const expiresIn = process.env.expiresIn;
const token = jwt.sign({ userId: foundUser._id, email }, privateKey, {
expiresIn: expiresIn,
});
In this tutorial, we learned how to implement Google Authentication using React and Node.js. We covered the steps required to set up the frontend and backend for Google Authentication. By following these steps, you can add social login functionality to your website, allowing users to log in using their Google accounts.
I hope you found this tutorial helpful and that it helps you resolve any login issues you may have encountered. Happy coding!