DEV Community

Cover image for Session & cookies  strategy in web applications
elhousseyn arab
elhousseyn arab

Posted on

Session & cookies strategy in web applications

i want to ask a question about how web applications keep your account open on web browser even you close the browser then re open it ex : facebook
how they do keep your account open, they use the session backend or they use localstorage of the web api js to keep it? thank you

Top comments (1)

weisk profile image

one way you can do it is like this:

  • when the user logs in, respond with an auth token. The webapp can store that token in the localStorage.
  • when the webapp is initialized, assume that the user is logged in if we have an auth token on the localstorage.
  • There must be a middleware on all the webapp's XHR handlers, that adds an authorizarion header on each request.
  • The backend has to have a mechanism to verify that token, and if it's not sent or is invalid, return a 403 forbidden status.
  • The webapp also has a middleware for every XHR response handler, that will catch whenever a 403 happens. In that case, unset the localStorage token, and redirect the user to login.

That could be one way to do it; as in how to save application state, the answer is also in localStorage. In this subject you also have to bear in mind that for this to be efficient, your app's state should be kind of "serialized" and kind of "normalized".

I suggest you research on the following topics:

  • cookies vs localstorage vs sessionstorage vs indexedDb
  • Authentication token mechanisms, e.g. JWT
  • Common patterns to normalize an app's state