This project provides a React hook (useGoogleAuth) that abstracts Google authentication logic, supporting both **FedCM
** and One Tap sign-in methods. It automatically detects browser compatibility and selects the appropriate method.
This project is based on Next.js 15, but you can use it in any version of React or Next.js.
- Automatic authentication selection: Uses FedCM if supported, otherwise falls back to One Tap.
- OAuth2.0 login fallback: Provides a manual OAuth2.0 login button for environments where neither FedCM nor One Tap is available.
- Easy integration: Just import and use
useGoogleAuthin your React components. - TypeScript support: Fully typed for better development experience.
npm install- FedCM Check: Uses
window.IdentityCredentialto detect FedCM support. - FedCM Authentication: If supported, requests an identity credential from Google.
- One Tap Fallback: If FedCM is not available, loads the Google One Tap script and prompts the user.
- OAuth2.0 Fallback: If neither FedCM nor One Tap works, provides a manual login button that redirects to Google's OAuth2.0 authentication flow.
import {useGoogleAuth} from "./hooks/useGoogleAuth";
const GoogleAuthButton = () => {
const {token, error, signInWithOAuth} = useGoogleAuth();
return (
<button onClick={signInWithOAuth}>
{token ? "Logged in" : "Sign in with Google"}
</button>
);
};const {token, error, signInWithOAuth} = useGoogleAuth();token: Google credential if the user is authenticated.error: Contains error messages if authentication fails.signInWithOAuth: Triggers the appropriate authentication method.
| Function | Description |
|---|---|
token |
Returns Google credential if logged in |
error |
Error message if login fails |
signInWithOAuth() |
Starts Google authentication |
Update NEXT_PUBLIC_GOOGLE_CLIENT_ID in .env.
const GOOGLE_CLIENT_ID = "your-client-id.apps.googleusercontent.com";Update NEXT_PUBLIC_GOOGLE_REDIRECT_URI in .env.
const GOOGLE_REDIRECT_URI = "https://yourdomain.com/callback";Ensure that this URI is registered in the Google Developer Console.
Modify the GoogleAuthButton component to fit your design.
<button className="custom-class" onClick={signIn}>Login with Google</button>- Ensure your OAuth redirect URI is correctly registered in the Google Developer Console.
- Verify that
GOOGLE_REDIRECT_URImatches the one in your Google OAuth settings.
- Ensure your browser supports FedCM (currently not supported on iOS Chrome).
- Use One Tap or OAuth2.0 as a fallback.
- Google One Tap does not show if the user has previously closed it.
- Try opening in Incognito Mode.
MIT License.
@asionesjia