feat: implementing the logout feature
Logout Functionality Overview
Key Features
-
API Call First
Attempts to call the backend logout endpoint to invalidate the token on the server side. -
Graceful Error Handling
If the API call fails (for example, token already invalid or network issues), a warning is logged and the logout process continues locally. -
Always Clear Local State
Uses afinallyblock to ensure the local authentication token is always cleared, even if the API call fails.
Related Functions
-
clearAuthToken()
Removes the authentication token fromlocalStorageand sets the auth state tonull. -
apiLogout()
Makes the actual API call to the backend logout endpoint.
Logout Usage
- Available through the
useAuth()hook. - Integrated with Axios interceptors via
setupAuthInterceptors(). - Supports multi-tab synchronization using the
storageevent listener.
Files Related to Logout Functionality
1. api.ts (Lines 640–645)
-
logout()
API function that callsPOST /api/v1/auth/logoutto invalidate the token on the backend.
2. AuthContext.tsx (Lines 2, 11, 106–118)
- Imports
logoutasapiLogoutfromapi.ts. - Exports
logoutfunction in theAuthContextValueinterface. - Implements a
logout()wrapper that:- Calls the backend logout API.
- Clears the local token using
clearAuthToken(). - Handles errors gracefully (continues local logout even if the API call fails).
- Integrated with Axios interceptors via
setupAuthInterceptors().
3. DashboardPage.tsx (Lines 11, 21–22)
- Uses
logoutfrom theuseAuth()hook. - Contains the
handleLogout()function.
4. LoginPage.tsx
- Imports authentication utilities from
@/contexts/AuthContext.
Logout Flow
- User clicks the Logout button → calls
logout()fromuseAuth(). -
logout()inAuthContextcallsapiLogout()fromapi.ts. - API sends
POST /api/v1/auth/logoutto invalidate the token on the server. - Local token is cleared from
localStorageviaclearAuthToken(). - User authentication state is reset to
null, and the user is redirected to the login page.
Edited by Bikkumalla Sai Krishna