react-auth-service
v0.0.2
Published
Reusable React **authentication library** with JWT handling, Axios interceptors, and routing helpers.
Readme
React Auth Service
Reusable React authentication library with JWT handling, Axios interceptors, and routing helpers.
⚠️ Routing and navigation are owned by the consumer app. This library provides UI, auth state, and API handling — not app routes.
Why this package?
Most apps repeat the same authentication logic:
- Login & signup UI
- JWT storage and refresh handling
- Protecting routes
- Attaching tokens to API calls
Auth UI centralizes this logic into a reusable package so consumer apps can focus on business features.
Features
- 🔐 Login & Signup UI (
AuthForm) - 👤 User profile UI (
UserProfile) - 🧠 Central auth state via
AuthProvider - 🛡️ Public & Protected route guards
- 🔄 Axios interceptor with automatic token refresh
- 🚫 Global session-expired handling
Installation
npm install react-auth-serviceRequired setup (important)
Auth Initialization (Mandatory for Consumer Apps) Purpose of initAuth()
initAuth() initializes the authentication service and configures the internal Axios instance with the backend API base URL.
This allows:
Dynamic backend URL configuration
Automatic token attachment
Refresh token handling
Environment-specific backend switching (local / QA / UAT / prod)
Without calling initAuth(), the auth service will not work.
⚠️ Mandatory Initialization Step
Before rendering the React application, the consumer app must call initAuth() exactly once.
✅ Correct Usage
import { initAuth } from 'react-auth-service';
await initAuth({
apiBaseUrl: 'http://localhost:9000', // Backend running URL
});1️⃣ Wrap your app with AuthProvider and BrowserRouter
import { BrowserRouter } from 'react-router-dom';
import { AuthProvider } from 'react-auth-service';
<BrowserRouter>
<AuthProvider>
<App />
</AuthProvider>
</BrowserRouter>
BrowserRoutermust be declared once in the consumer app.
Routing helpers
This package does not define routes. Instead, it provides helpers you can compose with your routes.
PublicRoute
Used for pages like Login / Signup.
- Accessible only when user is not authenticated
- Redirects authenticated users
<Route
path="/"
element={
<PublicRoute redirectTo="">
<AuthForm onLoginSuccess={login} />
</PublicRoute>
}
/>ProtectedRoute
Used for private pages.
- Blocks unauthenticated access
- Redirects to login page
<Route
path="/profile"
element={
<ProtectedRoute redirectTo="">
<UserProfile onLogout={logout} />
</ProtectedRoute>
}
/>Auth flow (how it works)
Login
- User submits login form
- Login API returns
accessToken - Token is stored in memory
AuthContextupdates auth state- Consumer app handles navigation
setAccessToken(token);
localStorage.setItem('isLoggedIn', 'true');Signup
- User submits signup form
- Password is validated on client
- Registration API is called
- User is redirected to login mode
Axios interceptor (core logic)
This package exports a preconfigured axiosInstance.
What it does
- Attaches
Authorization: Bearer <token>automatically - Skips auth headers for login & signup APIs
- Refreshes token automatically on expiry
- Queues failed requests during refresh
- Logs out user if refresh fails
Usage in consumer app
import { axiosInstance } from 'react-auth-service';
axiosInstance.get('/api/orders');You must use axiosInstance instead of raw Axios to get auth benefits.
Session expiration handling
If refresh token fails:
- User is logged out
- Session-expired flag is stored
- App redirects to login page
On next load, AuthForm detects this and shows a session-expired message.
Auth state management
Auth state is managed via AuthContext.
const { isAuthenticated, login, logout } = useAuth();- State is persisted using
localStorage - Token is cleared on logout
- Context ensures route guards stay in sync
UserProfile component
- Fetches user details on mount
- Uses
axiosInstanceinternally - Calls logout API on logout
- Delegates navigation to consumer
<UserProfile onLogout={logout} />Consumer responsibilities
The consumer app must:
- Own routing and navigation
- Provide backend APIs
- Configure endpoints
- Wrap app with
AuthProvider - Use provided
axiosInstance
This library does not:
- Create routes
- Handle databases
- Manage backend authentication
Backend expectations
Your backend should provide:
POST /login→ returnsaccessTokenPOST /registerPOST /refresh-token(cookie-based)GET /user-detailsPOST /logout
JWT-based authentication is assumed.
Common mistakes
❌ Importing Axios directly instead of axiosInstance
❌ Wrapping BrowserRouter multiple times
❌ Using useAuth outside AuthProvider
❌ Expecting this package to control routing
Summary
Auth UI provides:
- UI components
- Auth state management
- Secure API handling
You control:
- Routing
- Navigation
- Backend
This separation keeps your app flexible, secure, and scalable.
License
MIT
