title: How to detect expired user session in a react app?
body: <p>I am developing a REST API based on Node / Express and a frontend for it based on React / Redux. Users can login (which gives them access to additional functionality) but they can use basic functionality also without logging in.</p>
  
  <p>When a user logs in, the client makes an HTTP call with the credentials, the server creates a session and returns a user object (user_id and some other data) as well as a session cookie. The React app saves the user object in its Redux state. In subsequent HTTP calls, the user is authenticated through the cookie.</p>
  
  <p>When rendering the user interface, the React app determines whether it is logged in or not by checking for a user object in its state. This is used to grey out some buttons which are only available to logged in users, or to hide the login link when the user is already logged in.</p>
  
  <p><strong>The problem</strong></p>
  
  <p>It could occur that the session expires, or that the user logs out in a different browser tab. The React app has no way of knowing this and thinks it is still logged in (i.e. app state mismatches reality), leading to wrong UI display.</p>
  
  <p><strong>What pattern to solve this?</strong></p>
  
  <ul>
  <li>Put a hook on all Ajax calls to check for 401 and update the
  state?</li>
  <li>Return session state in HTTP headers (and then?)</li>
  <li>A Comet pattern for the server to notify the client that it has been logged out? (not a REST API anymore then)</li>
  <li>Additional calls before actual API calls to make sure user is still logged in? (seems wasteful)</li>
  </ul>
  
  <p>And how to deal with this once the client detects it is no longer logged in during an ongoing operation? I'd prefer to handle this in one place rather than all functions making API calls...</p>
  
  <p><strong>I'd be thankful for some best practice!</strong></p>