Skip to content

Instantly share code, notes, and snippets.

@ef2k
Created December 4, 2018 06:19
Show Gist options
  • Save ef2k/fdd38e4cb86e484e1e67f4a02bf8e28c to your computer and use it in GitHub Desktop.
Save ef2k/fdd38e4cb86e484e1e67f4a02bf8e28c to your computer and use it in GitHub Desktop.
jwt middleware
/**
* 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