Created
December 4, 2018 06:19
-
-
Save ef2k/fdd38e4cb86e484e1e67f4a02bf8e28c to your computer and use it in GitHub Desktop.
jwt middleware
This file contains 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
/** | |
* fetchMiddleware appends a JWT to the header of each fetch action | |
* and checks the response. If a 401 is encountered, it prompts for | |
* a redirect to /login. | |
*/ | |
const fetchMiddleware = (fetch, history) => store => next => (action) => { | |
if (action.type === 'FETCH') { | |
const { url, params } = action; | |
const { token } = store.getState(); | |
if (!params.headers) { | |
params.headers = {}; | |
} | |
params.headers.token = token; | |
return fetch(url, params) | |
.then((response) => { | |
if (response.ok) { | |
return response.json(); | |
} | |
if (response.status === 401) { | |
history.push('/login'); | |
return response.json(); | |
} | |
throw new Error('Network error'); | |
}); | |
} | |
return next(action); | |
}; | |
export default fetchMiddleware; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment