Skip to content

Instantly share code, notes, and snippets.

@berkin
Last active August 16, 2018 11:08
Show Gist options
  • Save berkin/d173f54cd03833e049f3dd66d432d78a to your computer and use it in GitHub Desktop.
Save berkin/d173f54cd03833e049f3dd66d432d78a to your computer and use it in GitHub Desktop.
redux authorization header middleware
import axios from 'axios'
export default ({ getState }) => next => action => {
const prevToken = getState().auth.access_token
// if authorization header is null and we have token, set it for the next action
if (!axios.defaults.headers['Authorization'] && prevToken) {
axios.defaults.headers['Authorization'] = `Bearer ${prevToken}`
}
const result = next(action)
const currentToken = getState().auth.access_token
// if the token is changed or set, set it to axios headers.
if (
prevToken !== currentToken ||
currentToken !== axios.defaults.headers['Authorization']
) {
currentToken
? (axios.defaults.headers['Authorization'] = `Bearer ${currentToken}`)
: delete axios.defaults.headers['Authorization']
}
return result
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment