Skip to content

Instantly share code, notes, and snippets.

@alfonmga
Last active September 5, 2023 22:29
Show Gist options
  • Save alfonmga/9602085094651c03cd2e270da9b2e3f7 to your computer and use it in GitHub Desktop.
Save alfonmga/9602085094651c03cd2e270da9b2e3f7 to your computer and use it in GitHub Desktop.
Apollo refresh auth token link. It tries to refresh the user access token on the fly when API throws out an UNAUTHENTICATED error. If multiple requests fail at the same time, it queues them to re-try them later if we are able to get a new access token, otherwise we log out the user and redirect him to the login page.
@d4rky-pl
Copy link

I tripped over this so badly my face still hurts: If you want to skip the operation, don't do return null but run observer.error(networkError) instead. Otherwise it'll get stuck and the client.query Promise will never get resolved.

@alfonmga
Copy link
Author

alfonmga commented May 6, 2019

@d4rky-pl oh my bad, thank you. I updated it.

@grgurev
Copy link

grgurev commented Jun 15, 2019

Hey please can you explain what is, or maybe to include those files/functions too: buildAuthHeader, getProvider.
I presume that utils/requests is fetch to auth server to get new access token or?? But I really can't tell what is globalProvider ..

@alfonmga
Copy link
Author

alfonmga commented Jun 15, 2019

@grgurev

Hey please can you explain what is, or maybe to include those files/functions too: buildAuthHeader, getProvider.
I presume that utils/requests is fetch to auth server to get new access token or?? But I really can't tell what is globalProvider ..

buildAuthHeader is just a simple function I use to build the authorization header: https://github.com/AMGAVentures/saas-boilerplate/blob/develop/packages/app/src/utils/requests.js

getProvider is where I keep my global application state (user authentication/profile state..etc) check out more about it here: https://github.com/AMGAVentures/saas-boilerplate/blob/develop/packages/app/src/GlobalState.js.

You don't need them to make it works.. you can refactor/tweak those part as you need.

@forrestwilkins
Copy link

I've been struggling to get my refresh token logic to work for multiple failed request for a couple days now, and this finally solved it for me. Thank you for sharing this!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment