get401
v1.0.13
Published
Easy authentication SDK for React, Vue, Next.js, Express, and React Native applications - Get401 Auth
Maintainers
Readme
get401
Flexible authentication SDK for React applications. Easy-to-use authentication with email/password login, OTP verification, and ready-made UI components.
Installation
npm install get401Quick Start
1. Wrap your app with Get401Provider
import { Get401Provider } from 'get401';
function App() {
return (
<Get401Provider
appId="your-app-id"
debug={true}
onSuccess={(user) => console.log('User logged in:', user)}
onError={(error) => console.error('Auth error:', error)}
>
<YourApp />
</Get401Provider>
);
}2. Use the useAuth hook
import { useAuth } from 'get401';
function LoginPage() {
const { login, challengeOTP, user, status, nextStep, error, isLoading } = useAuth();
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [otpCode, setOtpCode] = useState('');
const handleLogin = async (e) => {
e.preventDefault();
try {
// Send both email and password in one request
const response = await login(email, password);
// If response.next === 'otp', show OTP input form
// Otherwise, user is authenticated
} catch (err) {
console.error('Login failed:', err);
}
};
const handleOTP = async (e) => {
e.preventDefault();
try {
await challengeOTP(otpCode);
// User will be authenticated if successful
} catch (err) {
console.error('OTP verification failed:', err);
}
};
if (status === 'authenticated') {
return <div>Welcome {user?.email}!</div>;
}
if (nextStep === 'otp') {
return (
<form onSubmit={handleOTP}>
<input
type="text"
value={otpCode}
onChange={(e) => setOtpCode(e.target.value)}
placeholder="Enter OTP code"
/>
<button type="submit" disabled={isLoading}>
Verify OTP
</button>
{error && <div>{error}</div>}
</form>
);
}
return (
<form onSubmit={handleLogin}>
<input
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
placeholder="Email"
required
/>
<input
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
placeholder="Password"
required
/>
<button type="submit" disabled={isLoading}>
Login
</button>
{error && <div>{error}</div>}
</form>
);
}Ready-made UI Components
AuthModal - Complete Modal Component
Drop-in authentication modal that handles the entire flow:
import { useState } from 'react';
import { AuthModal } from 'get401';
function App() {
const [showAuth, setShowAuth] = useState(false);
return (
<>
<button onClick={() => setShowAuth(true)}>Login</button>
<AuthModal
isOpen={showAuth}
onClose={() => setShowAuth(false)}
mode="login" // or "register"
onSuccess={() => {
console.log('User authenticated!');
setShowAuth(false);
}}
/>
</>
);
}AuthModal Props:
isOpen: boolean- Controls modal visibilityonClose: () => void- Callback when modal should closemode?: 'login' | 'register'- Initial mode (default: 'login')title?: string- Custom modal titleshowCloseButton?: boolean- Show/hide close button (default: true)className?: string- Custom CSS classes for form containeroverlayClassName?: string- Custom CSS classes for overlaymodalClassName?: string- Custom CSS classes for modal containeronSuccess?: () => void- Callback on successful authentication
LoginForm and RegisterForm Components
Ready-to-use form components that you can customize:
import { LoginForm, RegisterForm } from 'get401';
function AuthPage() {
const [mode, setMode] = useState('login');
return (
<div>
{mode === 'login' ? (
<LoginForm onSuccess={() => console.log('Logged in!')} />
) : (
<RegisterForm onSuccess={() => console.log('Registered!')} />
)}
<button onClick={() => setMode(mode === 'login' ? 'register' : 'login')}>
Switch to {mode === 'login' ? 'Register' : 'Login'}
</button>
</div>
);
}LoginForm Props:
onSuccess?: () => void- Callback on successful loginclassName?: string- Custom CSS classes for form containerinputClassName?: string- Custom CSS classes for inputsbuttonClassName?: string- Custom CSS classes for buttonslabelClassName?: string- Custom CSS classes for labelserrorClassName?: string- Custom CSS classes for error messages
RegisterForm Props:
- Same as LoginForm
Protected Routes
import { ProtectedRoute } from 'get401';
function App() {
return (
<Routes>
<Route path="/login" element={<LoginPage />} />
<Route
path="/dashboard"
element={
<ProtectedRoute fallback={<Navigate to="/login" />}>
<Dashboard />
</ProtectedRoute>
}
/>
</Routes>
);
}Core JS SDK
If you need to use the SDK without React:
import { Get401Client } from 'get401';
const client = new Get401Client('your-app-id', true); // appId, debug
// Login flow - email and password are sent together in one request
const loginResponse = await client.login('[email protected]', 'password123');
// If loginResponse.next === 'otp', user needs to verify OTP
if (loginResponse.next === 'otp') {
const otpResponse = await client.challengeOTP('123456');
}
// Get current user
const user = await client.getUser();
// Registration
const registerResponse = await client.register('[email protected]', 'password123');
// If registerResponse.setup === 'email', verify email
await client.challengeEmailSetup('email-code');
// If setup === 'otp', setup OTP
const otpSetup = await client.getOTPSetup();
await client.verifyOTPSetup('otp-code');
// Logout
await client.logout();
// Refresh token
await client.refreshToken();API Reference
Get401Provider
Provider component that wraps your React app and manages authentication state.
Props:
appId?: string- Your application ID (can also be set viawindow.GET401_APP_ID)onSuccess?: (user: User) => void- Callback on successful authenticationonError?: (error: string) => void- Callback on errordebug?: boolean- Enable debug logging (default: false)children: React.ReactNode- Your app components
useAuth Hook
React hook that provides authentication state and methods.
Returns:
status: 'idle' | 'loading' | 'authenticated' | 'unauthenticated'- Authentication statususer: User | null- Current user or nullnextStep: 'email' | 'otp' | null- Next step in authentication flowerror: string | null- Error message or nullisLoading: boolean- Is loading stateisAuthenticated: boolean- Boolean authentication statuslogin(email: string, password: string)- Login with email and password (both sent together in one API request)challengeOTP(code: string)- Submit OTP challengelogout()- Logout current usergetUser()- Get current userregister(email: string, password: string)- Register new userchallengeEmailSetup(code: string)- Verify email code during registrationgetOTPSetup()- Get OTP setup data (secret, QR code)verifyOTPSetup(code: string)- Verify OTP setup coderefreshToken()- Refresh authentication tokenclearError()- Clear error message
Get401Client
Pure JavaScript/TypeScript client without React dependencies.
const client = new Get401Client(appId: string, debug?: boolean);Methods:
login(email: string, password: string)- Login with email and password. Both email and password are sent together in a single API request to/v1/platform/auth/login. ReturnsLoginResponsewithnext: 'otp'if OTP verification is required.challengeOTP(code: string)- Submit OTP coderegister(email: string, password: string)- Register new userchallengeEmailSetup(code: string)- Verify email code during registrationgetOTPSetup()- Get OTP setup data (returns{ secret, otpUrl, otpQrCode })verifyOTPSetup(code: string)- Verify OTP setup codegetUser()- Get current userlogout()- LogoutrefreshToken()- Refresh authentication tokenisAuthenticated()- Check authentication status (always returns true)getAppId()- Get client ID
Types
interface User {
id: string;
email: string;
name?: string;
picture?: string;
}
interface LoginResponse {
next: 'email' | 'otp';
}
interface ChallengeResponse {
next?: 'email' | 'otp' | null;
}
interface RegisterResponse {
setup: 'email' | 'otp';
}
interface OTPSetupResponse {
secret: string;
otpUrl: string;
otpQrCode: string;
}Authentication Flow
Login Flow
Important: The login method sends both email and password in a single request.
- User submits email and password together via
login(email, password)- both are sent in one API call - Server validates credentials and responds with:
- If MFA/OTP is required:
{ next: 'otp' } - If login is successful: user is authenticated
- If MFA/OTP is required:
- If
nextStep === 'otp', user enters OTP code and callschallengeOTP(code) - On success, user is authenticated and
userobject is available
Registration Flow
- User submits email and password via
register(email, password) - Response will have
setup: 'email'orsetup: 'otp' - If
setup === 'email':- User enters email verification code
- Call
challengeEmailSetup(code) - May need to setup OTP next
- If
setup === 'otp'or after email verification:- Call
getOTPSetup()to get QR code - User scans QR code with authenticator app
- User enters OTP code and calls
verifyOTPSetup(code)
- Call
- On success, user is authenticated
TypeScript Support
This package is written in TypeScript and includes full type definitions. All exports are fully typed.
License
MIT
