Created
September 18, 2021 20:10
-
-
Save omsharp/203079aec8998de891b3f066bee5310a to your computer and use it in GitHub Desktop.
A custom fetch function for Apollo Client to handle authentication error and refresh JWT token.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const customFetch = async ( | |
| uri: RequestInfo, | |
| options: RequestInit | undefined | |
| ) => { | |
| const response = await fetch(uri, options); | |
| const bodyJson = await response.json(); | |
| if ( | |
| bodyJson && | |
| bodyJson.errors && | |
| bodyJson.errors[0] && | |
| bodyJson.errors[0].message === 'Unauthorized' | |
| ) { | |
| return refresh().then((userData) => { | |
| if (userData) { | |
| // success: set the access token in the current header | |
| if (options?.headers) { | |
| options.headers = { | |
| ...options?.headers, | |
| authorization: `Bearer ${userData.accessToken}`, | |
| }; | |
| } | |
| // refetch with the new access token | |
| return fetch(uri, options); | |
| } else { | |
| // failed: move to login screen and logout user | |
| history.push('/login'); | |
| return fetch(uri, { | |
| method: 'POST', | |
| headers: { | |
| 'Content-Type': 'application/json', | |
| }, | |
| body: JSON.stringify({ | |
| query: ` | |
| query { | |
| logout | |
| } | |
| `, | |
| variables: {}, | |
| }), | |
| }); | |
| } | |
| }); | |
| } | |
| // no error - repackage and return the current response | |
| return new Response(JSON.stringify(bodyJson), options); | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment