### Install @react-oauth/google Source: https://github.com/momensherif/react-oauth/blob/master/packages/@react-oauth/google/README.md Install the library using npm or yarn. ```sh npm install @react-oauth/google@latest ``` ```sh yarn add @react-oauth/google@latest ``` -------------------------------- ### Install @react-oauth/github Source: https://github.com/momensherif/react-oauth/blob/master/packages/@react-oauth/github/README.md Install the library using npm, yarn, or pnpm. ```bash npm install @react-oauth/github # or yarn add @react-oauth/github # or pnpm add @react-oauth/github ``` -------------------------------- ### Build and Development Commands Source: https://github.com/momensherif/react-oauth/blob/master/CONTRIBUTING.md Commands to build all packages or start development mode. Use `yarn dev:google` to start development for the Google package specifically. ```bash # Build all packages yarn build # Start development mode for all packages yarn dev # Start development mode for Google package only yarn dev:google ``` -------------------------------- ### Install Google OAuth Package Source: https://github.com/momensherif/react-oauth/blob/master/README.md Use npm or yarn to add the Google OAuth package to your project. This is the first step before integrating Google Sign-In. ```bash npm install @react-oauth/google # or yarn add @react-oauth/google ``` -------------------------------- ### Install GitHub OAuth Package Source: https://github.com/momensherif/react-oauth/blob/master/README.md Use npm or yarn to add the GitHub OAuth package to your project. This package provides a modern React hook for GitHub authentication. ```bash npm install @react-oauth/github # or yarn add @react-oauth/github ``` -------------------------------- ### Conventional Commits Format Examples Source: https://github.com/momensherif/react-oauth/blob/master/CONTRIBUTING.md Examples illustrating the Conventional Commits format for commit messages, including type, scope, and subject. This format is used for clear and consistent commit history. ```bash feat(google): add custom button themes fix(github): handle popup blocked error docs(repo): update contributing guide ``` -------------------------------- ### Initialize Google Tag Manager in React Source: https://github.com/momensherif/react-oauth/blob/master/apps/playground/public/index.html This snippet should be placed in your main application file (e.g., index.js or App.js) to ensure Google Tag Manager is loaded when your application starts. It configures the dataLayer and injects the GTM script. ```javascript (function (w, d, s, l, i) { w[l] = w[l] || []; w[l].push({ 'gtm.start': new Date().getTime(), event: 'gtm.js' }); var f = d.getElementsByTagName(s)[0], j = d.createElement(s), dl = l != 'dataLayer' ? '&l=' + l : ''; j.async = true; j.src = 'https://www.googletagmanager.com/gtm.js?id=' + i + dl; f.parentNode.insertBefore(j, f); })(window, document, 'script', 'dataLayer', 'GTM-MM83JN6'); ``` -------------------------------- ### Initiate GitHub Login with useGitHubLogin Hook Source: https://context7.com/momensherif/react-oauth/llms.txt Use this hook to initiate the GitHub OAuth flow via a popup. Configure client ID, redirect URI, and desired scopes. The authorization code must be exchanged server-side. ```tsx import { useGitHubLogin, OAuthError, OAuthErrorCode } from '@react-oauth/github'; import axios from 'axios'; function GitHubLoginButton() { const { initiateGitHubLogin, isLoading } = useGitHubLogin({ clientId: process.env.REACT_APP_GITHUB_CLIENT_ID!, redirectUri: 'http://localhost:3000/callback', scope: 'user:email,read:org', // default: 'user:email' allowSignup: true, // allow new GitHub account creation popupOptions: { width: 600, height: 700 }, // state is auto-generated for CSRF protection; override if needed: // state: 'my-custom-csrf-token', onRequest: () => console.log('OAuth flow started'), onSuccess: async response => { // response: { code: string; state?: string } // Exchange code server-side β€” NEVER do this in the browser const { data } = await axios.post('/api/auth/github', { code: response.code, }); console.log('Authenticated user:', data.user); }, onError: error => { if (OAuthError.isOAuthError(error)) { switch (error.code) { case OAuthErrorCode.POPUP_CLOSED: // 'OA001' console.warn('User closed the GitHub login popup'); break; case OAuthErrorCode.POPUP_BLOCKED: // 'OA002' alert('Please allow popups for this site to sign in with GitHub'); break; case OAuthErrorCode.STATE_MISMATCH: // 'OA003' console.error('CSRF state mismatch β€” possible attack, aborting'); break; case OAuthErrorCode.MISSING_CODE: // 'OA004' console.error('Authorization code missing from GitHub response'); break; } } else { console.error('Unexpected error:', error.message); } }, }); return ( ); } ``` -------------------------------- ### Sign In With Google Button Source: https://github.com/momensherif/react-oauth/blob/master/packages/@react-oauth/google/README.md Render a default Google sign-in button. Handles success and error callbacks. ```jsx import { GoogleLogin } from '@react-oauth/google'; { console.log(credentialResponse); }} onError={() => { console.log('Login Failed'); }} />; ``` -------------------------------- ### useGoogleOneTapLogin Hook Source: https://github.com/momensherif/react-oauth/blob/master/packages/@react-oauth/google/README.md Implement one-tap sign-up and automatic sign-in functionality using the useGoogleOneTapLogin hook. ```APIDOC ## useGoogleOneTapLogin Hook ### Description Implement one-tap sign-up and automatic sign-in functionality using the `useGoogleOneTapLogin` hook. It provides `onSuccess` and `onError` callbacks for handling the authentication response. ### Usage ```jsx import { useGoogleOneTapLogin } from '@react-oauth/google'; useGoogleOneTapLogin({ onSuccess: credentialResponse => { console.log(credentialResponse); }, onError: () => { console.log('Login Failed'); }, }); ``` ### Alternative Usage with GoogleLogin ```jsx import { GoogleLogin } from '@react-oauth/google'; { console.log(credentialResponse); }} onError={() => { console.log('Login Failed'); }} useOneTap />; ``` ``` -------------------------------- ### Configure GoogleOAuthProvider Source: https://github.com/momensherif/react-oauth/blob/master/packages/@react-oauth/google/README.md Wrap your application with GoogleOAuthProvider and provide your Google client ID. ```jsx import { GoogleOAuthProvider } from '@react-oauth/google'; ...; ``` -------------------------------- ### Automatic Sign-in Prop Source: https://github.com/momensherif/react-oauth/blob/master/packages/@react-oauth/google/README.md Enable automatic sign-in for returning users by setting the `auto_select` prop to `true`. ```APIDOC ## Automatic Sign-in Prop ### Description Enable automatic sign-in for returning users by setting the `auto_select` prop to `true` on either the `GoogleLogin` component or within the `useGoogleOneTapLogin` hook configuration. ### Usage with GoogleLogin ```jsx ``` ### Usage with useGoogleOneTapLogin ```jsx useGoogleOneTapLogin({ ... auto_select }); ``` ``` -------------------------------- ### useGoogleLogin Hook (Implicit Flow) Source: https://github.com/momensherif/react-oauth/blob/master/packages/@react-oauth/google/README.md Initiate the OAuth 2.0 implicit flow for user authorization with a custom login button. ```APIDOC ## useGoogleLogin Hook (Implicit Flow) ### Description Use the `useGoogleLogin` hook to initiate the OAuth 2.0 implicit flow. This is suitable for obtaining access tokens to call Google APIs directly from the client-side. It requires a backend to exchange the code with access and refresh tokens. ### Usage ```jsx import { useGoogleLogin } from '@react-oauth/google'; const login = useGoogleLogin({ onSuccess: tokenResponse => console.log(tokenResponse), }); login()}>Sign in with Google πŸš€; ``` ``` -------------------------------- ### Basic GitHub OAuth Integration Source: https://github.com/momensherif/react-oauth/blob/master/README.md Implement GitHub authentication using the useGitHubLogin hook. Provide your GitHub client ID and redirect URI. The onSuccess callback receives the authorization code. ```jsx import { useGitHubLogin } from '@react-oauth/github'; function LoginButton() { const { initiateGitHubLogin, isLoading } = useGitHubLogin({ clientId: 'your-github-client-id', redirectUri: 'http://localhost:3000/callback', onSuccess: response => { console.log('Authorization code:', response.code); // Exchange code for access token on your backend }, onError: error => { console.error('Authentication failed:', error); }, }); return ( ); } ``` -------------------------------- ### useGitHubLogin Hook Source: https://context7.com/momensherif/react-oauth/llms.txt Initiates GitHub OAuth via a centered popup window. It polls the popup for the redirect, extracts the authorization code and state, verifies CSRF state, and calls onSuccess. The authorization code must be exchanged server-side. ```APIDOC ## useGitHubLogin ### Description Initiates GitHub OAuth via a centered popup window. Polls the popup every 500 ms for the redirect back to `redirectUri`, extracts the authorization `code` and `state`, verifies CSRF state, then calls `onSuccess`. The authorization code must be exchanged server-side β€” never expose your `GITHUB_CLIENT_SECRET` in the browser. Returns `{ initiateGitHubLogin, isLoading }`. ### Usage ```tsx import { useGitHubLogin, OAuthError, OAuthErrorCode } from '@react-oauth/github'; import axios from 'axios'; function GitHubLoginButton() { const { initiateGitHubLogin, isLoading } = useGitHubLogin({ clientId: process.env.REACT_APP_GITHUB_CLIENT_ID!, redirectUri: 'http://localhost:3000/callback', scope: 'user:email,read:org', // default: 'user:email' allowSignup: true, // allow new GitHub account creation popupOptions: { width: 600, height: 700 }, // state is auto-generated for CSRF protection; override if needed: // state: 'my-custom-csrf-token', onRequest: () => console.log('OAuth flow started'), onSuccess: async response => { // response: { code: string; state?: string } // Exchange code server-side β€” NEVER do this in the browser const { data } = await axios.post('/api/auth/github', { code: response.code, }); console.log('Authenticated user:', data.user); }, onError: error => { if (OAuthError.isOAuthError(error)) { switch (error.code) { case OAuthErrorCode.POPUP_CLOSED: // 'OA001' console.warn('User closed the GitHub login popup'); break; case OAuthErrorCode.POPUP_BLOCKED: // 'OA002' alert('Please allow popups for this site to sign in with GitHub'); break; case OAuthErrorCode.STATE_MISMATCH: // 'OA003' console.error('CSRF state mismatch β€” possible attack, aborting'); break; case OAuthErrorCode.MISSING_CODE: // 'OA004' console.error('Authorization code missing from GitHub response'); break; } } else { console.error('Unexpected error:', error.message); } }, }); return ( ); } ``` ### Parameters - **clientId** (string) - Required - Your GitHub application client ID. - **redirectUri** (string) - Required - The URI to redirect to after authorization. - **scope** (string) - Optional - The OAuth scopes to request (default: 'user:email'). - **allowSignup** (boolean) - Optional - Allows new GitHub account creation (default: false). - **popupOptions** (object) - Optional - Options for the popup window (e.g., `{ width: 600, height: 700 }`). - **state** (string) - Optional - Custom CSRF state token. If not provided, it's auto-generated. - **onRequest** (function) - Optional - Callback function executed when the OAuth flow is initiated. - **onSuccess** (function) - Required - Callback function executed upon successful authorization, receiving `{ code: string; state?: string }`. - **onError** (function) - Optional - Callback function executed if an error occurs during the OAuth flow. ### Returns - **initiateGitHubLogin** (function) - Function to call to start the GitHub login process. - **isLoading** (boolean) - Indicates if the login process is currently in progress. ``` -------------------------------- ### Basic GitHub Login Button Source: https://github.com/momensherif/react-oauth/blob/master/packages/@react-oauth/github/README.md Implement a custom button to initiate GitHub OAuth flow using the useGitHubLogin hook. Ensure your clientId and redirectUri are correctly configured. ```tsx import { useGitHubLogin } from '@react-oauth/github'; function CustomLoginButton() { const { initiateGitHubLogin, isLoading } = useGitHubLogin({ clientId: 'your-github-client-id', redirectUri: 'http://localhost:3000/callback', onSuccess: response => { console.log('Authorization code:', response.code); }, onError: error => { console.error('Authentication failed:', error); }, }); return ( ); } ``` -------------------------------- ### Custom Login Button - Implicit Flow Source: https://github.com/momensherif/react-oauth/blob/master/packages/@react-oauth/google/README.md Use the useGoogleLogin hook to create a custom login button that initiates the implicit OAuth 2.0 flow. ```jsx import { useGoogleLogin } from '@react-oauth/google'; const login = useGoogleLogin({ onSuccess: tokenResponse => console.log(tokenResponse), }); login()}>Sign in with Google πŸš€; ``` -------------------------------- ### Create a Changeset Source: https://github.com/momensherif/react-oauth/blob/master/CONTRIBUTING.md Generate a changeset file for user-facing changes to manage versioning and changelogs. This is part of the version management process using Changesets. ```bash yarn changeset ``` -------------------------------- ### Automatic Sign-in Prop Source: https://github.com/momensherif/react-oauth/blob/master/packages/@react-oauth/google/README.md Enable automatic sign-in for returning users by setting the `auto_select` prop to `true` on either the `GoogleLogin` component or the `useGoogleOneTapLogin` hook. ```jsx useGoogleOneTapLogin({ ... auto_select }); ``` -------------------------------- ### One-tap Login Hook Source: https://github.com/momensherif/react-oauth/blob/master/packages/@react-oauth/google/README.md Use the useGoogleOneTapLogin hook for a one-tap sign-in experience. Handles success and error callbacks. ```jsx import { useGoogleOneTapLogin } from '@react-oauth/google'; useGoogleOneTapLogin({ onSuccess: credentialResponse => { console.log(credentialResponse); }, onError: () => { console.log('Login Failed'); }, }); ``` -------------------------------- ### Google Login Button with Implicit Flow Source: https://context7.com/momensherif/react-oauth/llms.txt Use this for obtaining an access token directly in the browser. The `login` function accepts optional overrides like `prompt` at call time. ```tsx import { useGoogleLogin, hasGrantedAllScopesGoogle } from '@react-oauth/google'; import axios from 'axios'; // ── Implicit flow (access token in browser) ────────────────────────────────── function ImplicitLoginButton() { const login = useGoogleLogin({ flow: 'implicit', // default scope: 'https://www.googleapis.com/auth/calendar.readonly', prompt: 'consent', // '' | 'none' | 'consent' | 'select_account' hint: 'user@example.com', onSuccess: async tokenResponse => { // tokenResponse: { access_token, expires_in, scope, token_type, ... } const calendarGranted = hasGrantedAllScopesGoogle( tokenResponse, 'https://www.googleapis.com/auth/calendar.readonly', ); if (!calendarGranted) { console.warn('Calendar scope was not granted'); return; } const { data } = await axios.get( 'https://www.googleapis.com/calendar/v3/calendars/primary/events', { headers: { Authorization: `Bearer ${tokenResponse.access_token}` } }, ); console.log('Calendar events:', data.items); }, onError: err => console.error('Login failed:', err.error, err.error_description), onNonOAuthError: err => { // err.type: 'popup_failed_to_open' | 'popup_closed' | 'unknown' if (err.type === 'popup_closed') console.warn('User closed the popup'); }, }); return ; } ``` -------------------------------- ### GitHub Login with Error Handling Source: https://github.com/momensherif/react-oauth/blob/master/packages/@react-oauth/github/README.md Initiates GitHub login using the useGitHubLogin hook and handles various OAuth error codes. Ensure you have the necessary imports and a client ID. ```tsx import { useGitHubLogin, OAuthError, OAuthErrorCode, } from '@react-oauth/github'; function LoginButton() { const { initiateGitHubLogin, isLoading } = useGitHubLogin({ clientId: 'your-client-id', onSuccess: handleSuccess, onError: error => { if (OAuthError.isOAuthError(error)) { switch (error.code) { case OAuthErrorCode.POPUP_CLOSED: console.log('User closed the popup'); // Handle popup closed break; case OAuthErrorCode.POPUP_BLOCKED: console.log('Popup blocked by browser'); // Prompt user to enable popups break; case OAuthErrorCode.STATE_MISMATCH: console.log('State mismatch - possible CSRF attack'); // Handle security issue break; case OAuthErrorCode.MISSING_CODE: console.log('Authorization code not found in response'); // Handle missing code break; default: console.log('Other OAuth error:', error.message); } } else { // Handle other errors console.error('Unexpected error:', error); } }, }); return ( ); } ``` -------------------------------- ### GoogleOAuthProvider Configuration Source: https://github.com/momensherif/react-oauth/blob/master/packages/@react-oauth/google/README.md Wrap your application with GoogleOAuthProvider and provide your Google API client ID. ```APIDOC ## GoogleOAuthProvider Configuration ### Description Wrap your application with `GoogleOAuthProvider` and provide your Google API client ID to enable Google OAuth functionality. ### Usage ```jsx import { GoogleOAuthProvider } from '@react-oauth/google'; ...; ``` ``` -------------------------------- ### useGoogleOneTapLogin Source: https://context7.com/momensherif/react-oauth/llms.txt Triggers the Google One Tap sign-in prompt without rendering a button, suitable for auto-signing-in users on page load. Can be imperatively cancelled by passing `disabled={true}`. ```APIDOC ## useGoogleOneTapLogin ### Description Triggers the Google One Tap sign-in prompt without rendering any button. Useful for auto-signing-in users on page load. Returns `void`; pass `disabled={true}` to imperatively cancel the prompt (e.g., when the user is already logged in). ### Usage Example ```tsx import { useGoogleOneTapLogin } from '@react-oauth/google'; import { jwtDecode } from 'jwt-decode'; function App() { const isLoggedIn = false; // replace with your auth state useGoogleOneTapLogin({ onSuccess: credentialResponse => { const user = jwtDecode<{ email: string; name: string; picture: string }> (credentialResponse.credential!), console.log('One Tap success:', user.email, user.name); // Store session, redirect, etc. }, onError: () => console.error('One Tap failed'), disabled: isLoggedIn, // cancels prompt when user is already signed in auto_select: true, // silently sign in returning users cancel_on_tap_outside: false, hosted_domain: 'example.com', // restrict to Workspace accounts promptMomentNotification: n => { if (n.isDismissedMoment()) { console.log('Dismissed:', n.getDismissedReason()); // 'credential_returned' | 'cancel_called' | 'flow_restarted' } }, }); return
{/* rest of app */}
; } ``` ``` -------------------------------- ### Basic Google OAuth Integration Source: https://github.com/momensherif/react-oauth/blob/master/README.md Integrate Google Sign-In into your React application using GoogleOAuthProvider and GoogleLogin components. Ensure you replace '' with your actual Google Client ID. ```jsx import { GoogleOAuthProvider, GoogleLogin } from '@react-oauth/google'; function App() { return ( { console.log(credentialResponse); }} onError={() => { console.log('Login Failed'); }} /> ); } ``` -------------------------------- ### useGoogleLogin Hook (Authorization Code Flow) Source: https://github.com/momensherif/react-oauth/blob/master/packages/@react-oauth/google/README.md Initiate the OAuth 2.0 authorization code flow for secure user authorization, requiring backend token exchange. ```APIDOC ## useGoogleLogin Hook (Authorization Code Flow) ### Description Use the `useGoogleLogin` hook with `flow: 'auth-code'` to initiate the OAuth 2.0 authorization code flow. This flow is more secure as it requires a backend to exchange the authorization code for access and refresh tokens. ### Usage ```jsx import { useGoogleLogin } from '@react-oauth/google'; const login = useGoogleLogin({ onSuccess: codeResponse => console.log(codeResponse), flow: 'auth-code', }); login()}>Sign in with Google πŸš€; ``` ### Note This flow requires a backend service to exchange the received code with access and refresh tokens. ``` -------------------------------- ### useGitHubLogin Hook Parameters Source: https://github.com/momensherif/react-oauth/blob/master/packages/@react-oauth/github/README.md Defines the parameters for the useGitHubLogin hook, including required client ID and callbacks, and optional redirect URI, scopes, and popup configurations. ```typescript useGitHubLogin(options: UseGitHubLoginOptions): UseGitHubLoginReturn ``` -------------------------------- ### GoogleLogin Component Source: https://github.com/momensherif/react-oauth/blob/master/packages/@react-oauth/google/README.md Use the GoogleLogin component for a customizable sign-in button with success and error handlers. ```APIDOC ## GoogleLogin Component ### Description Use the `GoogleLogin` component to render a customizable sign-in button. It accepts `onSuccess` and `onError` callbacks to handle the authentication response. ### Usage ```jsx import { GoogleLogin } from '@react-oauth/google'; { console.log(credentialResponse); }} onError={() => { console.log('Login Failed'); }} />; ``` ### Notes For popup mode, ensure the correct [Cross Origin Opener Policy](https://developers.google.com/identity/gsi/web/guides/get-google-api-clientid#cross_origin_opener_policy) is set to `same-origin-allow-popups` to avoid the blank window issue. ``` -------------------------------- ### One-tap Login with GoogleLogin Component Source: https://github.com/momensherif/react-oauth/blob/master/packages/@react-oauth/google/README.md Enable one-tap login directly on the GoogleLogin component by setting the `useOneTap` prop. ```jsx import { GoogleLogin } from '@react-oauth/google'; { console.log(credentialResponse); }} onError={() => { console.log('Login Failed'); }} useOneTap />; ``` -------------------------------- ### Linting and Formatting Commands Source: https://github.com/momensherif/react-oauth/blob/master/CONTRIBUTING.md Commands to check code formatting and automatically fix issues using Prettier. Formatting is applied automatically on commit. ```bash # Check code formatting yarn prettier:check # Auto-fix formatting issues yarn prettier:fix ``` -------------------------------- ### Custom Login Button - Authorization Code Flow Source: https://github.com/momensherif/react-oauth/blob/master/packages/@react-oauth/google/README.md Use the useGoogleLogin hook with the 'auth-code' flow to initiate the authorization code flow. This requires a backend to exchange the code for tokens. ```jsx import { useGoogleLogin } from '@react-oauth/google'; const login = useGoogleLogin({ onSuccess: codeResponse => console.log(codeResponse), flow: 'auth-code', }); login()}>Sign in with Google πŸš€; ``` -------------------------------- ### useGitHubLogin Options Interface Source: https://github.com/momensherif/react-oauth/blob/master/packages/@react-oauth/github/README.md Interface detailing the options available for the useGitHubLogin hook, such as clientId, onSuccess, onError, and redirectUri. ```typescript interface UseGitHubLoginOptions { clientId: string; redirectUri?: string; scope?: string; popupOptions?: PopupWindowOptions; state?: string; // Auto-generated if not provided allowSignup?: boolean; onSuccess: (response: OAuthResponse) => void; onError: (error: Error) => void; onRequest?: () => void; } ``` -------------------------------- ### useGoogleLogin (Implicit Flow Props) Source: https://github.com/momensherif/react-oauth/blob/master/packages/@react-oauth/google/README.md Props available for the `useGoogleLogin` hook when using the implicit OAuth flow. These props control user interaction during the login process. ```APIDOC ## useGoogleLogin (Implicit Flow Props) ### Description Props to customize the user experience for the implicit OAuth flow. ### Parameters #### Query Parameters - **prompt** (string) - Optional - Defaults to 'select_account'. A space-delimited, case-sensitive list of prompts to present to the user (e.g., 'none', 'consent', 'select_account'). - **state** (string) - Optional - Specifies any string value your application uses to maintain state between the authorization request and the server's response. Not recommended for general use. ``` -------------------------------- ### useGoogleOneTapLogin Source: https://github.com/momensherif/react-oauth/blob/master/packages/@react-oauth/google/README.md The useGoogleOneTapLogin hook facilitates the integration of Google's One Tap sign-in flow into your React application. It accepts various configuration options to customize the login experience. ```APIDOC ## useGoogleOneTapLogin ### Description This hook enables the Google One Tap sign-in prompt, allowing users to log in with their Google account seamlessly. It provides callbacks for success and error scenarios, along with several configuration options to tailor the prompt's behavior. ### Parameters #### Props - **onSuccess** (function) - Required - Callback function that is invoked with the `CredentialResponse` object upon successful user login. - **onError** (function) - Optional - Callback function that is invoked when the login process fails. - **promptMomentNotification** (function) - Optional - Callback function that receives `PromptMomentNotification` methods and descriptions, allowing for advanced control over the prompt's lifecycle. See [PromptMomentNotification](https://developers.google.com/identity/gsi/web/reference/js-reference) for more details. - **cancel_on_tap_outside** (boolean) - Optional - If true, the prompt will be canceled if the user clicks outside of it. Defaults to false. - **hosted_domain** (string) - Optional - Provides a hint to Google about the user's Workspace domain, useful for domain-specific applications. Refer to the [hd](https://developers.google.com/identity/protocols/oauth2/openid-connect#authenticationuriparameters) parameter in OpenID Connect documentation for more information. - **disabled** (boolean) - Optional - If true, the prompt will be disabled, for example, if the user is already logged in. Defaults to false. - **use_fedcm_for_prompt** (boolean) - Optional - If true, enables the browser to manage the sign-in prompt and mediate the flow between your website and Google. - **use_fedcm_for_button** (boolean) - Optional - If true, enables the FedCM Button flow. ``` -------------------------------- ### Google Login Button with Authorization Code Flow Source: https://context7.com/momensherif/react-oauth/llms.txt Use this when your backend needs to exchange the authorization code for tokens. Ensure `redirect_uri` is configured for redirect mode. ```tsx import { useGoogleLogin, hasGrantedAllScopesGoogle } from '@react-oauth/google'; import axios from 'axios'; // ── Authorization code flow (backend token exchange) ───────────────────────── function AuthCodeLoginButton() { const login = useGoogleLogin({ flow: 'auth-code', scope: 'https://www.googleapis.com/auth/drive.readonly', ux_mode: 'popup', // 'popup' | 'redirect' // redirect_uri: 'https://example.com/callback', // required for redirect mode onSuccess: async codeResponse => { // codeResponse: { code, scope, state? } await axios.post('/api/auth/google', { code: codeResponse.code }); console.log('Backend received code, tokens stored server-side'); }, onError: err => console.error('Auth code flow failed:', err), }); return ; } ``` -------------------------------- ### useGoogleLogin Hook Configuration Source: https://github.com/momensherif/react-oauth/blob/master/packages/@react-oauth/google/README.md Configuration options for the useGoogleLogin hook, which supports both implicit and authorization code flows for Google authentication. ```APIDOC ## useGoogleLogin Hook ### Description Facilitates user login with Google using either the implicit or authorization code flow. It handles the OAuth 2.0 authentication process and provides callbacks for success and error scenarios. ### Parameters #### `flow` (string) - Optional Specifies the OAuth 2.0 flow to use. Can be either `"implicit"` or `"auth-code"`. Defaults to `"auth-code"` if not specified. #### `onSuccess` ((response: TokenResponse | CodeResponse) => void) - Required A callback function that is executed upon successful login. The `response` object contains either a `TokenResponse` (for implicit flow) or a `CodeResponse` (for authorization code flow). #### `onError` ((errorResponse: {error: string; error_description?: string; error_uri?: string}) => void) - Required A callback function that is executed when a login failure occurs. It receives an `errorResponse` object containing details about the error. #### `onNonOAuthError` ((nonOAuthError: NonOAuthError) => void) - Optional A callback function for handling non-OAuth errors, such as issues with the popup window (e.g., `"popup_failed_to_open"`, `"popup_closed"`, `"unknown"`). #### `scope` (string) - Optional A space-delimited string of scopes that the user should approve. This determines the level of access your application requests. #### `enable_serial_consent` (boolean) - Optional Defaults to `true`. If set to `false`, it disables more granular Google Account permissions for clients created before 2019. It has no effect on newer clients. #### `hint` (string) - Optional Provides a hint to Google about the expected user, typically an email address, to streamline the login process. See Google's `login_hint` documentation for more details. #### `hosted_domain` (string) - Optional Provides a hint to Google about the user's Workspace domain, which can be useful for applications within specific organizations. See Google's `hd` documentation for more details. ``` -------------------------------- ### GoogleLogin Source: https://context7.com/momensherif/react-oauth/llms.txt The GoogleLogin component renders the official Google Sign-In button using the GSI SDK. It supports extensive customization for button appearance and behavior, and handles authentication callbacks. ```APIDOC ## GoogleLogin ### Description Renders the official Google Sign-In button using the GSI SDK and optionally activates One Tap. Accepts extensive customization for button appearance (type, theme, size, shape, text, logo alignment, width) and all `IdConfiguration` options. Passes a decoded `CredentialResponse` with an ID token (`credential` JWT) to `onSuccess`. ### Usage ```tsx import { GoogleLogin } from '@react-oauth/google'; import { jwtDecode } from 'jwt-decode'; // optional β€” any JWT decoder works function LoginPage() { return ( { // credentialResponse: { credential?: string; select_by?: string; clientId?: string } const decoded = jwtDecode(credentialResponse.credential!); // decoded contains: sub, email, name, picture, iat, exp, etc. console.log('ID token:', credentialResponse.credential); console.log('User:', decoded); }} onError={() => { console.error('Google Sign-In failed'); }} promptMomentNotification={notification => { if (notification.isNotDisplayed()) { console.warn('One Tap not shown:', notification.getNotDisplayedReason()); } if (notification.isSkippedMoment()) { console.warn('One Tap skipped:', notification.getSkippedReason()); } }} /> ); } ``` ### Props - **type** (string) - Optional - The type of the button ('standard', 'icon'). Defaults to 'standard'. - **theme** (string) - Optional - The theme of the button ('outline', 'filled_blue', 'filled_black'). Defaults to 'filled_blue'. - **size** (string) - Optional - The size of the button ('large', 'medium', 'small'). Defaults to 'large'. - **text** (string) - Optional - The text displayed on the button ('signin_with', 'signup_with', 'continue_with', 'signin'). Defaults to 'signin_with'. - **shape** (string) - Optional - The shape of the button ('rectangular', 'pill', 'circle', 'square'). Defaults to 'rectangular'. - **logo_alignment** (string) - Optional - The alignment of the logo ('left', 'center'). Defaults to 'left'. - **width** (string) - Optional - The width of the button. - **useOneTap** (boolean) - Optional - Whether to also trigger the One Tap prompt. - **auto_select** (boolean) - Optional - Whether to auto sign-in returning users. - **ux_mode** (string) - Optional - The UX mode ('popup' or 'redirect'). Defaults to 'popup'. - **login_hint** (string) - Optional - A hint for the user's email address. - **hosted_domain** (string) - Optional - The hosted domain for Google Workspace users. - **onSuccess** (function) - Required - Callback function that receives the `CredentialResponse` upon successful sign-in. - **onError** (function) - Optional - Callback function for when sign-in fails. - **promptMomentNotification** (function) - Optional - Callback for One Tap prompt notifications. ``` -------------------------------- ### GoogleLogin Component Props Source: https://github.com/momensherif/react-oauth/blob/master/packages/@react-oauth/google/README.md The GoogleLogin component accepts several props to customize its behavior and appearance. Below is a detailed breakdown of each prop. ```APIDOC ## GoogleLogin Component Props ### Description This component facilitates Google sign-in functionality. It accepts various props to customize the button's appearance and behavior, including success and error callbacks. ### Props #### Required Props - **onSuccess** (`(response: CredentialResponse) => void`) - Required - Callback function that is invoked with the credential response upon successful login. #### Optional Props - **onError** (`function`) - Optional - Callback function that is invoked when the login process fails. - **type** (`standard` | `icon`) - Optional - Specifies the type of the Google sign-in button. Refer to Google Identity Services documentation for details on available types. - **theme** (`outline` | `filled_blue` | `filled_black`) - Optional - Sets the visual theme of the button. Refer to Google Identity Services documentation for available themes. - **size** (`large` | `medium` | `small`) - Optional - Determines the size of the button. Refer to Google Identity Services documentation for available sizes. - **text** (`signin_with` | `signup_with` | `continue_with` | `signin`) - Optional - Defines the text displayed on the button, such as "Sign in with Google" or "Sign in". Refer to Google Identity Services documentation for available text options. - **shape** (`rectangular` | `pill` | `circle` | `square`) - Optional - Sets the shape of the button. Refer to Google Identity Services documentation for available shapes. - **logo_alignment** (`left` | `center`) - Optional - Controls the alignment of the Google logo on the button. Refer to Google Identity Services documentation for alignment options. - **width** (`string`) - Optional - Specifies the width of the button in pixels. Refer to Google Identity Services documentation for width specifications. ``` -------------------------------- ### useGoogleOAuth Source: https://context7.com/momensherif/react-oauth/llms.txt Provides access to the GoogleOAuthProvider context. This low-level hook returns context values like `clientId`, `scriptLoadedSuccessfully`, and `locale`. It throws an error if used outside of a `GoogleOAuthProvider`. ```APIDOC ## useGoogleOAuth ### Description Internal low-level hook that returns `{ clientId, scriptLoadedSuccessfully, locale }` from the nearest `GoogleOAuthProvider`. Throws if called outside a provider. Use this to build custom Google OAuth integrations beyond what `useGoogleLogin` provides. ### Returns - **clientId** (string) - The client ID configured in the `GoogleOAuthProvider`. - **scriptLoadedSuccessfully** (boolean) - Indicates whether the Google Identity Services (GIS) script has loaded successfully. - **locale** (string) - The locale configured in the `GoogleOAuthProvider`. ### Usage Example ```tsx import { useGoogleOAuth } from '@react-oauth/google'; function GoogleOAuthStatus() { const { clientId, scriptLoadedSuccessfully } = useGoogleOAuth(); return (

Client ID: {clientId}

GSI Script: {scriptLoadedSuccessfully ? 'βœ… Loaded' : '⏳ Loading…'}

); } ``` ### Error Handling - Throws an error if called outside of a `GoogleOAuthProvider`. ``` -------------------------------- ### useGoogleLogin Source: https://context7.com/momensherif/react-oauth/llms.txt Provides a login trigger function to open the Google consent popup. Supports both implicit flow for direct token retrieval and authorization code flow for backend token exchange. ```APIDOC ## useGoogleLogin ### Description Returns a login trigger function that opens the Google consent popup. Use `flow: 'implicit'` (default) to get an access token directly in the browser; use `flow: 'auth-code'` to receive an authorization code that your backend exchanges for tokens. The returned function for the implicit flow accepts optional `OverridableTokenClientConfig` at call-time to override `prompt`, `hint`, or `state`. ### Implicit Flow Example ```tsx import { useGoogleLogin, hasGrantedAllScopesGoogle } from '@react-oauth/google'; import axios from 'axios'; function ImplicitLoginButton() { const login = useGoogleLogin({ flow: 'implicit', // default scope: 'https://www.googleapis.com/auth/calendar.readonly', prompt: 'consent', // '' | 'none' | 'consent' | 'select_account' hint: 'user@example.com', onSuccess: async tokenResponse => { // tokenResponse: { access_token, expires_in, scope, token_type, ... } const calendarGranted = hasGrantedAllScopesGoogle( tokenResponse, 'https://www.googleapis.com/auth/calendar.readonly', ); if (!calendarGranted) { console.warn('Calendar scope was not granted'); return; } const { data } = await axios.get( 'https://www.googleapis.com/calendar/v3/calendars/primary/events', { headers: { Authorization: `Bearer ${tokenResponse.access_token}` } }, ); console.log('Calendar events:', data.items); }, onError: err => console.error('Login failed:', err.error, err.error_description), onNonOAuthError: err => { // err.type: 'popup_failed_to_open' | 'popup_closed' | 'unknown' if (err.type === 'popup_closed') console.warn('User closed the popup'); }, }); return ; } ``` ### Authorization Code Flow Example ```tsx import { useGoogleLogin } from '@react-oauth/google'; import axios from 'axios'; function AuthCodeLoginButton() { const login = useGoogleLogin({ flow: 'auth-code', scope: 'https://www.googleapis.com/auth/drive.readonly', ux_mode: 'popup', // 'popup' | 'redirect' // redirect_uri: 'https://example.com/callback', // required for redirect mode onSuccess: async codeResponse => { // codeResponse: { code, scope, state? } await axios.post('/api/auth/google', { code: codeResponse.code }); console.log('Backend received code, tokens stored server-side'); }, onError: err => console.error('Auth code flow failed:', err), }); return ; } ``` ``` -------------------------------- ### useGoogleLogin (Authorization Code Flow Props) Source: https://github.com/momensherif/react-oauth/blob/master/packages/@react-oauth/google/README.md Props available for the `useGoogleLogin` hook when using the authorization code OAuth flow. These props are essential for configuring the redirect behavior and user account selection. ```APIDOC ## useGoogleLogin (Authorization Code Flow Props) ### Description Props to configure the authorization code flow for Google Sign-In. ### Parameters #### Query Parameters - **ux_mode** (string) - Optional - The UX mode for the authorization flow. Valid values are 'popup' (default) or 'redirect'. - **redirect_uri** (string) - Required for 'redirect' UX mode. The URI to which the user is redirected after completing the authorization flow. Must match a pre-configured URI in the API Console. - **state** (string) - Optional - Recommended for 'redirect' UX mode. A string value used to maintain state between the authorization request and the server's response. - **select_account** (boolean) - Optional - Defaults to 'false'. A boolean value to prompt the user to select an account. ``` -------------------------------- ### Commit Changes with Commitizen Source: https://github.com/momensherif/react-oauth/blob/master/CONTRIBUTING.md Use this command to interactively create commit messages that follow the Conventional Commits specification. ```bash yarn commit ``` -------------------------------- ### GoogleLogin Props Source: https://github.com/momensherif/react-oauth/blob/master/packages/@react-oauth/google/README.md The GoogleLogin component accepts various props to customize its behavior and appearance. These props control aspects like the state returned, prompt text, cookie domains, allowed origins, callback functions, ITP support, hosted domain hints, login hints, and FedCM integration. ```APIDOC ## GoogleLogin Component Props ### Props - **state** (`string`) - Required - This string returns with the ID token. - **context** (`signin` | `signup` | `use`) - Optional - The title and words in the One Tap prompt. - **state_cookie_domain** (`string`) - Optional - 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[]`) - Optional - 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`) - Optional - Overrides the default intermediate iframe behavior when users manually close One Tap. - **itp_support** (`boolean`) - Optional - Enables upgraded One Tap UX on ITP browsers. - **hosted_domain** (`string`) - Optional - 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](https://developers.google.com/identity/protocols/oauth2/openid-connect#authenticationuriparameters) field in the OpenID Connect docs. - **login_hint** (`string`) - Optional - 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](https://developers.google.com/identity/protocols/oauth2/openid-connect#authenticationuriparameters) field in the OpenID Connect docs. - **use_fedcm_for_prompt** (`boolean`) - Optional - Allow the browser to control user sign-in prompts and mediate the sign-in flow between your website and Google. - **use_fedcm_for_button** (`boolean`) - Optional - Enable FedCM Button flow. ``` -------------------------------- ### PopupWindowOptions Interface Source: https://github.com/momensherif/react-oauth/blob/master/packages/@react-oauth/github/README.md Interface for configuring the dimensions and position of the OAuth popup window. ```typescript interface PopupWindowOptions { height?: number; width?: number; left?: number; top?: number; } ``` -------------------------------- ### Initialize Google OAuth Provider Source: https://context7.com/momensherif/react-oauth/llms.txt Wrap your application with GoogleOAuthProvider to load the Google Identity Services script. This context is required for child components and hooks that use Google OAuth. ```tsx import React from 'react'; import ReactDOM from 'react-dom/client'; import { GoogleOAuthProvider } from '@react-oauth/google'; import App from './App'; ReactDOM.createRoot(document.getElementById('root')!).render( console.log('GSI script loaded')} onScriptLoadError={() => console.error('GSI script failed to load')} > ); ``` -------------------------------- ### GoogleOAuthProvider Props Source: https://github.com/momensherif/react-oauth/blob/master/packages/@react-oauth/google/README.md The GoogleOAuthProvider component accepts the following props for configuration. ```APIDOC ## GoogleOAuthProvider ### Description Provides the necessary context and configuration for Google OAuth functionality within the application. ### Props #### Required Props - **clientId** (string) - Required - The Google API client ID obtained from the Google Cloud Console. This is essential for authenticating with Google. #### Optional Props - **nonce** (string) - Optional - A nonce value that can be applied to the Google Identity Services (GSI) script tag. This value propagates to GSI's inline style tag. - **onScriptLoadSuccess** (function) - Optional - A callback function that is executed when the GSI script is successfully loaded. - **onScriptLoadError** (function) - Optional - A callback function that is executed if there is an error loading the GSI script. ``` -------------------------------- ### useGitHubLogin Return Value Interface Source: https://github.com/momensherif/react-oauth/blob/master/packages/@react-oauth/github/README.md Interface defining the return values of the useGitHubLogin hook, including the function to initiate login and the loading state. ```typescript interface UseGitHubLoginReturn { initiateGitHubLogin: () => void; isLoading: boolean; } ```