Skip to content
Create and maintain a sessions in react, compatible with React Router (login/logout) and sync with the localstorage
JavaScript
Branch: master
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
dist
docs
src
tests
.babelrc
.gitignore
.travis.yml integrations with travis Oct 2, 2018
README.md
jest.config.js
package.json
webpack.config.js

README.md

React Session Management

Maintenance Tests npm npm GitHub license

Create and maintain persisten login sessions on the browser (even if the website is refreshed). Checkout the live demo.

Note: Extremely easy integration with React Router.

Installation

$ npm i --save bc-react-session

Usage

  1. Open a session by doing Session.login();:
import {Session} from 'bc-react-session';

Session.start({ 
	payload: {
	    // (optional) any info you want to save on the persisten session
	},
	expiration: 86400000; // (optional) defaults to 1 day
});
  1. Close the session by doing Session.destroy();:
import {Session} from 'bc-react-session';

Session.destroy();
  1. Retrieve the session and payload from anywhere
import {Session} from 'bc-react-session';

const session = Session.get();
const { payload } = Session.get();

console.log(session.isValid); // will be true if is not expired or innactive
console.log(payload); // anything you have set on the session payload is stored here

That is it!!

Some other functionalities:

  1. Listen to session changes
// listen to session changes
const unsubscribe = Session.onChange((session) => {
  console.log(session);
  
  if(session.expired) console.log('The session has expired')
  if(session.autenticated) console.log('No one has logged in')
  
});
 
 //unsubscribe to session changes if needed
unsubscribe();
  1. Wait for session expiration callback
// you need to enforce before calling the login method.
Session.onExpiration((session) => session.destroy()); //you can destroy the session if it expires
  1. Change reset the session payload whenever you want
import {Session} from 'bc-react-session';

// pass a new username that will override previous one (if any)
Session.setPayload({
    username: 'alesanchezr'
});
  1. Check session expiration
const session = Session.get();
console.log(session.expired); // boolean
  1. Make a Private Route using react router

The library brings a component called <PrivateRoute /> to make your routes private without any extra code.

import {PrivateRoute} from 'bc-react-session';

<BrowserRouter>
    <div>
        <PrivateRoute exact path='/profile' component={PrivateLayout} />
    </div>
</BrowserRouter>
You can’t perform that action at this time.