Authentication Flow Implementation Guide
Implementing core authentication using TanStack Query, Zustand, Axios interceptors, and Secure Storage.
GUIDE-05: Authentication Flow Implementation Guide
Overview
This guide provides practical patterns for implementing secure authentication flows (login, register, logout, session management) in React Native applications, aligned with our core architecture (DOC-01). It leverages TanStack Query for API interactions, Zustand for client-side auth state, an Axios interceptor for seamless token refresh, and secureStorage (DOC-04) for persistent, secure token storage.
🚀 Production-Ready Implementation Available
Want to skip the manual setup? Check out our Authentication Domain for a complete, copy-paste ready solution with:
- TypeScript authentication hooks and services
- Secure token management with automatic refresh
- Authentication context and protected routes
- Comprehensive testing patterns
Perfect for getting authentication working quickly in your project!
🚀 Production-Ready Implementation Available
Want to skip the manual setup? Check out our Authentication Domain for a complete, copy-paste ready solution with:
- TypeScript authentication hooks and services
- Secure token management with automatic refresh
- Authentication context and protected routes
- Comprehensive testing patterns
Perfect for getting authentication working quickly in your project!
When To Use
Use these patterns when implementing:
- Email/Password authentication (Login, Register).
- Token-based session management with automatic refresh.
- Secure persistence of authentication tokens across app launches.
- Integration of authentication state with TanStack Query (GUIDE-01) and Zustand (GUIDE-02).
- Basic structure for handling authentication-related API calls.
- Protected routes based on authentication status.
Note: Social Login and Biometric Login are covered in GUIDE-07 and GUIDE-08, respectively.
🚀 Production-Ready Implementation Available
Want to skip the manual setup? Check out our Authentication Domain for a complete, copy-paste ready solution with TypeScript hooks, secure token management, authentication context, and testing patterns.
Implementation Patterns
1. Sequence Diagram (Login Flow)
(Token refresh happens transparently within the API Client interceptor on subsequent API calls if needed)
2. Authentication Service
Defines functions for interacting with authentication-related backend endpoints (DOC-03).
3. Zustand Authentication Store
Manage authentication state using Zustand.
4. Authentication Hook (useAuth)
Combines Zustand state access with TanStack Query mutations for a unified auth interface.
5. Secure Token Storage (secureStorage)
Uses expo-secure-store for native platforms. (Ensure alignment with DOC-04).
6. Auth Provider (AuthProvider)
Responsible for initializing the auth state from secure storage on app startup.
7. API Client with Token Handling Interceptor
Handles automatic token injection into requests and triggers refresh on 401 errors.
8. Protected Route Components (Conceptual)
Guards access to routes based on authentication status.
Common Challenges
1. Handling Deep Links and Authentication
When a user opens the app via a deep link (e.g., myapp://reset-password/abc), ensure correct routing based on auth status.
Key Idea: Access the Zustand store directly (outside React hooks) within getStateFromPath using useAuthStore.getState() to check isLoggedIn. Modify the initial navigation state returned by getStateFromPath based on the user's auth status and the target route's protection level.
2. Handling Specific API Errors in Login/Register
The useAuth hook exposes loginError and registerError from the mutations. Map backend error codes to user-friendly messages in the UI.
Challenge: Displaying meaningful feedback (e.g., "Invalid Credentials", "Email Taken").
Solution: Inspect the error object in the component using the mutation.
(Do ✅) Define constants for backend error codes. (Consider 🤔) Centralizing error code-to-message mapping in a utility function if used in multiple places.
3. Understanding Token Refresh Robustness
The Axios interceptor handles automatic token refresh.
Key Robustness Features:
- (Concurrency Handling ✅): If multiple API calls fail with 401 while a refresh is ongoing (
isRefreshing === true), subsequent requests are added tofailedQueue. They only proceed after the initial refresh attempt concludes (success or failure). - (Infinite Loop Prevention ✅): The interceptor checks
!originalRequest._retryand the request URL (originalRequest.url !== API_ENDPOINTS.REFRESH_TOKEN) to prevent the refresh logic from triggering itself or retrying indefinitely. - (Refresh Failure Handling ✅): If the
refreshTokenAPI call fails, the interceptor logs the user out (dispatchesclearAuthState, removes header/storage) and rejects all queued requests, ensuring a clean state.
(Be Aware ❗): Ensure the backend's /auth/refresh-token endpoint does not require the (expired) access token for authorization. It should only rely on the provided refreshToken in the request body.
Related Documents
- DOC-01: Core Architecture Reference
- DOC-03: API & State Management Reference
- DOC-04: Security & Offline Framework Reference
- GUIDE-01: Server State Management Guide
- GUIDE-02: State Management Implementation Guide
- GUIDE-06: Offline Support Implementation Guide
- GUIDE-07: Social Login Implementation Guide
- GUIDE-08: Biometric Authentication Implementation Guide