Refresh Oauth token after certain time in Node API
The normal approach is to handle the 401 Unauthorized
Error, that is used when the token is expired.
let axiosRequest = async (options) => { try { await axios(options) // try to call } catch (err) { if (err.status === 401) { // token is expired let accessToken = await getNewAccessToken(refreshToken) // call the refresh token endpoint to get a new access token options.headers = {Authorization : `Bearer ${accessToken}`} // set the new access token to initial petition return await axiosRequest(options) // call again with new token } throw err } }
A more elegant approach can be found using the axios native interceptors, but couldnt try it:https://gist.github.com/mkjiau/650013a99c341c9f23ca00ccb213db1c