redux-sessions
App-wide session management in Redux.
This library allows the straightforward management of global session state via Redux action creators and selectors. It also includes functionality for persisting session state in local storage out of the box.
Example
// First, include the sessions reducer keyed under 'sessions' in your root reducer const reducer = // Then, include the sessions enhancer to enable persistence in local storage const enhancers = const store = // Now you can dispatch session actions const action = sessionsActionsstore // And access session information from the state const state = store sessionsSelectors// => 'A session token!'
API
Action creators
redux-sessions
exposes the following action creators, namespaced under actions
:
actions.setToken(token, options)
: Set a session token in the state.actions.clearToken(options)
: Clear a session token from the state.actions.login(token, options)
: An alias foractions.setToken()
.actions.logout(options)
: An alias foractions.clearToken()
.
The options
object passed to these action creators may contain the following attributes:
userType (default='user')
: A string identifying which type of user the session token belongs to. This option is useful if you need to allow different types of users to log into different parts of your application concurrently.persist
: A flag indicating whether to persist the token across sessions- under the hood, this flag determines whether the token is saved inlocalStorage
orsessionsStorage
.
Enhancer
The redux-sessions
enhancer is what allows the session state to persist across page refreshes. It can receive the following options:
persist (default=true)
: A flag indicating whether or not to persist session state.
Selectors
redux-sessions
exposes the following state selectors, namespaced under selectors
:
selectors.token(state, options) -> string
: Retrieves a session token from the state.selectors.isAuthenticated(state, options) -> bool
: Returnstrue
when a session token exists.selectors.isUnauthenticated(state, options) -> bool
: Returnstrue
when a session token does not exist.
The options
object passed to these selectors may contain the following attributes:
userType (default='user')
: A string identifying which type of user to retrieve information for.
Reducer
redux-sessions
exposes a reducer to handle the actions it creates. This reducer must be attached to your root reducer using the key sessions
in order for the library to function (see example).
Authentication example
Here's a simple example of how redux-sessions
can be used to conditionally display an authenticated portion of an app:
// This component is passed an external auth function that resolves with a session token. { return <div> isAuthenticated && <div> Only an admin can see this! </div> <button onClick= > Login </button> </div> } { return isAuthenticated: sessionsSelectors } const mapDispatchToProps = login: sessionsActionslogin mapStateToProps mapDispatchToPropsView