Data Persistence (Cookies, Sessions, Tokens, LocalStorage and SessionStorage)

samirabawad

Samira Awad

Posted on August 15, 2024

Data Persistence (Cookies, Sessions, Tokens, LocalStorage and SessionStorage)

In this article, we will explore how data persistence on the web works in two parts. First, we’ll cover how to store authentication information using cookies with sessions or tokens. Next, we’ll look at how browser-side persistence is handled to store user preferences, using cookies for identification and localStorage or sessionStorage to store those preferences.

Introduction:

To understand data persistence in web applications, it is essential to understand how the browser and web server interact:

• HTTP (Hypertext Transfer Protocol): This protocol facilitates communication between the browser and the server, but it is stateless, meaning it does not retain information about previous interactions.

• Request and Response: Every time a user visits a URL or interacts with a website, the browser sends a request to the server, and the server responds with the requested information.

Need for Persistence: Due to the stateless nature of HTTP, cookies were created so that servers could remember users and their preferences on future visits.

1. Cookies

Cookies are small pieces of information that a website sends to the user’s browser to be stored locally. They are represented as key-value pairs, where the key acts as an identifying tag for the cookie. A website can set multiple cookies, and on each subsequent request, the browser sends these cookies to the server, allowing the latter to respond with a personalized page.

Cookies Features:

• Storage: Cookies are saved in the user’s browser and can be accessed by client-side scripts (JavaScript).

• Use: They are widely used to personalize the user experience, remember language preferences, keep user sessions logged in, and track ads.

• Security: Cookies can be vulnerable if they are not configured correctly, especially against XSS (Cross-Site Scripting) attacks. Therefore, it is not advisable to store sensitive data in them.

Duration: Cookies can be session cookies (they are deleted when you close the browser) or persistent cookies (they remain for a defined time).

History and Operation:

Cookies were created in 1994 to enable state persistence in web interactions. The name comes from the analogy with fortune cookies, which contain a message inside. Initially, there was no way to remember user preferences or identify the user, which meant that all users saw the same version of the website.

• Basic Operation: Cookies are automatically sent with each HTTP request to the server. These may be your own (created by the website you visit) or third parties (created by external servers, such as ad servers).

• Types of Cookies:

  • Own cookies: Associated with the domain of the website that the user visits.

  • Third-party cookies: Associated with external domains, such as ad servers, for advertising tracking and personalization.

Limitations and Safety Considerations:

• Size: Limited to 4 KB.

• Vulnerability: They can be attacked or modified if they are not configured correctly.

• Duration: They can be session (deleted when closing the browser) or persistent (with a defined expiration date).

How Cookies Work in State Persistence:

  1. Login and Initial Authentication: When a user enters a website for the first time, they enter their credentials and log in.

  2. Server Response: The server responds with the home page and adds a header called 'Set-Cookie', assigning a cookie with the name 'sessionid' and a numeric value. This is a session identifier.

  3. Cookie Establishment: The browser stores this cookie with the name and value assigned by the server.

  4. Subsequent Requests: In future requests, such as accessing the order history, the browser includes the cookie in the Cookie header, allowing the server to identify the user and validate their session, without needing to request their credentials again.

  5. Server Identification and Response: The server uses the sessionid value to identify the user and respond with the requested information, maintaining state persistence during the session. If the user logs out or the session expires, the cookie is invalidated.

Alternatives to Cookies for Authentication:

Cookies allow session-based authentication, but there are security risks. For this reason, alternatives have been developed such as tokens (JWT, OAuth), which allow secure and controlled authentication without storing confidential information directly in cookies. Tokens are best suited for scenarios involving multiple parties who may not trust each other.

2. Authentication and Sessions

Cookie-based and token-based authentication are widely used methods, and in many cases, they are used in a complementary way. For example, a mobile app might use tokens, while a website of the same service might use cookie-based authentication.

Sessions vs Tokens Based Authentication:

• Authentication with Cookies and Sessions: This method involves only the user and the server. Cookies are used to keep the session logged in and remember the user with each request, giving them access to all available information. Sessions have a certain lifespan, which may expire after a period of inactivity or upon closing the session. They emerged as a solution to overcome the security limitations of cookies, allowing more secure authentication.

• Token Authentication: This approach is used in scenarios where multiple parties are involved, such as in mobile applications. Tokens, like JWT, are temporary keys that provide limited access to user data without exposing their credentials. These tokens have a limited lifespan and can be invalidated if necessary.

If a user decides to revoke access, they can invalidate the token, detaching it from the account. Tokens can be issued using protocols such as JWT, OAuth2, or OpenID. A JWT token, for example, can contain crucial information such as the token’s scope, creation date, and expiration date. This information is cryptographically signed, which ensures the integrity of the token and makes it impossible to modify it without invalidating it.

Data persistence in the browser:

Cookies, localStorage and sessionStorage are three web storage mechanisms that operate on the browser side, not on the server. Of these, only cookies can be automatically sent to the server with each request. Instead, localStorage and sessionStorage store data exclusively on the client side. The key differences between them lie in their persistence, storage capacity, and data Access.

Cookies:

Cookies are the oldest and most traditional method of storing user information in the browser, such as authentication or shopping cart data. They are stored as text and are accessible from any browser window, that is, if multiple windows of the same website are opened, the same cookie and its value will be available.

Every time the browser makes a request to the server, it attaches all the cookies associated with the domain, allowing the server to process them. Although useful for user authentication and tracking, cookies are limited to 4 KB of storage and are not ideal for storing large volumes of information. Furthermore, since they are sent automatically with each HTTP request, cookies can be vulnerable to attacks, so it is not advisable to store sensitive data in them.

localStorage and sessionStorage:

To overcome the limitations of cookies, localStorage and sessionStorage were introduced, two browser APIs that allow data to be stored more flexibly and with greater capacities. The main difference between the two is their persistence: data in sessionStorage is deleted when you close the browser, while in localStorage it persists until deleted manually or by code.

Both mechanisms offer a storage capacity that varies between 5 MB and 10 MB, depending on the browser. Unlike cookies, data in localStorage and sessionStorage is not sent with every HTTP request, making them safer for storing information on the client side, although they still require precautions to prevent unauthorized access from malicious scripts.

Comparison: Cookies vs localStorage vs sessionStorage

Cookies:

• Definition: Fragments of information sent by a website to the user’s browser for local storage.

• Storage: Saved in the browser and sent automatically with each HTTP request.

• Use: Mainly for user authentication and tracking. They are accessible in all browser windows.

• Duration: They can be session or persistent, with a defined expiration date or manual deletion.

• Security: Vulnerable to XSS attacks if not configured correctly. It is not recommended to store sensitive data.

Size: Limited to 4 KB.

localStorage:

• Definition: Browser API that allows persistent data to be stored in the user’s browser.

• Storage: Exclusively in the browser, not sent with each HTTP request. The information is unique for each origin (URL protocol and domain).

• Duration: Persistent between sessions, not deleted when closing the browser. The data remains until it is deleted manually or via code.

• Capacity: Generally between 5 and 10 MB.

• Use: Ideal for storing data that needs to persist beyond the user session, such as user settings or application states, since they do not have an expiration time. For example, they are used to improve the user experience, storing their preferences such as the browser theme, languages, among others, avoiding the need to ask the user repeatedly.

sessionStorage:

• Definition: Similar to localStorage, but with persistence limited to the current browsing session.

• Storage: Exclusive in the user’s browser. It is not sent with every HTTP request. Each tab has its own independent sessionStorage.

• Duration: Only persists during the browsing session; It is removed when you close the tab or window.

• Capacity: Similar to localStorage (5–10 MB).

• Usage: Useful for storing temporary data that should only exist during the current browsing session, such as partially completed forms.

Storage Security and Accessibility:

Data in localStorage, sessionStorage, and cookies can be viewed and manipulated from the browser console, so it is not recommended to store sensitive information in them.

How to use localStorage and sessionStorage:

Both localStorage and sessionStorage are objects in JavaScript’s global window variable. Both store data in key-value pairs, where both keys and values ​​are strings.

1. Save data:

localStorage.setItem(‘key’, ‘value’);

sessionStorage.setItem(‘key’, ‘value’);

2. Get data:

const value = localStorage.getItem(‘key’);

const value = sessionStorage.getItem(‘key’);

3. Delete data:

localStorage.removeItem(‘key’);

sessionStorage.removeItem(‘key’);

4. Delete all data:

localStorage.clear();

sessionStorage.clear();

Example:

Image description

💖 💪 🙅 🚩
samirabawad
Samira Awad

Posted on August 15, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related