Skip to content

Instantly share code, notes, and snippets.

@iamstarkov
Last active May 17, 2019 18:03
Show Gist options
  • Save iamstarkov/87741d3b3fbf979a5e77c40805c92125 to your computer and use it in GitHub Desktop.
Save iamstarkov/87741d3b3fbf979a5e77c40805c92125 to your computer and use it in GitHub Desktop.
```
// src/modules/jwt-fetch.js
let token;
const updateToken = x => { token = x };
const getToken = () => fetch('/api/jwt/token').then(extractTokenFromRes);
const refreshToken = () => fetch('/api/jwt/token/refresh').then(extractTokenFromRes);
const jwtFetch = async (url, opts) => {
if (!token) { await getToken().then(updateToken); }
return fetch(url, { ... opts, headers: { ...opts.headers, token }})
.then(res => {
if (hasTokenExpired(res)) {
return refreshToken().then(updateToken).then(() => jwtFetch(url, opts))
}
return res;
}
}
export default jwtFetch;
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment