Design Converter
Education
Software Development Executive - I
Developer Advocate
Last updated on Aug 5, 2024
Last updated on Feb 10, 2024
Securing user data and simplifying the login process is paramount in the modern web landscape. For developers building applications with React, integrating Google OAuth can enhance user experience by providing a familiar and trusted sign-in method.
This blog will guide you through implementing Google OAuth in your React app, leveraging the latest tools and best practices.
OAuth is an open standard for access delegation, commonly used to grant websites or applications access to user information without sharing password details. When you add a Google login to your React app, you essentially allow users to authenticate using their Google credentials. This streamlines the sign-in process and adds a layer of security, as Google manages the user's login information.
Implementing Google OAuth in a React app involves several steps, including setting up the OAuth consent screen, obtaining a client ID, and handling the authorization code flow. These steps ensure that users can successfully log in to your React app with their Google account, and you can safely obtain access tokens to access Google APIs on behalf of the user.
The Google Identity Services SDK is a powerful library that simplifies the integration of Google login into your React app. It provides a set of React components and hooks that handle the intricacies of the OAuth 2.0 protocol and the interactions with Google's authentication services.
To get started, you'll need to install the @react-oauth/google package, which is the official SDK designed for React applications:
1// Installation using npm 2npm install @react-oauth/google@latest 3 4// Installation using yarn 5yarn add @react-oauth/google@latest 6
Once installed, you can wrap your React app with the GoogleOAuthProvider component, providing it with the clientId obtained from the Google Cloud Console:
1import { GoogleOAuthProvider } from '@react-oauth/google'; 2 3function App() { 4 return ( 5 <GoogleOAuthProvider clientId="your-client-id"> 6 {/* Your app components go here */} 7 </GoogleOAuthProvider> 8 ); 9} 10 11export default App; 12
With the provider in place, you can now use the GoogleLogin component to render a sign-in with a Google button within your React app. This button will handle the user interactions and the authorization server's response, making it easy to implement the sign-in flow:
1import { GoogleLogin } from '@react-oauth/google'; 2 3function SignIn() { 4 const handleSuccess = (credentialResponse) => { 5 console.log(credentialResponse); 6 }; 7 8 const handleError = () => { 9 console.log('Login Failed'); 10 }; 11 12 return ( 13 <GoogleLogin 14 onSuccess={handleSuccess} 15 onError={handleError} 16 /> 17 ); 18} 19
You must configure the OAuth consent screen before users can sign in with Google to your React app. This is a crucial step in the setup process, as it defines the information your application will request from users and what they will agree to when they sign up or sign in.
The Google client ID is a unique identifier for your application that allows the Google OAuth service to recognize incoming requests from your React app. Obtaining this client ID is critical in setting up the authentication flow.
To register your web application and obtain the Google client ID, follow these steps:
After selecting the application type, you will be prompted to configure the consent screen if you still need to. This is where you specify the details that users will see when they are asked to grant permissions to your application.
The next step involves specifying the authorized JavaScript origins and redirecting URIs for your application. This security measure ensures that only requests from these origins are accepted by the Google OAuth service.
http://localhost
and http://localhost:<port_number>
.After filling in these details, save the credentials to generate your Google client ID. You will use this client ID in your React app to initialize the Google Identity Services SDK and create the Google login button:
1import { GoogleOAuthProvider } from '@react-oauth/google'; 2 3function App() { 4 return ( 5 <GoogleOAuthProvider clientId="your-google-client-id"> 6 {/* Your app components go here */} 7 </GoogleOAuthProvider> 8 ); 9} 10 11export default App; 12
You have successfully registered your web application with Google and obtained the Google client ID by completing these steps. This ID is essential for the next steps, where you will add the Google login functionality to your React app and handle the user authorization process.
Integrating Google login into your React app not only enhances the user experience by providing a quick and secure authentication method but also simplifies the management of user sessions.
You can now add the Google login button to your React app with the Google client ID. The @react-oauth/google package provides a GoogleLogin component that renders the button and manages the sign-in flow.
To add the Google button to your React app, you can include the GoogleLogin component in your sign-in component. Here's an example of how to do it:
1import { GoogleLogin } from '@react-oauth/google'; 2 3function SignIn() { 4 const handleSuccess = (credentialResponse) => { 5 // Handle the successful login here 6 console.log('Google login successful', credentialResponse); 7 }; 8 9 const handleError = () => { 10 // Handle login errors here 11 console.log('Google login failed'); 12 }; 13 14 return ( 15 <div> 16 <GoogleLogin 17 onSuccess={handleSuccess} 18 onError={handleError} 19 // Optionally, you can customize the button appearance and behavior 20 /> 21 </div> 22 ); 23} 24
By including this component, users will see a sign in with Google button in your React app. The Google Identity Services SDK will handle the user interactions and initiate the authorization request when they click this button.
When a user clicks the Google button, an authorization request is sent to Google's servers. If the user consents to sign in with their Google account, Google will respond with an authorization code or an access token, depending on the flow you've chosen (implicit or authorization code flow).
The below example assumes you are using the authorization code flow, which is recommended for web applications as it keeps the client secret secure on the server.
1import React from 'react'; 2import { GoogleLogin } from '@react-oauth/google'; 3 4function SignIn() { 5 // This function will be called upon a successful login 6 const handleSuccess = (credentialResponse) => { 7 // If you are using the authorization code flow, you will receive a code to be exchanged for an access token 8 const authorizationCode = credentialResponse.code; 9 10 // Send the authorization code to your backend server 11 fetch('/api/auth/google', { 12 method: 'POST', 13 headers: { 14 'Content-Type': 'application/json', 15 }, 16 body: JSON.stringify({ code: authorizationCode }), 17 }) 18 .then(response => response.json()) 19 .then(data => { 20 // Handle the response from your backend server 21 console.log('Login successful, backend response:', data); 22 }) 23 .catch(error => { 24 // Handle errors in communicating with your backend server 25 console.error('Error exchanging authorization code:', error); 26 }); 27 }; 28 29 const handleError = (errorResponse) => { 30 console.error('Google login failed', errorResponse); 31 }; 32 33 return ( 34 <div> 35 <GoogleLogin 36 onSuccess={handleSuccess} 37 onError={handleError} 38 useOneTap 39 flow="auth-code" 40 /> 41 </div> 42 ); 43} 44 45export default SignIn; 46
In the case of the authorization code flow, you will need to handle the exchange of the authorization code for an access token on your backend server. This is a more secure method, especially for web applications, as it keeps the client’s secret safe on the server.
Enhancing the user experience is key to increasing user engagement and satisfaction. Providing a seamless and visually appealing login interface can make a significant difference in authentication.
The @react-oauth/google package allows you to create a custom login button that aligns with your app's design. You can use the useGoogleLogin hook to initiate the login process when your custom button is clicked. Here's an example of how to implement a custom Google login button in a React function component:
1import React from 'react'; 2import { useGoogleLogin } from '@react-oauth/google'; 3 4function CustomLoginButton() { 5 const googleLogin = useGoogleLogin({ 6 onSuccess: (tokenResponse) => { 7 console.log('Google login successful', tokenResponse); 8 // You can now use the tokenResponse to authenticate the user in your app 9 }, 10 onError: () => { 11 console.error('Google login failed'); 12 // Handle login errors here 13 }, 14 flow: 'auth-code', // Use 'auth-code' for the authorization code flow 15 }); 16 17 return ( 18 <button onClick={() => googleLogin()}> 19 Sign in with Google 🚀 20 </button> 21 ); 22} 23 24export default CustomLoginButton; 25
In this code snippet, the useGoogleLogin hook is configured to handle the login process. When the custom button is clicked, the googleLogin function is invoked, triggering the Google login flow.
Google's One Tap login offers a frictionless sign-in experience that allows users to authenticate with just one tap, without being interrupted by a sign-up screen. To manage the One Tap prompt and popup UX, you can use the useGoogleOneTapLogin hook provided by the @react-oauth/google package. Here's how you can implement it:
1import React, { useEffect } from 'react'; 2import { useGoogleOneTapLogin } from '@react-oauth/google'; 3 4function OneTapLogin() { 5 useGoogleOneTapLogin({ 6 onSuccess: (credentialResponse) => { 7 console.log('One Tap login successful', credentialResponse); 8 // Handle the successful login here 9 }, 10 onError: () => { 11 console.error('One Tap login failed'); 12 // Handle login errors here 13 }, 14 // Additional configuration options can be provided here 15 auto_select: true, // Automatically prompt the user if they have a single session 16 }); 17 18 return ( 19 <div> 20 {/* Your component UI */} 21 </div> 22 ); 23} 24 25export default OneTapLogin; 26
In this example, the useGoogleOneTapLogin hook is configured inside a component to automatically prompt users for login if they have a single session available. The onSuccess and onError callbacks handle the login success and failure scenarios, respectively.
The authorization code flow is a secure method for authenticating users and obtaining access tokens that allow your application to access Google APIs on behalf of the user. This flow involves a two-step process where the client receives an authorization code, which is then exchanged for access and refresh tokens.
To safely obtain access tokens using the authorization code flow, your React app must interact with your backend server. The front end will handle the user authorization and receive an authorization code, which is then sent to the backend. The backend server will exchange this code for an access token and a refresh token from Google's authorization server.
Here's how you can handle the authorization code flow in your React app:
1import React from 'react'; 2import { useGoogleLogin } from '@react-oauth/google'; 3 4function SignIn() { 5 const googleLogin = useGoogleLogin({ 6 onSuccess: (codeResponse) => { 7 // Send the authorization code to the backend server 8 fetch('/api/auth/google', { 9 method: 'POST', 10 headers: { 11 'Content-Type': 'application/json', 12 }, 13 body: JSON.stringify({ code: codeResponse.code }), 14 }) 15 .then(response => response.json()) 16 .then(data => { 17 console.log('Backend response:', data); 18 }) 19 .catch(error => { 20 console.error('Error:', error); 21 }); 22 }, 23 onError: () => { 24 // Handle login errors here 25 console.error('Google login failed'); 26 }, 27 flow: 'auth-code', 28 }); 29 30 return ( 31 <button onClick={() => googleLogin()}> 32 Sign in with Google 33 </button> 34 ); 35} 36 37export default SignIn; 38
Once the authorization code is sent to your backend server, you must exchange it for tokens. This is done by making a POST request to Google's OAuth 2.0 token endpoint from your server. Here's an example of how this exchange might be handled in a Node.js backend using the fetch API:
1const fetch = require('node-fetch'); 2 3app.post('/api/auth/google', (req, res) => { 4 const { code } = req.body; 5 const client_id = 'YOUR_CLIENT_ID'; 6 const client_secret = 'YOUR_CLIENT_SECRET'; 7 const redirect_uri = 'YOUR_REDIRECT_URI'; 8 const grant_type = 'authorization_code'; 9 fetch('https://oauth2.googleapis.com/token', { 10 method: 'POST', 11 headers: { 12 'Content-Type': 'application/x-www-form-urlencoded', 13 }, 14 body: new URLSearchParams({ 15 code, 16 client_id, 17 client_secret, 18 redirect_uri, 19 grant_type, 20 }), 21 }) 22 .then(response => response.json()) 23 .then(tokens => { 24 // Send the tokens back to the frontend, or store them securely and create a session 25 res.json(tokens); 26 }) 27 .catch(error => { 28 // Handle errors in the token exchange 29 console.error('Token exchange error:', error); 30 res.status(500).json({ error: 'Internal Server Error' }); 31 }); 32}); 33
In this backend code, replace 'YOUR_CLIENT_ID', 'YOUR_CLIENT_SECRET', and 'YOUR_REDIRECT_URI' with your client ID, client secret, and redirect URI. The server receives the authorization code from the frontend, exchanges it for tokens, and then sends the tokens back to the frontend or creates a session for the user.
Properly managing user state and access is crucial for maintaining a secure and efficient user experience. Once a user has authenticated with Google, you must handle their session and ensure their credentials are stored securely.
After a user successfully signs in with Google and obtains their access token and possibly a refresh token, you'll need to decide how to store this information. User details and tokens are typically stored in a secure, server-side session. However, you may store the access token in the client-side state or local storage for easy access when making API requests.
Here's an example of how you might store user details and tokens in the local state of your React app after receiving them from your backend server:
1import React, { useState } from 'react'; 2 3function UserSession() { 4 const [user, setUser] = useState(null); 5 6 const handleLoginSuccess = (tokens) => { 7 // Assuming tokens contain user details and the access token 8 setUser({ 9 accessToken: tokens.access_token, 10 refreshToken: tokens.refresh_token, 11 profile: tokens.profile, // User profile information 12 }); 13 14 // Optionally, you might want to store the access token in local storage for persistence 15 localStorage.setItem('accessToken', tokens.access_token); 16 }; 17 18 return ( 19 <div> 20 {user ? ( 21 <div> 22 <h1>Welcome, {user.profile.name}</h1> 23 {/* Display user information and provide logout functionality */} 24 </div> 25 ) : ( 26 <button onClick={/* Trigger Google login here */}> 27 Sign in with Google 28 </button> 29 )} 30 </div> 31 ); 32} 33 34export default UserSession; 35
In this example, the user's access token, refresh token, and profile information are stored in the component's state using the useState hook. The access token is also stored locally to persist the user's session even if the page is reloaded.
To ensure a secure sign-in process with Google, it's essential to follow best practices such as:
Here's an example of how you might implement logout functionality in your React app:
1function UserSession() { 2 // ... (user state and handleLoginSuccess function) 3 4 const handleLogout = () => { 5 // Clear the user session and tokens 6 setUser(null); 7 localStorage.removeItem('accessToken'); 8 fetch('/api/auth/logout', { 9 method: 'POST', 10 // Include necessary headers and body if needed 11 }) 12 .then(() => { 13 console.log('User logged out'); 14 }) 15 .catch(error => { 16 console.error('Logout error:', error); 17 }); 18 }; 19 20 return ( 21 <div> 22 {user ? ( 23 <div> 24 <button onClick={handleLogout}>Logout</button> 25 </div> 26 ) : ( 27 // ... (sign-in button) 28 )} 29 </div> 30 ); 31} 32
In this logout function, the user's session is cleared from the state and local storage, and a request is made to the backend server to revoke the tokens, ensuring that the user is securely signed out.
Customizing the sign-up flow allows you to tailor the authentication experience to match your React app's branding and user expectations. You can customize the appearance of the Google sign-in button, the One Tap prompt, and other elements to create a cohesive look and feel.
For example, you can use the GoogleLogin component to render a customized sign-in button with specific properties for theme, size, and text:
1import React from 'react'; 2import { GoogleLogin } from '@react-oauth/google'; 3 4function CustomSignIn() { 5 return ( 6 <GoogleLogin 7 onSuccess={(response) => { 8 // Handle the successful response here 9 console.log('Custom Google login successful', response); 10 }} 11 onError={() => { 12 // Handle errors here 13 console.error('Custom Google login failed'); 14 }} 15 theme="filled_blue" 16 size="large" 17 text="continue_with" 18 /> 19 ); 20} 21 22export default CustomSignIn; 23
In this example, the GoogleLogin component is customized with a blue-filled theme, large size, and text that prompts the user to "continue with" Google. These properties allow you to modify the button's appearance to better integrate with your app's design.
Incorporating Google OAuth into your React app can significantly elevate user experience by providing a secure and streamlined sign-in process. We've covered the essentials—setting up the OAuth consent screen and obtaining your Google client ID to customize the login interface and manage user sessions. By leveraging the @react-oauth/google package, you can implement advanced features like One Tap login and customize the authentication flow to fit your app's unique needs. With these tools, you can create a user-friendly and secure authentication experience.
Tired of manually designing screens, coding on weekends, and technical debt? Let DhiWise handle it for you!
You can build an e-commerce store, healthcare app, portfolio, blogging website, social media or admin panel right away. Use our library of 40+ pre-built free templates to create your first application using DhiWise.