0

I'm creating a React frontend that makes authenticated requests to an Express backend using a cookie with a session ID stored.

I would like to know what is standard for dealing with authentication state and keeping that up-to-date—more specifically, if an admin user is modifying properties of a currently signed in user (or, say, the user clicks "sign out from other sessions" on another device), how do we keep that up to date in our React app rather than just having API requests fail but the user stays logged in due to frontend state becoming out-of-sync?

For example, Google Docs will display a message very quickly if access is revoked. I assume this is partly because they're using something similar to web sockets to maintain a continuous connection, but if we're making HTTP API requests, what are some industry standard approaches to keeping the current signed in user on the frontend up-to-date?

Some initial ideas:

  1. Have it stored in a global store like Redux, and wrap each API request in a handler that catches a 401 (forbidden, sent when user isn't authorized) and dispatches an action to log out. Then when the state is updated to be not logged in, the user gets redirected to /login. Con: we can't know of a change of user settings, just whether they got signed out.
  2. On each request, sending another API request to check current user info and update the state based on this. Has the benefit of keeping up to date on every action, but seems rather inefficient in terms of network requests made.

The most ideal scenario seems to somehow be to "push" to the client a notification that something has changed so the frontend can update accordingly. I don't see this being feasible without using long polling or sockets.

Please note that rather than with this question which is asking more about dealing with the authentication itself, this is about keeping this "cached" state information consistent with what's in the backend.

rb612
  • 5,280
  • 3
  • 30
  • 68

1 Answers1

1

What I do is something very similar to your ideas.

1) Keep the user login status and settings in redux 2) Whenever the user changes a setting, the api response sends back an updated settings object that goes to the redux store to keep it updated.

There aren't more requests because the updated setting object comes in the response of the request made to change the settings.

Hope it helps

guillo
  • 39
  • 1
  • 3