Skip to content

Instantly share code, notes, and snippets.

@omsharp
Created September 18, 2021 20:10
Show Gist options
  • Select an option

  • Save omsharp/203079aec8998de891b3f066bee5310a to your computer and use it in GitHub Desktop.

Select an option

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.
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