redux-token-api-middleware
Alpha software - currently under heavy development
A redux middleware for making calls to APIs with token-based auth, automatically requesting a new token if needed. Actions can be calls to single or multiple API endpoints.
Installation
$ npm install redux-token-api-middleware
Usage
API actions
Actions that will be intercepted by the middleware are identified by the symbol
CALL_TOKEN_API
, and follow the Flux Standard Action pattern, however they must have a payload and have at least an endpoint
in the payload.
Examples
const BASIC_GET_ACTION = 'BASIC_GET_ACTION'const BASIC_POST_ACTION = 'BASIC_POST_ACTION' // basic GET// method defaults to GET if not providedconst basicGetAction = CALL_TOKEN_API: type: BASIC_GET_ACTION payload: endpoint: 'http://localhost/foo' // basic POSTconst basicPostAction = CALL_TOKEN_API: type: BASIC_POST_ACTION payload: endpoint: 'http://localhost/bar' method: 'POST'
Setup
main.js
// example refresh token actionconst refreshAction = CALL_TOKEN_API: type: 'REFRESH_TOKEN' endpoint: 'http://localhost/token' method: 'POST' body: JSON You will need to provide a `retrieveRefreshToken` method to the config that willreturn the refresh token that is used to obtain a token const retrieveRefreshToken = { // This return value is passed to `refreshAction` return localStorage;}; const config = refreshAction retrieveRefreshToken; const apiTokenMiddleware = const store =
API
createTokenApiMiddleware(config)
Creates a Redux middleware to handle API objects.
In the config, you must define at least a refreshAction
method and a retrieveRefreshToken
method, which is used by the middleware to attempt to get a fresh token. This should be an API
action itself.
Other methods can be passed in via config, but have defaults:
// defaults shownconst config = defaultHeaders: 'Content-Type': 'application/json' {}; // To be implemented by the user for refreshing tokens. tokenStorageKey: 'reduxMiddlewareAuthToken' minTokenLifespan: 300 // seconds (min remaining lifespan to indicate new token should be requested) { let token = responsetoken; localStorage; return token; } { let storedValue = localStorage; if !storedValue return null; try return JSON; catch e if e instanceof SyntaxError return null; throw e; } { let tokenPayload = ; let expiry = moment; return expiry > MIN_TOKEN_LIFESPAN; } { const token = ; return token ? : false; } { return headers: Object endpoint body }
Note: retrieveRefreshToken
, storeToken
and retrieveToken
methods may also return
promises that the middleware will resolve.