title: How to persist login after refresh in react-redux app using JWT
body: <p>In my react/redux app, i have a problem where the app doesn't persist login after refresh. I'm using JWT token for my authentication. Below is my code for the auth actions file named <em>auth.js</em> and my auth reducers file named <em>auth.js</em> as well.</p>
  <p>If there is a way i could make all my private routes check for the token and makes sure that i'm always logged in after refresh, kindly advice.</p>
  <p><strong>My action</strong></p>
  <pre><code>import axios from &quot;axios&quot;;
  import { setAlert } from &quot;./alert&quot;;
  import {
    SIGNUP_SUCCESS,
    SIGNUP_FAIL,
    LOGIN_SUCCESS,
    LOGIN_FAIL,
    LOGOUT,
  } from &quot;./types&quot;;
  
  export const login = (email, password) =&gt; async (dispatch) =&gt; {
    const config = {
      headers: {
        &quot;Content-Type&quot;: &quot;application/json&quot;,
      },
    };
  
    const body = JSON.stringify({ email, password });
  
    try {
      const res = await axios.post(
        &quot;http://localhost:8000/api/token/&quot;,
        body,
        config
      );
  
      dispatch({
        type: LOGIN_SUCCESS,
        payload: res.data,
      });
  
      dispatch(setAlert(&quot;Authenticated successfully&quot;, &quot;success&quot;));
    } catch (err) {
      dispatch({
        type: LOGIN_FAIL,
      });
  
      dispatch(setAlert(&quot;Error Authenticating&quot;, &quot;error&quot;));
    }
  };
  </code></pre>
  <p><strong>My reducer</strong></p>
  <pre><code>import {
      LOGIN_SUCCESS,
  } from '../actions/types'
  
  const initialState = {
      token: localStorage.getItem(&quot;token&quot;),
      isAuthenticated: null,
      loading: false
  }
  
  export default function(state = initialState, action) {
      const { type, payload } = action
  
      switch (type) {
        case LOGIN_SUCCESS:
          localStorage.setItem(&quot;token&quot;, payload.access);
          return {
            ...state,
            isAuthenticated: true,
            loading: false,
            token: payload.access,
          };
  }
  </code></pre>
  <p><strong>My index.js</strong></p>
  <pre><code>import React from 'react';
  import ReactDOM from 'react-dom';
  import { Provider } from &quot;react-redux&quot;;
  import store from &quot;./store&quot;;
  import './index.css';
  import App from './App';
  import * as serviceWorker from './serviceWorker';
  
  
  ReactDOM.render(
    &lt;React.StrictMode&gt;
      &lt;Provider store={store}&gt;
        &lt;App /&gt;
      &lt;/Provider&gt;
    &lt;/React.StrictMode&gt;,
    document.getElementById(&quot;root&quot;)
  );
  </code></pre>
  <p><strong>Edit:</strong> I have been adviced localStorage is not safe, if <strong>cookies</strong> is a safer alternative. Kindly assist with the solution implementation.</p>