乐闻世界logo
搜索文章和话题

How do I automatically do a refresh token once it expired with react- query / axios ?

1个答案

1

React Query and Axios are widely adopted frontend development tools. React Query is designed for data synchronization, while Axios functions as an HTTP client. When implementing automatic token refresh, we commonly leverage Axios interceptors alongside specific features of React Query to achieve this. Here is an example demonstrating how to automatically refresh the token upon expiration:

First, configure Axios interceptors to manage request and response handling. Before initiating a request, verify the token's presence and attach it to the request headers if available. Upon receiving a response, check for errors caused by token expiration (e.g., HTTP 401 Unauthorized errors). If token expiration is detected, initiate a token refresh operation and retry the original request upon successful refresh.

Here is a simplified code example:

javascript
import axios from 'axios'; import { queryClient } from './reactQuerySetup'; // Assuming the React Query queryClient has been configured // Create an Axios instance const axiosInstance = axios.create({ baseURL: 'https://your.api.endpoint', // Other configurations }); // Request interceptor axiosInstance.interceptors.request.use( config => { const token = localStorage.getItem('accessToken'); // Or other token storage method if (token) { config.headers['Authorization'] = `Bearer ${token}`; } return config; }, error => { return Promise.reject(error); } ); // Response interceptor axiosInstance.interceptors.response.use( response => response, async error => { const originalRequest = error.config; if (error.response.status === 401 && !originalRequest._retry) { originalRequest._retry = true; try { // Assuming you have a refresh token API endpoint const refreshToken = localStorage.getItem('refreshToken'); const response = await axiosInstance.post('/refresh-token', { refreshToken }); const { accessToken } = response.data; localStorage.setItem('accessToken', accessToken); // Update local storage token // Retry the original request with the new token originalRequest.headers['Authorization'] = `Bearer ${accessToken}`; return axiosInstance(originalRequest); } catch (refreshError) { // Token refresh failed; may require re-authentication return Promise.reject(refreshError); } } // If the response is not due to token expiration, return the error directly return Promise.reject(error); } ); // Use axiosInstance to make requests const fetchData = async () => { try { const response = await axiosInstance.get('/some-endpoint'); console.log(response.data); } catch (error) { console.error('Error fetching data', error); } }; fetchData();

In React Query, you can utilize this Axios instance within the global queryFn for making requests. If your application employs React Query hooks like useMutation or useQuery, ensure these requests are executed through the Axios instance configured with interceptors, enabling automatic token refresh handling when expired.

Additionally, React Query provides the QueryClient's setDefaultOptions method to define default behaviors for all queries and mutations, such as retrying on specific errors. However, token refresh logic is better managed at the Axios layer, as it directly pertains to HTTP request handling and response processing.

2024年6月29日 12:07 回复

你的答案