SG
Thus Spoke Zarathustra
The feeling
โ† Back to writing

Cookies. Are they edible?

Notes on cookies and session storage, their differences, and how they are used in web development.

computer programming

The ubiquitous cookie consent popup is a familiar sight when visiting a new website, prompting visitors to "Accept All" or "Reject Non-Essential." In frontend web development, this ties directly into a concept known as client-side storage, which is the practice of storing and managing data directly within the user's browser.

There are three primary reasons websites need to store this data:

  • Personalization: Saving site preferences and settings (like dark mode or language choices).
  • State Management: Retaining previous activity, such as automatically filled form data or active user sessions.
  • Performance: Caching temporary data to ensure faster subsequent page loads.

cookies and session storage

The Mechanics of Client-Side Storage

The mechanics behind the three primary methods of client-side cookies, local storage, and session storage, can be broken down by looking at how web applications function.

Static VS Dynamic Site

To understand why a browser needs to store data locally, it helps to step back and examine how content is delivered.

A static site consists of a combination of hypertext markup files (HTML), stylesheets (CSS), and client-side scripts (JavaScript). These files are usually stored on a virtual private server (VPS) or a content delivery network (CDN). When a user requests a page from a static site, an HTTP request is sent to the server from the browser. The server then responds by returning the pre-built HTML, CSS, and JavaScript files to the browser, which renders the page for the user.

In contrast, a dynamic site generates content based on user interactions, server-side logic, or real-time data. When a user requests a page, the server doesn't just return a file. Instead, it processes the request, performs computations, or queries a database. Only after this processing is complete does it generate the final HTML, CSS, and JavaScript to send back to the browser. Since dynamic site requires server-side processsing per request, the backend architecture splits into multiple layers such as the presentation layer, application logic layer, and data storage layer.

While this multi-layered architecture allows for greater flexibility in implementation, it incurs additional time and network resources. Every time a request is made, the server must go through the entire process of handling the request, executing the necessary logic, and generating the response, which can introduce latency compared to serving pre-built static files. This is where client-side storage, such as cookies, local storage, and session storage, becomes valuable.

By storing frequently accessed information such as user preferences, session tokens or previously loaded data directly on user's device, the browser can skip the back and forth communication with the server for every request, offloading some of the processing and reducing latency.

However, not all data should be stored the same way. The saved information can be categorized based on its capacity or intended lifespan before deciding whether to use cookies, local storage, or session storage.

What are Cookies ๐Ÿช

Cookies are the oldest form of web storage. Essentially, a cookie is a tiny text file at around 4KB in size, saved in the browser by a web server.

Their defining feature is that they are automatically sent back to the server with every single HTTP request. This is how a server recognizes returning users and maintains active sessions as they navigate from page to page. Cookies can be encrypted and given specific expiration dates, meaning they delete themselves after a set amount of time.

Because of their small size and the fact that they travel over the network, cookies are best reserved for small, critical data. For anything larger, alternative storage methods are required.

What is Local Storage?

Introduced with modern HTML, local storage allows web applications to save significantly more data, typically 5โ€“10MB per domain, directly on a device as a long-term cache. This data is not sent to the server with every request, and it has no expiration date. It persists even after the browser is closed and the system is rebooted, remaining there until the user or the web application explicitly deletes it. It is great for saving user preferences, like a chosen language or a theme setting.

How to use local storage

Local storage uses a key-value pair system. Here is how you might save and retrieve a user's theme preference:

// Save data to local storage
localStorage.setItem('key', 'value');
 
// Retrieve data from local storage
const value = localStorage.getItem('key');
 
// Remove data from local storage
localStorage.removeItem('key');
 
// Clear all data from local storage
localStorage.clear();

What is Session Storage?

Session Storage is nearly identical to Local Storage in capacity, but with one crucial difference: its lifespan is tied strictly to the current browser tab. The moment that specific tab or window is closed, the data is permanently erased. This makes it useful for temporary data that shouldn't stick around, such as saving information in a multi-step checkout form so progress isn't lost if the page is accidentally refreshed.

How to use session storage

sessionStorage.setItem('emailDraft', 'Hello, I am writing to...');
 
// Retrieve data from session storage
const emailDraft = sessionStorage.getItem('emailDraft');
 
// Remove data from session storage
sessionStorage.removeItem('emailDraft');
 
// Clear all data from session storage
sessionStorage.clear();

Wrapping Up

Understanding client-side storage is a fundamental step in building web applications that feel fast, responsive, and tailored to the user. In summary:

  • Cookies are the go-to choice for secure session management and authentication due to their ability to mitigate XSS and CSRF attacks.
  • Local Storage is best suited for client-side state management and non-sensitive session data in Single Page Applications, though generally not recommended for storing authentication tokens due to security risks.
  • Session Storage is best for temporary, single-tab data that should disappear the moment the window closes.

Now we know what is going on the next time we click "Accept All" on a cookie popup.

Ate and left no crumbs. ๐Ÿชโœจ

Appreciate this?

Leave a mark.

Loading...