nicelogin-react
v0.1.0
Published
NiceLogin React SDK - Simple authentication for React applications
Maintainers
Readme
nicelogin-react
React SDK for NiceLogin authentication. Simple, minimal, zero external dependencies.
Installation
npm install nicelogin-reactQuick Start
1. Wrap your app with NiceLoginProvider
import { NiceLoginProvider } from 'nicelogin-react';
function App() {
return (
<NiceLoginProvider apiKey="nicelogin_your_api_key">
<YourApp />
</NiceLoginProvider>
);
}2. Use the useNiceLogin hook
import { useNiceLogin } from 'nicelogin-react';
function LoginPage() {
const { login, isAuthenticated, user, isLoading } = useNiceLogin();
if (isLoading) return <div>Loading...</div>;
if (isAuthenticated) {
return <div>Welcome, {user.email}!</div>;
}
const handleLogin = async () => {
try {
await login('[email protected]', 'password123');
} catch (error) {
console.error(error.message);
}
};
return <button onClick={handleLogin}>Login</button>;
}API Reference
NiceLoginProvider
Context provider that wraps your application.
<NiceLoginProvider
apiKey="nicelogin_xxx" // Required: Your API key
baseUrl="https://custom.api" // Optional: Custom API URL
storage="localStorage" // Optional: "localStorage" (default) or "memory"
>
<App />
</NiceLoginProvider>| Prop | Type | Default | Description |
|------|------|---------|-------------|
| apiKey | string | Required | Your NiceLogin API key |
| baseUrl | string | https://api.v1.nicelogin.com | Custom API base URL |
| storage | "localStorage" \| "memory" | "localStorage" | Token storage method |
useNiceLogin()
Main hook for authentication. Must be used within NiceLoginProvider.
const {
user, // User | null
token, // string | null
isAuthenticated, // boolean
isLoading, // boolean
login, // (email, password) => Promise<void>
logout, // () => void
register, // (email, password, userData?) => Promise<void>
requestPasswordReset, // (email) => Promise<string>
} = useNiceLogin();Return Values
| Property | Type | Description |
|----------|------|-------------|
| user | User \| null | Current authenticated user |
| token | string \| null | Raw JWT token |
| isAuthenticated | boolean | true if user is logged in |
| isLoading | boolean | true during initial auth check |
| login | function | Login with email and password |
| logout | function | Logout and clear token |
| register | function | Register new user |
| requestPasswordReset | function | Request password reset token |
User Object
interface User {
id: string; // User UUID
email: string; // User email
companyId: string; // Company UUID
userData?: object; // Custom user data
}Usage Examples
Login
const { login } = useNiceLogin();
try {
await login('[email protected]', 'password123');
// Success - user is now authenticated
} catch (error) {
console.error(error.message); // "Invalid credentials"
}Logout
const { logout } = useNiceLogin();
logout(); // Clears token and resets stateRegister
const { register } = useNiceLogin();
try {
await register('[email protected]', 'password123', {
name: 'John Doe',
plan: 'premium'
});
// Success - user is registered and logged in
} catch (error) {
console.error(error.message);
}Request Password Reset
const { requestPasswordReset } = useNiceLogin();
try {
const resetToken = await requestPasswordReset('[email protected]');
// Use resetToken to complete password reset
} catch (error) {
console.error(error.message);
}Protected Route
import { Navigate } from 'react-router-dom';
import { useNiceLogin } from 'nicelogin-react';
function ProtectedRoute({ children }) {
const { isAuthenticated, isLoading } = useNiceLogin();
if (isLoading) return <div>Loading...</div>;
if (!isAuthenticated) return <Navigate to="/login" />;
return children;
}
// Usage
<ProtectedRoute>
<Dashboard />
</ProtectedRoute>Access Raw Token
const { token } = useNiceLogin();
// Use token for authenticated API requests
fetch('/api/data', {
headers: {
'Authorization': `Bearer ${token}`
}
});Token Storage
localStorage (default)
- Persists across page refreshes
- Persists across browser tabs
- Auto-login on page load
memory
- Lost on page refresh
- More secure for sensitive applications
- No persistence
<NiceLoginProvider apiKey="xxx" storage="memory">Error Handling
All methods throw NiceLoginError on failure:
import { NiceLoginError } from 'nicelogin-react';
try {
await login(email, password);
} catch (error) {
if (error instanceof NiceLoginError) {
console.log(error.message); // Error message
console.log(error.status); // HTTP status code
}
}Types
import type {
User,
TokenPayload,
LoginResponse,
RegisterResponse,
PasswordResetResponse,
NiceLoginConfig,
AuthState,
AuthContextValue,
} from 'nicelogin-react';Utilities
decodeToken
Decode JWT payload (no validation):
import { decodeToken } from 'nicelogin-react';
const payload = decodeToken(token);
console.log(payload.sub); // User ID
console.log(payload.email); // User email
console.log(payload.exp); // Expiration timestampisTokenExpired
Check if token is expired:
import { isTokenExpired } from 'nicelogin-react';
if (isTokenExpired(token)) {
console.log('Token has expired');
}Requirements
- React >= 18.0.0
- Modern browser with
fetchAPI
License
MIT
