Skip to content
Branch: master
Find file Copy path
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
114 lines (83 sloc) 3.1 KB

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.


$ npm i --save bc-react-session


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

	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';

  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) => {
  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
  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)
    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';

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