Authentication Functionality in React + React Query Application
This document focuses on the authentication functionality within your React + React Query application, specifically the components/auth
folder.
Components:
AuthenticateGuard:
- Protects routes requiring authentication.
- Uses
useQueryClient
to access the React Query client. - Retrieves access token from cookies using
cookies.get
. - Fetches user account data using
useMyAccount
and checks its status. - Uses
useRefreshToken
to refresh access token if necessary. - Implements logic to handle various states:
- Loading: Displays
PageLoader
. - Authenticated: Renders child components (
Outlet
). - Un-authenticated: Redirects to the login page (
appRoutes.LOGIN
). - Errors: Handles errors during data fetching or refreshing tokens.
- Loading: Displays
UnAuthenticateGuard:
- Protects routes that should only be accessible to unauthenticated users.
- Uses
useQuery
to fetch the access token from cookies. - Renders child components (
Outlet
) if no token is present (unauthenticated). - Redirects to the home page (
appRoutes.HOME
) if a token is found (authenticated).
Key Functionalities:
- Protected Routes: Ensures access to certain pages only for authenticated users.
- Automatic Token Refresh: Refreshes expired access tokens using the refresh token.
- Error Handling: Handles errors during data fetching and token refreshing.
- Redirection: Redirects users to appropriate pages based on authentication status.
Integration with AppRoutes:
AppRoutes
component utilizes these guards to define protected and unprotected routes.AuthenticateGuard
is used for routes within theDashboard
layout, requiring authentication.UnAuthenticateGuard
is used for routes within theAuth
layout, allowing only unauthenticated users.
Benefits:
- Improved security by protecting sensitive routes.
- Enhanced user experience with seamless token refresh and error handling.
- Clear separation of authentication logic for better maintainability.
Additional Notes:
- This explanation assumes familiarity with React, React Query, and the overall project structure.
- For deeper understanding, consider reviewing the implementation details of each component and related hooks/queries.