A lightweight React hook package for implementing Google OAuth2 login functionality in React applications.
- Easy-to-use React hooks for Google OAuth2 integration
- Handle Google login flow with minimal setup
- Automatic window message handling
- TypeScript support
- Zero dependencies (other than React)
npm install react-google-login-ts
Or using yarn:
yarn add react-google-login-ts
Note: This package requires React 16.8.0 or higher as a peer dependency.
First, set up your Google OAuth2 credentials in the Google Cloud Console and get your Client ID.
import { googleLoginClick } from 'react-google-login-ts';
function LoginButton() {
const handleLogin = () => {
const clientId = 'YOUR_GOOGLE_CLIENT_ID';
const redirectPath = 'http://your-domain.com/auth/callback';
googleLoginClick(clientId, redirectPath);
};
return <button onClick={handleLogin}>Login with Google</button>;
}
Create a callback page component:
import { useRedirectPageGoogleLogin } from 'react-google-login-ts';
function GoogleCallback() {
useRedirectPageGoogleLogin('YOUR_BACKEND_URL');
return <div>Processing login...</div>;
}
In your main component or where you need the login data:
import { useGetDataFromGoogleLogin } from 'react-google-login-ts';
function App() {
const loginData = useGetDataFromGoogleLogin((data) => {
console.log('Login successful:', data);
});
return <div>{loginData ? <div>Welcome, {loginData.name}!</div> : <LoginButton />}</div>;
}
function googleLoginClick(clientId: string, redirectPath: string): void;
Opens the Google login window.
-
clientId
: Your Google OAuth2 client ID -
redirectPath
: The URL where Google will redirect after authentication
function useRedirectPageGoogleLogin(backendUrl: string): void;
Hook for handling the OAuth2 callback.
-
backendUrl
: Your backend endpoint that handles the OAuth2 code exchange
function useGetDataFromGoogleLogin(callback?: (data: any) => any): any;
Hook for receiving the login data.
-
callback
: Optional callback function that runs when login data is received - Returns the login data object
"This project is licensed under the MIT License - see the LICENSE.md file or details.
Made with ❤️ using TypeScript