-
-
Save yalamber/23f5790404e1cc5284d8b96c626e26fc to your computer and use it in GitHub Desktop.
Inject an Authorization header into a redux-api-middleware request with a Redux middleware.
This file contains hidden or 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
import { CALL_API } from 'redux-api-middleware' | |
export function fetchLocations() { | |
return { | |
[CALL_API]: { | |
endpoint: 'http://api.somesite.com/api/locations', | |
method: 'GET', | |
// Don't have to manually add the Authorization header to every request. | |
headers: { 'Content-Type': 'application/json' }, | |
types: ['REQUEST', 'SUCCESS', 'FAILURE'] | |
} | |
} | |
} |
This file contains hidden or 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
// ...Likely some other imports such as React etc. | |
import { createStore, applyMiddleware } from 'redux' | |
import { apiMiddleware } from 'redux-api-middleware' | |
// Our custom middleware. | |
import apiAuthInjector from './apiAuthInjector' | |
const store = createStore( | |
reducers, | |
applyMiddleware( | |
apiAuthInjector, // Put it somewhere before `apiMiddleware`. | |
apiMiddleware, | |
) | |
) | |
// ...the rest of your app setup. |
This file contains hidden or 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
import { CALL_API } from 'redux-api-middleware' | |
import ls from 'local-storage' | |
export default function() { | |
return function(next) { | |
return function(action) { | |
const callApi = action[CALL_API] | |
// Check if this action is a redux-api-middleware action. | |
if (callApi) { | |
// Inject the Authorization header from localStorage. | |
callApi.headers = Object.assign({}, callApi.headers, { | |
Authorization: ls.get('id_token') || '', | |
}) | |
} | |
// Pass the FSA to the next action. | |
return next(action) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment