atozas-react-auth-kit
v1.0.1
Published
Production-ready React authentication components for Google OAuth and Email OTP
Downloads
216
Maintainers
Readme
atozas-react-auth-kit
Production-ready React authentication components for Google OAuth and Email OTP. Drop-in components with beautiful UI.
Features
- 🎨 Beautiful UI - Clean, modern components with minimal CSS
- 🔐 Google OAuth - One-tap login with
@react-oauth/google - 📧 Email OTP - Passwordless authentication
- 🔄 Auto Token Refresh - Axios interceptors handle expired tokens
- 💾 Flexible Storage - Memory or localStorage for tokens
- 🪝 React Hooks - Simple
useAuth()hook - 📦 TypeScript - Full type definitions
- ⚡ Zero Config - Works out of the box
Installation
npm install atozas-react-auth-kitQuick Start
import { AuthProvider, useAuth, GoogleLoginButton, EmailOtpLogin } from 'atozas-react-auth-kit';
import 'atozas-react-auth-kit/styles.css';
// Wrap your app
function App() {
return (
<AuthProvider
apiUrl="http://localhost:3000/api/auth"
googleClientId={process.env.REACT_APP_GOOGLE_CLIENT_ID!}
enableLocalStorage={true}
>
<YourApp />
</AuthProvider>
);
}
// Login page
function LoginPage() {
const { isAuthenticated } = useAuth();
if (isAuthenticated) {
return <Navigate to="/dashboard" />;
}
return (
<div>
<h1>Welcome</h1>
<GoogleLoginButton
onSuccess={() => console.log('Logged in!')}
/>
<div style={{ margin: '20px 0' }}>OR</div>
<EmailOtpLogin
onSuccess={() => console.log('Logged in!')}
/>
</div>
);
}
// Use auth in any component
function Dashboard() {
const { user, logout } = useAuth();
return (
<div>
<h1>Welcome {user?.name || user?.email}</h1>
<button onClick={logout}>Logout</button>
</div>
);
}Components
<AuthProvider>
Wraps your app and provides authentication context.
<AuthProvider
apiUrl="http://localhost:3000/api/auth"
googleClientId="YOUR_GOOGLE_CLIENT_ID"
enableLocalStorage={true}
onAuthError={(error) => console.error(error)}
>
{children}
</AuthProvider>Props:
apiUrl(required): Your backend auth endpointgoogleClientId(required): Google OAuth client IDenableLocalStorage(optional): Store tokens in localStorage (default: false)onAuthError(optional): Callback for auth errors
<GoogleLoginButton>
Google OAuth login button.
<GoogleLoginButton
text="Continue with Google"
onSuccess={() => navigate('/dashboard')}
onError={(error) => console.error(error)}
className="custom-class"
/>Props:
text(optional): Button text (default: "Continue with Google")onSuccess(optional): Callback on successful loginonError(optional): Callback on errorclassName(optional): Additional CSS classes
<EmailOtpLogin>
Email OTP login form.
<EmailOtpLogin
onSuccess={() => navigate('/dashboard')}
onError={(error) => console.error(error)}
className="custom-class"
/>Props:
onSuccess(optional): Callback on successful loginonError(optional): Callback on errorclassName(optional): Additional CSS classes
Hooks
useAuth()
Access authentication state and methods.
const {
user, // Current user object
isAuthenticated, // Boolean auth status
isLoading, // Initial loading state
accessToken, // Current access token
login, // Login function (handled by components)
logout, // Logout function
refreshToken, // Manual token refresh
} = useAuth();User Object:
interface User {
id: string;
email: string;
name?: string;
picture?: string;
provider: 'google' | 'email';
}API Client
Use the pre-configured axios client for authenticated requests:
import { apiClient } from 'atozas-react-auth-kit';
// In your component
const fetchUserData = async () => {
const response = await apiClient.get('/user/profile');
return response.data;
};The client automatically:
- Adds access token to requests
- Refreshes token on 401 errors
- Retries failed requests with new token
Custom Styling
Import the default styles:
import 'atozas-react-auth-kit/styles.css';Or override with your own CSS:
.auth-button {
background-color: #your-color;
}
.form-input {
border-color: #your-color;
}CSS Classes:
.google-button- Google login button.email-otp-login- Email OTP container.auth-form- Form container.form-input- Input fields.auth-button- Primary buttons.auth-button-secondary- Secondary buttons.auth-error- Error messages.auth-success- Success messages
Protected Routes
import { useAuth } from 'atozas-react-auth-kit';
import { Navigate } from 'react-router-dom';
function ProtectedRoute({ children }) {
const { isAuthenticated, isLoading } = useAuth();
if (isLoading) {
return <div>Loading...</div>;
}
if (!isAuthenticated) {
return <Navigate to="/login" />;
}
return children;
}
// Usage
<Route path="/dashboard" element={
<ProtectedRoute>
<Dashboard />
</ProtectedRoute>
} />TypeScript
Full TypeScript support:
import type { User, AuthState, AuthContextValue } from 'atozas-react-auth-kit';
const MyComponent: React.FC = () => {
const auth: AuthContextValue = useAuth();
const user: User | null = auth.user;
// ...
};Advanced Usage
Manual Token Refresh
const { refreshToken } = useAuth();
const handleRefresh = async () => {
const newToken = await refreshToken();
if (newToken) {
console.log('Token refreshed!');
} else {
console.log('Refresh failed');
}
};Custom API Calls
import { apiClient } from 'atozas-react-auth-kit';
// The client handles auth automatically
const updateProfile = async (data) => {
const response = await apiClient.put('/user/profile', data);
return response.data;
};
const uploadFile = async (file) => {
const formData = new FormData();
formData.append('file', file);
const response = await apiClient.post('/upload', formData, {
headers: { 'Content-Type': 'multipart/form-data' },
});
return response.data;
};Examples
Check the examples/mern-demo folder for a complete working example.
License
MIT
