Web services often provide access token and refresh token pairs for authentication. The access token is used to authenticate requests, while the refresh token is used to obtain a new access token when the current one expires. Since the short-lived access token is always being sent around, not the long-lived refresh token, it’s considered a more secure approach.
However, it can be cumbersome to worry about whether the access token is expired or not in every API call. It’s a good idea to implement a function that handles this for you.
Example
In my SvelteKit application, I have a function called obtain
that handles API calls. It checks if the response status is 401 (unauthorized), and if so, it attempts to refresh the token by calling the refreshToken
function. If the refresh is successful, it retries the original request.
|
|
Usage: just like a normal fetch call
|
|
Here, it is assumed that the refresh token is stored in cookie, so the following happens automatically:
- The refresh token is sent to the server
- The server checks if the refresh token is valid
- If valid, the server sends back a new access token, which is also stored in cookie
Conclusion
In my experience, abstracting away this kind of logic makes an application more readable and maintainable.
The example comes from my Review Planner application, which is currently under development.