@zhengliu92/react-auth-hook
v1.0.1
Published
A custom React hook library for managing authentication status
Maintainers
Readme
React Auth Hook
A lightweight React hook library for authentication with automatic token refresh and request management.
Features
- 🔐 Simple authentication state management
- 🔄 Automatic token refresh on expiration
- 📡 Built-in authenticated requests with Bearer token
- 💾 Persistent state with localStorage
- 🎯 Full TypeScript support with generic response types
- ⚡ Lightweight and performant
Installation
npm install @zhengliu92/react-auth-hookQuick Start
1. Setup AuthProvider
import { AuthProvider } from '@zhengliu92/react-auth-hook';
const config = {
login_url: 'https://api.example.com/auth/login',
refresh_url: 'https://api.example.com/auth/refresh', // optional
access_expiration_code: 401, // optional
};
function App() {
return (
<AuthProvider config={config}>
<YourApp />
</AuthProvider>
);
}2. Use the Hook and HTTP Client
import { useAuth, httpClient } from '@zhengliu92/react-auth-hook';
function LoginComponent() {
const { login, logout, isAuthenticated } = useAuth();
const handleLogin = async () => {
try {
await login({ email: '[email protected]', password: 'password' });
} catch (error) {
console.error('Login failed:', error);
}
};
const fetchData = async () => {
// httpClient automatically handles authentication and token refresh
const response = await httpClient.get('/api/protected');
console.log(response.data);
};
const createUser = async (userData) => {
const response = await httpClient.post('/api/users', userData);
console.log('User created:', response.data);
};
return isAuthenticated ? (
<div>
<button onClick={fetchData}>Fetch Data</button>
<button onClick={() => createUser({ name: 'John' })}>Create User</button>
<button onClick={logout}>Logout</button>
</div>
) : (
<button onClick={handleLogin}>Login</button>
);
}API Reference
AuthConfig
interface AuthConfig {
login_url: string;
refresh_url?: string;
access_expiration_code?: number;
}useAuth Hook
const {
isAuthenticated, // boolean - auth status
login, // (credentials) => Promise<LoginResponse>
logout, // () => void
getLoginResponse, // () => LoginResponse | null - retrieve login response data
isLoading, // boolean - request state
error // string | null - error message
} = useAuth<CustomResponseType>(); // Optional: specify custom response typehttpClient
A pre-configured Axios instance with automatic authentication:
import { httpClient, configureHttpClientDefaults } from '@zhengliu92/react-auth-hook';
// All standard Axios methods are available
await httpClient.get('/api/users');
await httpClient.post('/api/users', userData);
await httpClient.put('/api/users/123', userData);
await httpClient.delete('/api/users/123');
// Automatically handles:
// - Adding Bearer token to requests
// - Token refresh on 401 errors
// - Retrying failed requests after refreshCustom HTTP Client Configuration
Configure the httpClient with custom defaults like baseURL, headers, timeout, etc:
import { configureHttpClientDefaults } from '@zhengliu92/react-auth-hook';
// Configure custom defaults for the httpClient
configureHttpClientDefaults({
baseURL: 'https://api.example.com',
timeout: 10000,
headers: {
'Content-Type': 'application/json',
'X-API-Version': 'v1'
}
});
// Now all requests will use these defaults
await httpClient.get('/users'); // Actually requests: https://api.example.com/users
await httpClient.post('/users', userData); // Includes default headers + auth headerGeneric Login Response
Support for custom API response structures:
// Default structure
interface DefaultLoginResponse {
access_token: string;
refresh_token?: string;
}
// Custom response type
interface CustomLoginResponse {
access_token: string;
refresh_token: string;
user: { id: string; email: string };
permissions: string[];
}
// Usage with custom type
const { login, getLoginResponse } = useAuth<CustomLoginResponse>();
const response = await login(credentials);
// response.user and response.permissions are now available
// Later, retrieve the stored login response
const storedResponse = getLoginResponse();
if (storedResponse) {
console.log('User:', storedResponse.user);
console.log('Permissions:', storedResponse.permissions);
}Key Features
Automatic Token Refresh
Configure refresh_url and access_expiration_code for automatic token renewal when requests fail with the specified status code.
Authenticated Requests
The httpClient automatically adds Bearer tokens and handles token refresh:
import { httpClient, configureHttpClientDefaults } from '@zhengliu92/react-auth-hook';
// All requests automatically include Authorization header
await httpClient.get('/api/users');
await httpClient.post('/api/users', userData);
await httpClient.put('/api/users/123', updatedData);
// You can also use with custom config per request
await httpClient.request({
method: 'GET',
url: '/api/users',
headers: { 'Custom-Header': 'value' }
});
// Or configure defaults that apply to all requests
configureHttpClientDefaults({
baseURL: 'https://api.example.com',
headers: {
'Content-Type': 'application/json'
}
});Persistent Authentication
Authentication state persists across browser sessions using localStorage.
Login Response Access
Use getLoginResponse() to retrieve the full login response data:
const { login, getLoginResponse } = useAuth<CustomLoginResponse>();
// After successful login
await login(credentials);
// Access the full login response data
const loginData = getLoginResponse();
if (loginData) {
// Access any custom fields returned by your API
console.log('User info:', loginData.user);
console.log('Permissions:', loginData.permissions);
}Note: Login response data is stored in memory only and will be null after browser refresh, while tokens are persisted in localStorage for maintaining authentication across sessions.
Requirements
- React 16.8+
- Modern browser with localStorage support
License
MIT
