Setup authentication & authorization in Reactjs

Handling refresh

Your app is ready and you’re able to log in, but if you refresh, your login information is gone.

While it’d be nice if your users never refreshed your page after login, it’s not feasible to expect this behavior from your users, and you’d surely be left with users either complaining or leaving your site and never coming back.

What we need to do is find a way to inject the previous state in our stores upon initializing. Fortunately, this is not very hard; we just need a secure place to store the data that we want to survive a refresh.

To this end, we’ll use sessionStorage. It is similar to localStorage, the only difference being that while data stored in localStorage has no expiration set, any data stored in sessionStorage gets cleared when the page session ends.

A session lasts for as long as the browser window is open and it survives page reloads and restores.

It doesn’t support opening the same page in a new tab or a window, which is the main difference between this and, for instance, session cookies.

The first thing we’ll do is change actions/login.js and modify the function setLoginDetails. Replace the function with this code (and note that now we will export it):

export function setLoginDetails(json) {
  const loginData = {
    type: LOGIN_USER,
    loginResponse: json,
    timestamp: Date.now()
  };
  sessionStorage.setItem('login',JSON.stringify(loginData));
  return loginData;
}

We’ll then enter index.jsx and add the function to our imports. Add it to the line with imports from actions/login like this:

import { login, setLoginDetails } from './actions/login'

And then, we’ll add a new function within the App class:

componentWillMount() {
  const { dispatch, } = this.props;
  let storedSessionLogin = sessionStorage.getItem('login');
  if(storedSessionLogin){
    dispatch(
      setLoginDetails(
        JSON.parse(storedSessionLogin).loginResponse)
      );
    }
  }

Before the component mounts, it will check whether there’s a stored entry inside sessionStoragethat holds the user info. If there is, it will dispatch an action call to setLoginDetails, which will simply set the state to logged in and display the familiar welcome message.

And that’s all you need to do.

There are other ways to inject a state than by simply dispatching actions. You could do it in the mapStateToProps function and set an initial state based on sessionStorage, session cookies, or some other source of data (we’ll come back to this when making an isomorphic app).

About the author

Deven Rathore

Deven Rathore

I'm Deven Rathore, a multidisciplinary & self-taught designer with 3 years of experience. I'm passionate about technology, music, coffee, traveling and everything visually stimulating. Constantly learning and experiencing new things.

Pin It on Pinterest

Shares