title: How to logout user when token expires in react app
body: <p>I am working on a app where I am using React as my front-end and <code>React-apollo-graphql</code> for my API calling.</p>
  <p>I am using <code>react-hooks</code> i.e in React 16.8 +.</p>
  <p><strong>What I am doing</strong></p>
  <p>I have crated a <code>auth.js</code> file where I am storing my values when user is loging in and also checking the token is it valid or not, (expiry I am checking), but that file is only loading my I am refreshing or reloading the page, That is not  how it should work</p>
  <p><strong>My auth.js file</strong></p>
  <pre><code>const initialstate = {
      user: null,
  };
  if (localStorage.getItem(&quot;JWT_Token&quot;)) {
      const jwt_Token_decoded = Jwt_Decode(localStorage.getItem(&quot;JWT_Token&quot;));
      console.log(jwt_Token_decoded.exp * 1000);
      console.log(Date.now());
      if (jwt_Token_decoded.exp * 1000 &lt; Date.now()) {
          localStorage.clear(); // this runs only when I refresh the page or reload on route change it dosent work
      } else {
          initialstate.user = jwt_Token_decoded;
      }
  }
  
  const AuthContext = createContext({
      user: null,
      login: (userData) =&gt; {},
      logout: () =&gt; {},
  });
  const AuthReducer = (state, action) =&gt; {
      switch (action.type) {
          case &quot;LOGIN&quot;:
          return {
              ...state,
              user: action.payload,
          };
          case &quot;LOGOUT&quot;:
          return {
              ...state,
              user: null,
          };
          default:
          return state;
      }
  };
      
  const AuthProvider = (props) =&gt; {
      const [state, dispatch] = useReducer(AuthReducer, initialstate);
      const login = (userData) =&gt; {
          localStorage.setItem(&quot;JWT_Token&quot;, userData.token);
          dispatch({
          type: &quot;LOGIN&quot;,
          payload: userData,
          });
      };
      const logout = () =&gt; {
          localStorage.clear();
          dispatch({ action: &quot;LOGOUT&quot; });
      };
      
      return (
          &lt;AuthContext.Provider
          value={{ user: state.user, login, logout }}
          {...props}
          /&gt;
      );
  };
      
  export { AuthContext, AuthProvider };
  </code></pre>
  <p>As I have commented the line where I am checking the token expiry.</p>
  <p>My only issue is why it is working on page reload not on each route like we  do in store file when we use Redux.</p>
  <p><strong>My App.js</strong></p>
  <pre><code>&lt;AuthProvider&gt;
    &lt;Router&gt;
      &lt;div className=&quot;App wrapper&quot;&gt;
        &lt;Routes/&gt;
      &lt;/div&gt;
    &lt;/Router&gt;
  &lt;/AuthProvider&gt;
  </code></pre>
  <p><strong>My index.js</strong></p>
  <pre><code>import React from 'react';
  import ReactDOM from 'react-dom';
  import App from './App';
  import ApolloClient from 'apollo-boost'
  import { ApolloProvider } from '@apollo/react-hooks';
  import { InMemoryCache } from 'apollo-cache-inmemory';
      
  const client = new ApolloClient({
    uri: 'my url',
    cache: new InMemoryCache(),
  });
  ReactDOM.render(
    &lt;ApolloProvider client={client}&gt;
      &lt;App /&gt;
    &lt;/ApolloProvider&gt;,
    document.getElementById('root')
  );
  </code></pre>
  <p><strong>Important points</strong></p>
  <p>As I am using <code>react-apollo-graphql</code> so do they provide ant Authentication flow ? like how redux does, we have to create a store file which will store our data</p>
  <p>I am using React 16.8 + so I am using react-hooks so here I am using <code>use Reducer</code> from that only.</p>
  <p>My only question is am I doing it right? I am open to other approaches.</p>
  <p>I have done authentication and authorization in Vue using Vuex there I use to create a store file which runs on ever route</p>
  <p>Same I have done with Redux, In my store file I use to store the states and all.</p>
  <p>Now if I am using react-hooks and react-apollo-graphql so no need to do this things with redux.</p>
  <p><strong>I am using <code>apollo-link-context</code></strong> for passing the header (Authorization) like below</p>
  <pre><code>const authLink = setContext(() =&gt; {
    const token = localStorage.getItem('JWT_Token')
    return {
      headers:{
        Authorization: token ? `${token}` : ''
      }
    }
  });
  </code></pre>
  <p>I think here I can check on each route or on each request if the token is valid or not ( check exp time) if it is invalid then I will logout and clear my local storage, Clearing the storage is not a big deal the main thing is how to redirect to login page.</p>