Google OAuth2 using the new Google Identity Services SDK for React 🚀

Last update: May 11, 2022

React OAuth2 | Google

Google OAuth2 using the new Google Identity Services SDK for React @react-oauth/google 🚀

Install

$ npm install @react-oauth/google

# or

$ yarn add @react-oauth/google

Seamless sign-in and sign-up flows

Sign In With Google

Add a personalized and customizable sign-up or sign-in button to your website.

personalized button

One-tap sign-up

Sign up new users with just one tap, without interrupting them with a sign-up screen. Users get a secure, token-based, passwordless account on your site, protected by their Google Account.

One-tap sign-up

Automatic sign-in

Sign users in automatically when they return to your site on any device or browser, even after their session expires.

Automatic sign-in

User authorization for Google APIs (with custom button)

OAuth 2.0 implicit and authorization code flows for web apps

The Google Identity Services JavaScript library helps you to quickly and safely obtain access tokens necessary to call Google APIs. Your web application, complete either the OAuth 2.0 implicit flow, or to initiate the authorization code flow which then finishes on your backend platform.

How to use

  1. Get your Google API client ID

Key Point: Add both http://localhost and http://localhost: to the Authorized JavaScript origins box for local tests or development.

  1. Configure your OAuth Consent Screen

  2. Wrap your application with GoogleOAuthProvider

">...;">
import { GoogleOAuthProvider } from '@react-oauth/google';

<GoogleOAuthProvider clientId="">...</GoogleOAuthProvider>;

Sign In With Google

import { GoogleLogin } from '@react-oauth/google';

<GoogleLogin
  onSuccess={credentialResponse => {
    console.log(credentialResponse);
  }}
  onError={() => {
    console.log('Login Failed');
  }}
/>;

One-tap

import { useGoogleOneTapLogin } from '@react-oauth/google';

useGoogleOneTapLogin({
    onSuccess: credentialResponse => {
        console.log(credentialResponse);
    },
    onError={() => {
        console.log('Login Failed')
    }}
});

or

import { GoogleLogin } from '@react-oauth/google';

<GoogleLogin
  onSuccess={credentialResponse => {
    console.log(credentialResponse);
  }}
  onError={() => {
    console.log('Login Failed');
  }}
  useOneTap
/>;

If you are using one tap login, when logging user out consider this issue may happen, to prevent it call googleLogout when logging user out from your application.

import { googleLogout } from '@react-oauth/google';

googleLogout();

Automatic sign-in

auto_select prop true

<GoogleLogin
    ...
    auto_select
/>

useGoogleOneTapLogin({
    ...
    auto_select
});

Custom login button (implicit & authorizaion code flow)

Implicit flow

import { useGoogleLogin } from '@react-oauth/google';

const login = useGoogleLogin({
  onSuccess: tokenResponse => console.log(tokenResponse),
});

<MyCustomButton onClick={() => login()}>
  Sign in with Google 🚀{' '}
</MyCustomButton>;

Authorization code flow

Requires backend to exchange code with access and refresh token.

import { useGoogleLogin } from '@react-oauth/google';

const login = useGoogleLogin({
  onSuccess: codeResponse => console.log(codeResponse),
  flow: 'auth-code',
});

<MyCustomButton onClick={() => login()}>
  Sign in with Google 🚀{' '}
</MyCustomButton>;

Checks if the user granted all the specified scope or scopes

import { hasGrantedAllScopesGoogle } from '@react-oauth/google';

const hasAccess = hasGrantedAllScopesGoogle(
  tokenResponse,
  'google-scope-1',
  'google-scope-2',
);

Checks if the user granted any of the specified scope or scopes

import { hasGrantedAnyScopeGoogle } from '@react-oauth/google';

const hasAccess = hasGrantedAnyScopeGoogle(
  tokenResponse,
  'google-scope-1',
  'google-scope-2',
);

API

GoogleOAuthProvider

Required Prop Type Description
clientId string Google API client ID
onScriptLoadSuccess function Callback fires on load gsi script success
onScriptLoadError function Callback fires on load gsi script failure

GoogleLogin

Required Prop Type Description
onSuccess (response: CredentialResponse) => void Callback fires with credential response after successfully login
onError function Callback fires after login failure
type standard | icon Button type type
theme outline | filled_blue | filled_black Button theme
size large | medium | small Button size
text signin_with | signup_with | continue_with | signin Button text. For example, "Sign in with Google", "Sign up with Google" or "Sign in"
shape rectangular | pill | circle | square Button shape
logo_alignment left | center Google logo alignment
width string button width, in pixels
locale `string If set, then the button language is rendered
useOneTap boolean Activate One-tap sign-up or not
promptMomentNotification (notification: PromptMomentNotification) => void PromptMomentNotification methods and description
cancel_on_tap_outside boolean Controls whether to cancel the prompt if the user clicks outside of the prompt
auto_select boolean Enables automatic selection on Google One Tap
ux_mode popup | redirect The Sign In With Google button UX flow
login_uri string The URL of your login endpoint
native_login_uri `string The URL of your password credential handler endpoint
native_callback (response: { id: string; password: string }) => void The JavaScript password credential handler function name
prompt_parent_id string The DOM ID of the One Tap prompt container element
nonce string A random string for ID tokens
context signin | signup | use The title and words in the One Tap prompt
state_cookie_domain string If you need to call One Tap in the parent domain and its subdomains, pass the parent domain to this attribute so that a single shared cookie is used
allowed_parent_origin string | string[] The origins that are allowed to embed the intermediate iframe. One Tap will run in the intermediate iframe mode if this attribute presents
intermediate_iframe_close_callback function Overrides the default intermediate iframe behavior when users manually close One Tap
itp_support boolean Enables upgraded One Tap UX on ITP browsers

useGoogleLogin (Both implicit & authorization code flow)

Required Prop Type Description
flow implicit | auth-code Two flows, implicit and authorization code are discussed. Both return an access token suitable for use with Google APIs
onSuccess (response: TokenResponse|CodeResponse) => void Callback fires with response (token | code) based on flow selected after successfully login
onError (errorResponse: {error: string; error_description?: string,error_uri?: string}) => void Callback fires after login failure
scope string A space-delimited list of scopes that are approved by the user
enable_serial_consent boolean defaults to true. If set to false, more granular Google Account permissions will be disabled for clients created before 2019. No effect for newer clients, since more granular permissions is always enabled for them.
hint string If your application knows which user should authorize the request, it can use this property to provide a hint to Google. The email address for the target user. For more information, see the login_hint field in the OpenID Connect docs
hosted_domain string If your application knows the Workspace domain the user belongs to, use this to provide a hint to Google. For more information, see the hd field in the OpenID Connect docs

useGoogleLogin (Extra implicit flow props)

Required Prop Type Description
prompt '' | none | consent | select_account defaults to 'select_account'. A space-delimited, case-sensitive list of prompts to present the user
state string Not recommended. Specifies any string value that your application uses to maintain state between your authorization request and the authorization server's response

useGoogleLogin (Extra authorization code flow props)

Required Prop Type Description
ux_mode popup | redirect The UX mode to use for the authorization flow. By default, it will open the consent flow in a popup. Valid values are popup and redirect
redirect_uri string Required for redirect UX. Determines where the API server redirects the user after the user completes the authorization flow The value must exactly match one of the authorized redirect URIs for the OAuth 2.0 client which you configured in the API Console and must conform to our Redirect URI validation rules. The property will be ignored by the popup UX
state string Recommended for redirect UX. Specifies any string value that your application uses to maintain state between your authorization request and the authorization server's response
select_account boolean defaults to 'false'. Boolean value to prompt the user to select an account

useGoogleOneTapLogin

Required Prop Type Description
onSuccess (response: CredentialResponse) => void Callback fires with credential response after successfully login
onError function Callback fires after login failure
promptMomentNotification (notification: PromptMomentNotification) => void PromptMomentNotification methods and description

GitHub

https://github.com/MomenSherif/react-oauth
You might also like...

A React wrapper for Typeform Embed SDK.

React wrapper for Typeform Embed SDK

Apr 4, 2022

Our SDK for the 3D rendering platform React-Three-Fiber.

Zappar for React Three Fiber This library allows you use Zappar's best-in-class AR technology with content built using the 3D rendering platform React

May 5, 2022

Foxpage SDK for JavaScript in the browser and Node.js.

Foxpage SDK for JavaScript in the browser and Node.js.

Nov 21, 2021

React project with Google Firebase API, create partys with admin view and user view. Users can ask topics to admin, and support other topics.

🧪 Tecnologias Esse projeto foi desenvolvido com as seguintes tecnologias: React Firebase TypeScript 🚀 Como executar Clone o projeto e acesse a pasta

Aug 27, 2021

Perguntei é uma plataforma para de criação de salas online onde qualquer pessoa autenticada com o Google pode enviar perguntas que são atualizadas na tela em tempo real.

Perguntei é uma plataforma para de criação de salas online onde qualquer pessoa autenticada com o Google pode enviar perguntas que são atualizadas na tela em tempo real.

💻 Sobre o projeto Perguntei é uma plataforma para você criar salas de Q&A com o seu próprio público, de uma forma muito organizada, só tendo acesso a

Oct 31, 2021

Hypersearch enhances all major search engines (Google, DuckDuckGo, Amazon, etc.) with results from trusted sources in the sidebar and removing results from blocked sources

Hypersearch enhances all major search engines (Google, DuckDuckGo, Amazon, etc.) with results from trusted sources in the sidebar and removing results from blocked sources

Hypersearch Coming soon for Firefox and Opera. Microsoft Edge users can install from the Chrome store. Hypersearch enhances all major search engines (

May 5, 2022

A drum machine built with React using the Create React App toolchain.

drum-machine A simple drum machine built with React using the Create React App toolchain. Getting Started Clone or download the repository. Open a com

Dec 30, 2021

Calculator-in-react - Calculator made in React.JS using Hooks as useReducer

Calculator-in-react - Calculator made in React.JS using Hooks as useReducer

Calculator-in-react - Calculator made in React.JS using Hooks as useReducer

Mar 9, 2022

React component to blur image backgrounds using canvas.

React component to blur image backgrounds using canvas.

React Blur React component for creating blurred backgrounds using canvas. Live demo Installation npm install react-blur --save Usage var Blur = requir

May 12, 2022
Comments
  • 1. I can't use custom login button

    I couldn't use it with custom button. It wants auth provider, but useGoogleLogin cannot be used in auth provider. Can you help me? It would be nice if the client id could be sent as options in useGoogleLogin.

    Reviewed by koraykavruk at 2022-05-11 07:00
This project is created to demonstrate the uses of various services delivery models with the help of a simple application.

CCET-IA-2 This project is created to demonstrate the uses of various services delivery models with the help of a simple application. Notes On Cloud No

Apr 1, 2022
A curated collection of publicly available resources on how technology and tech-savvy organizations around the world use Amazon Web Services (AWS)
A curated collection of publicly available resources on how technology and tech-savvy organizations around the world use Amazon Web Services (AWS)

How they AWS | A curated collection of publicly available resources on how technology and tech-savvy organizations around the world use Amazon Web Ser

May 12, 2022
Calypso is the new WordPress.com front-end – a beautiful redesign of the WordPress dashboard using a single-page web application
Calypso is the new WordPress.com front-end – a beautiful redesign of the WordPress dashboard using a single-page web application

Calypso is the new WordPress.com front-end – a beautiful redesign of the WordPress dashboard using a single-page web application, powered by the WordPress.com REST API. Calypso is built for reading, writing, and managing all of your WordPress sites in one place.

May 9, 2022
A description of React's new core algorithm, React Fiber

React Fiber Architecture Introduction React Fiber is an ongoing reimplementation of React's core algorithm. It is the culmination of over two years of

May 11, 2022
Compares Discord libraries and their support of new API features. Made with React, Next.js, and Bulma.

Compares Discord libraries and their support of new API features. Made with React, Next.js, and Bulma.

May 9, 2022
Appends a new DOM node to the end of the `document.body` and renders it's child React tree into it.

@react-lit/portal Appends a new DOM node to the end of the document.body and renders it's child React tree into it. Useful to break out of the DOM hie

Dec 9, 2021
A react app lets users find new beers similar to the ones they like
A react app lets users find new beers similar to the ones they like

Hold my beer Your digital beer connoisseur! Hold my beer is an app to demonstrate the usefulness of TF-IDF (Term Frequency-Inverse Document Frequency)

Dec 18, 2021
Glaze is a new tab extension , based primarily on productivity and great UX
Glaze is a new tab extension , based primarily on productivity and great UX

Glaze is a new tab extension , based primarily on productivity and great UX, it is still in early phase of development, I have only pushed the create-react-app build for now, but I plan to push the extension version along with build instructions in a few days. Currently glaze has the functionality of setting a nice backgorund with a clock + greeting feature.

Oct 18, 2021
❄️ Winterly Tab ❄️ Beautifully replace new tab screen with winter themed background.
❄️ Winterly Tab ❄️ Beautifully replace new tab screen with winter themed background.

Beautifully replace the new-tab page in your web browser with winter-themed background. It's free & open source!

Jan 23, 2022
A verification library for COVID-19 Vaccine Passes in New Zealand

A JavaScript implementation of NZ COVID Pass verification, New Zealand's proof of COVID-19 vaccination solution,

Feb 17, 2022