/    Sign up×
Bounties /Pin to ProfileBookmark

How best to manage token refreshes and repeated failed requests on the front-end?

+ 4,000
Copy linkTweet thisAlerts:
Sep 21.2023

I’m exploring how to handle token refreshes on the front-end and whether a mechanism for retrying failed requests after the access token is refreshed needs to be implemented for each API call. So far, I’ve found refresh-fetch but it seems outdated. Any suggestions on better approaches?

to post a answer
Back-endFront-endFull-stack DeveloperJavaScript

1 Replies

Davinci•003 auto-replyManaging token refreshes and repeated failed requests on the front-end can be a bit tricky, but there are several strategies you can use to handle these situations effectively.

1. **Token Refresh**: When a token expires, you can use a refresh token to get a new access token without requiring the user to log in again. This can be done by sending a request to the server with the refresh token, and the server will respond with a new access token. Here's a simple example:

``javascript
function refreshToken() {
const refreshToken = localStorage.getItem('refreshToken');
fetch('/refresh-token', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ refreshToken }),
})
.then(res => res.json())
.then(data => {
localStorage.setItem('accessToken', data.accessToken);
})
.catch(err => console.error(err));
}
`

2. **Retry Failed Requests**: If a request fails due to an expired token, you can automatically refresh the token and retry the request. This can be done using an HTTP interceptor that catches the error, refreshes the token, and retries the request. Here's an example using Axios:

`javascript
axios.interceptors.response.use(undefined, error => {
if (error.config && error.response && error.response.status === 401) {
return refreshToken()
.then(_ => {
error.config.headers['Authorization'] = 'Bearer ' + localStorage.getItem('accessToken');
return axios(error.config);
});
}
return Promise.reject(error);
});
`

3. **Handle Repeated Failed Requests**: If a request fails repeatedly, it might be best to stop retrying after a certain number of attempts to avoid an infinite loop. You can do this by adding a retry counter to the request config:

`javascript
axios.interceptors.response.use(undefined, error => {
if (error.config && error.response && error.response.status === 401) {
if (!error.config._retryCount) {
error.config._retryCount = 0;
}
if (error.config._retryCount >= 3) {
return Promise.reject(error);
}
error.config._retryCount++;
return refreshToken()
.then(_ => {
error.config.headers['Authorization'] = 'Bearer ' + localStorage.getItem('accessToken');
return axios(error.config);
});
}
return Promise.reject(error);
});
``

Remember to handle the case where the refresh token is also expired or invalid. In this case, you should redirect the user to the login page.

Was this helpful?

×

Success!

Help @cosmic spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 4.30,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,
)...