@darshan3431/google-login-react
v1.0.5
Published
A plug-and-play React component for Google OAuth 2.0 authentication with Django backend integration
Downloads
60
Maintainers
Readme
@td/google-login-react
A plug-and-play React component library for Google OAuth 2.0 authentication that seamlessly integrates with Django backends using the td-google-login package.
Features
- 🚀 Plug-and-play: Works out of the box with minimal setup
- 🔐 Secure: Built on Google Identity Services with proper token handling
- 🎯 Flexible: Multiple authentication flows (button click, One Tap, programmatic)
- 📱 Responsive: Mobile-friendly components with customizable styling
- 🛡️ TypeScript: Full TypeScript support with comprehensive type definitions
- ⚡ Performance: Optimized with lazy loading and efficient re-renders
- 🎨 Customizable: Extensive styling and configuration options
Installation
npm install @td/google-login-reactQuick Setup
1. Wrap your app with GoogleAuthProvider
import { GoogleAuthProvider } from '@td/google-login-react';
function App() {
return (
<GoogleAuthProvider clientId="your-google-client-id">
<YourApp />
</GoogleAuthProvider>
);
}2. Use the GoogleLoginButton component
import { GoogleLoginButton } from '@td/google-login-react';
function LoginPage() {
const handleSuccess = (response) => {
console.log('Login successful:', response.user);
// Redirect or update UI
};
const handleError = (error) => {
console.error('Login failed:', error);
};
return (
<GoogleLoginButton
clientId="your-google-client-id"
onSuccess={handleSuccess}
onError={handleError}
/>
);
}Components
GoogleLoginButton
The main login button component with full customization options.
import { GoogleLoginButton } from '@td/google-login-react';
<GoogleLoginButton
clientId="your-google-client-id"
callbackUrl="/auth/google/callback/"
onSuccess={(response) => console.log('Success:', response)}
onError={(error) => console.log('Error:', error)}
text="Sign in with Google"
theme="outline"
size="large"
shape="rectangular"
width={300}
className="my-google-button"
loading={false}
disabled={false}
/>Props:
| Prop | Type | Default | Description |
|------|------|---------|-------------|
| clientId | string | required | Google OAuth client ID |
| callbackUrl | string | /auth/google/callback/ | Backend endpoint for token verification |
| onSuccess | function | - | Callback for successful login |
| onError | function | - | Callback for login errors |
| text | string | 'Sign in with Google' | Button text |
| theme | 'outline' \| 'filled_blue' \| 'filled_black' | 'outline' | Button theme |
| size | 'large' \| 'medium' \| 'small' | 'large' | Button size |
| shape | 'rectangular' \| 'pill' \| 'circle' \| 'square' | 'rectangular' | Button shape |
| width | number | - | Button width in pixels |
| className | string | - | Custom CSS class |
| style | object | - | Custom inline styles |
| loading | boolean | false | Show loading state |
| loadingText | string | 'Signing in...' | Loading text |
| disabled | boolean | false | Disable button |
| autoLogin | boolean | false | Auto-trigger login on mount |
GoogleOneTap
Automatic sign-in with Google One Tap.
import { GoogleOneTap } from '@td/google-login-react';
<GoogleOneTap
clientId="your-google-client-id"
callbackUrl="/auth/google/callback/"
onSuccess={(response) => console.log('One Tap success:', response)}
onError={(error) => console.log('One Tap error:', error)}
autoPrompt={true}
promptDelay={1000}
cancelOnTapOutside={true}
/>Props:
| Prop | Type | Default | Description |
|------|------|---------|-------------|
| clientId | string | required | Google OAuth client ID |
| callbackUrl | string | /auth/google/callback/ | Backend endpoint for token verification |
| onSuccess | function | - | Callback for successful login |
| onError | function | - | Callback for login errors |
| autoPrompt | boolean | true | Auto-show One Tap prompt |
| promptDelay | number | 1000 | Delay before showing prompt (ms) |
| cancelOnTapOutside | boolean | true | Cancel prompt when clicking outside |
GoogleAuthProvider
Context provider for managing authentication state across your app.
import { GoogleAuthProvider, useGoogleAuth } from '@td/google-login-react';
function App() {
return (
<GoogleAuthProvider
clientId="your-google-client-id"
callbackUrl="/auth/google/callback/"
>
<Dashboard />
</GoogleAuthProvider>
);
}
function Dashboard() {
const { user, isAuthenticated, login, logout, loading } = useGoogleAuth();
if (loading) return <div>Loading...</div>;
if (!isAuthenticated) {
return <button onClick={login}>Sign In</button>;
}
return (
<div>
<h1>Welcome, {user?.first_name}!</h1>
<button onClick={logout}>Sign Out</button>
</div>
);
}Hooks
useGoogleLogin
Programmatic Google login hook.
import { useGoogleLogin } from '@td/google-login-react';
function CustomLoginComponent() {
const { login, loading, error, user } = useGoogleLogin('your-client-id', {
callbackUrl: '/auth/google/callback/',
onSuccess: (response) => console.log('Success:', response),
onError: (error) => console.log('Error:', error),
});
return (
<div>
<button onClick={login} disabled={loading}>
{loading ? 'Signing in...' : 'Sign in with Google'}
</button>
{error && <p>Error: {error}</p>}
{user && <p>Welcome, {user.first_name}!</p>}
</div>
);
}useAuthState
Check current authentication state.
import { useAuthState } from '@td/google-login-react';
function AuthStatusComponent() {
const { user, loading, error, isAuthenticated } = useAuthState();
if (loading) return <div>Checking auth status...</div>;
if (error) return <div>Auth error: {error}</div>;
return (
<div>
Status: {isAuthenticated ? 'Logged in' : 'Not logged in'}
{user && <p>User: {user.email}</p>}
</div>
);
}useGoogleLogout
Logout functionality.
import { useGoogleLogout } from '@td/google-login-react';
function LogoutButton() {
const { logout, loading, error } = useGoogleLogout();
const handleLogout = async () => {
try {
await logout();
console.log('Logged out successfully');
} catch (err) {
console.error('Logout failed:', err);
}
};
return (
<button onClick={handleLogout} disabled={loading}>
{loading ? 'Signing out...' : 'Sign Out'}
{error && <span> - Error: {error}</span>}
</button>
);
}Advanced Usage
Custom Styling
import { GoogleLoginButton } from '@td/google-login-react';
<GoogleLoginButton
clientId="your-client-id"
className="custom-google-btn"
style={{
borderRadius: '8px',
boxShadow: '0 2px 4px rgba(0,0,0,0.1)',
fontSize: '16px',
}}
theme="filled_blue"
size="medium"
/>Error Handling
import { GoogleLoginButton } from '@td/google-login-react';
<GoogleLoginButton
clientId="your-client-id"
onError={(error) => {
// Log error to your error tracking service
console.error('Google login error:', error);
// Show user-friendly message
if (error.includes('popup_blocked')) {
alert('Please allow popups for this site');
} else if (error.includes('network')) {
alert('Network error. Please check your connection.');
} else {
alert('Login failed. Please try again.');
}
}}
/>Custom Fetch Options
import { GoogleLoginButton } from '@td/google-login-react';
<GoogleLoginButton
clientId="your-client-id"
fetchOptions={{
headers: {
'X-Custom-Header': 'value',
},
credentials: 'include',
}}
/>Loading States
import { useState } from 'react';
import { GoogleLoginButton } from '@td/google-login-react';
function LoginForm() {
const [isLoading, setIsLoading] = useState(false);
return (
<GoogleLoginButton
clientId="your-client-id"
loading={isLoading}
loadingText="Authenticating..."
onSuccess={() => setIsLoading(false)}
onError={() => setIsLoading(false)}
/>
);
}Backend Integration
This package is designed to work with the td-google-login Django package. Make sure your Django backend is configured with the same Google OAuth client ID.
Django Setup
# settings.py
INSTALLED_APPS = [
'td_google_login',
# ... other apps
]
GOOGLE_CLIENT_ID = 'your-google-client-id'
GOOGLE_CLIENT_SECRET = 'your-google-client-secret'
# urls.py
urlpatterns = [
path('auth/google/', include('td_google_login.urls')),
# ... other URLs
]API Endpoints
The React components expect these endpoints to be available:
POST /auth/google/callback/- Token verificationGET /auth/google/user-info/- Get current user infoPOST /auth/google/logout/- Logout user
TypeScript Support
This package includes comprehensive TypeScript definitions:
import type {
GoogleUser,
GoogleLoginResponse,
GoogleLoginButtonProps
} from '@td/google-login-react';
const user: GoogleUser = {
id: '123',
username: '[email protected]',
email: '[email protected]',
first_name: 'John',
last_name: 'Doe',
};Testing
The package includes test utilities and mocks:
// In your test file
import { render, screen } from '@testing-library/react';
import { GoogleLoginButton } from '@td/google-login-react';
test('renders google login button', () => {
render(
<GoogleLoginButton
clientId="test-client-id"
onSuccess={jest.fn()}
onError={jest.fn()}
/>
);
expect(screen.getByText(/sign in with google/i)).toBeInTheDocument();
});Browser Support
- Chrome 60+
- Firefox 60+
- Safari 12+
- Edge 79+
Security Considerations
- Always validate tokens on your backend
- Use HTTPS in production
- Keep your Google client secret secure (never expose it in frontend code)
- Implement proper CSRF protection
- Consider implementing rate limiting
Troubleshooting
Common Issues
"Google Auth not initialized"
- Ensure you have a valid Google client ID
- Check that the Google Identity Services script loaded properly
CORS errors
- Make sure your domain is authorized in Google Cloud Console
- Check your Django CORS settings
Token verification failed
- Verify your Django backend has the correct client secret
- Check that system time is synchronized
Debug Mode
Enable debug logging:
import { useGoogleLogin } from '@td/google-login-react';
// The package will log detailed information to the console in development modeContributing
Contributions are welcome! Please feel free to submit a Pull Request.
License
This project is licensed under the MIT License.
Support
For support, please open an issue on GitHub or contact [email protected].
