DEV Community

Cover image for Cookies, Local Storage, and Session Storage: Which One Is Best for Your Web App?
Mainul Hasan
Mainul Hasan

Posted on • Edited on • Originally published at webdevstory.com

Cookies, Local Storage, and Session Storage: Which One Is Best for Your Web App?

Table of Contents

  1. Cracking the Code: How Do Cookies Work?
  2. An Overview of Local Storage
  3. The Flexibility of Session Storage
  4. Comparative Analysis: Cookies, Local Storage, and Session Storage
  5. Choosing the Best Storage for Your Web App
  6. Test Your Knowledge: Quick Quiz Time
  7. Further Readings and Resources

Web Storage Methods: Cookies, Local Storage, and Session Storage

Web development is a world full of numerous tools and technologies, each with its unique way of handling data. One key aspect of web development is understanding how to manage and maintain user data across sessions.

The web, inherently stateless, treats each server request independently. So, how do we create a smooth, continuous, and personalized user experience across multiple sessions and requests?

The answer lies in web storage methods: Cookies, Local Storage, and Session Storage. These tools work silently in the background, storing and retrieving data as needed to provide a seamless user experience.

But when do you use one over the others? How do you decide which tool is right for your web application?

The choice significantly shapes your application's performance, efficiency, and user experience.

This article dives into each of these tools, helping you understand their workings, strengths, limitations, and ideal use cases. So, let's get started on this journey toward mastering web storage methods.

Cracking the Code: How Do Cookies Work?

In simple terms, cookies are small text files that websites send to your browser and store for later use. When you visit the website again, the cookie data is sent back to the server.

Cookies is being used for a long time since the early days of the web and have a maximum size limit of 4KB.

Mainly, cookies were created to provide a reliable mechanism for websites to remember stateful information.

Cookies are commonly used for:

  • Session management: To keep a user logged in.
  • Personalization: Remembering user settings and preferences.
  • Tracking: Recording user behavior on a site.

Cookies Code Example - User Authentication

Suppose a user logs into a web application. The server creates a session for the user and sends a cookie containing the session ID back to the user’s browser. This cookie is saved in the browser of the user.

For subsequent requests from the user, the browser sends the cookie back to the server, and the server uses the session ID in the cookie to identify the user and provide personalized content.

// Logging in
function login(username) {
  const oneHour = 60 * 60 * 1000; // in milliseconds
  const expires = new Date(Date.now() + oneHour);
  document.cookie = `username=${username}; expires=${expires.toUTCString()}; path=/`;
}

// Verifying the session
function verifySession() {
  const username = getCookie("username");
  if (username) {
    console.log(`User ${username} is logged in`);
  } else {
    console.log("No active session");
  }
}

// Get a specific cookie
function getCookie(name) {
  const cookieArr = document.cookie.split("; ");
  for(let i = 0; i < cookieArr.length; i++) {
    const cookiePair = cookieArr[i].split("=");
    if (name == cookiePair[0]) {
      return decodeURIComponent(cookiePair[1]);
    }
  }
  return null;
}

login("John Doe");
verifySession();
Enter fullscreen mode Exit fullscreen mode

An Overview of Local Storage

Introduced with HTML5, local storage allows web applications to store data persistently in a web browser. Unlike cookies, this data is never transferred to the server and remains after the browser is closed.

The storage limit is the maximum amongst the three and can be up to 5MB depending on the browser.

Local Storage is often used for:

  • Storing larger amounts of data: Like a draft of a blog post or caching data.
  • Persisting data between sessions: For example, saving user settings or cart contents.

Local Storage Code Example - Caching Data

Imagine an app that shows the current weather for the user's location. The app might decide to store the user's location in local storage.

Then, instead of asking the user for their location every time they visit, the app can just pull the location from local storage.

// Save the location data to local storage
function saveLocation(location) {
  localStorage.setItem("location", JSON.stringify(location));
}

// Get the location data from local storage
function getLocation() {
  const location = localStorage.getItem("location");
  if (location) {
    return JSON.parse(location);
  } else {
    console.log("No location data found");
  }
}

// Assume we got the location data from user or API
const locationData = {
  city: "San Francisco",
  country: "USA",
};

saveLocation(locationData);
console.log(getLocation());
Enter fullscreen mode Exit fullscreen mode

The Flexibility of Session Storage

Session storage is also part of the Web Storage API, similar to local storage. However, unlike local storage, data stored in session storage gets cleared when the session ends (i.e., when the tab or browser is closed).

Use Cases for Session Storage

Session Storage can be used for:

  • Temporary storage: Like storing user input while filling out a multi-page form.
  • Tracking progress: To track a user's progress through a multi-stage process like a checkout flow.

Session Storage Code Example - Multi-page Forms

Let's imagine an insurance website with a multi-page form for a quote. As the user navigates through the form, their inputs can be stored in Session Storage.

If they accidentally refresh the page, their data isn't lost, and they can pick up where they left off. But once they close the tab, the data is cleared, which is often desirable for sensitive information like this.

// Save the form data to session storage
function saveFormData(page, data) {
  sessionStorage.setItem(`formPage${page}`, JSON.stringify(data));
}

// Get the form data from session storage
function getFormData(page) {
  const data = sessionStorage.getItem(`formPage${page}`);
  if (data) {
    return JSON.parse(data);
  } else {
    console.log(`No data found for page ${page}`);
  }
}

// Assume user input on different pages of the form
const page1Data = { firstName: "John", lastName: "Doe" };
const page2Data = { email: "john@example.com", phone: "1234567890" };

saveFormData(1, page1Data);
saveFormData(2, page2Data);

console.log(getFormData(1)); // Output: { firstName: "John", lastName: "Doe" }
console.log(getFormData(2)); // Output: { email: "john@example.com", phone: "1234567890" }
Enter fullscreen mode Exit fullscreen mode

Comparative Analysis: Cookies, Local Storage, and Session Storage

Now that we've understood how each storage method works with practical examples, let's compare them side-by-side. The following table highlights some key differences between the three:

Feature Cookies Local Storage Session Storage
Expiration Manually set Never (until cleared by user or server) On tab close
Storage Limit 4KB 5MB (or more) per domain 5MB (or more) per domain
Accessible From Any window Any window Same tab
Storage Location Browser and server Browser only Browser only
Sent with Requests Yes No No

Choosing the Best Storage for Your Web App

Checklist for choosing a web storage method.
Have you ever thought why some web apps just seem to 'get' you? They remember your preferences, make relevant suggestions, and provide an overall smooth and customized experience.

Well, the secret lies in their data storage methods. But how can you choose the best data store approach while creating your web application? Let's break it down:

1. Nature of the Data

First things first, think about the kind of data you're dealing with. If it's sensitive or confidential, it's best not to store it on the client-side because of security risks.

But if it's non-sensitive data that makes the user experience smoother and more enjoyable, client-side storage could be a great fit.

2. Duration of the Data

Next up, consider how long you need the data to be available. Local storage is the best option if your data needs to be kept beyond a single session or browser window.

You should use session storage if you need the data for one session or window. And for data that needs to be stored and sent with every server request? Cookies are the best client-side method for this.

3. Size of the Data

When it comes to data, size matters. Cookies may not be suitable if you are working with a large amount of data due to their size limitation (only 4KB).

But don't worry. Local and session storage are here and can store up to 5MB or more of data, based on the browser.

4. Sending the Data to the Server

If the data needs to be sent to the server with every HTTP request, cookies are the way to go since they are sent with every request by default.

But keep in mind this can increase your application's load time. If performance is your main concern, you can choose local or session storage that isn’t sent with every request, which can improve performance.

5. Browser Compatibility

While cookies are supported on virtually all browsers, local and session storage are part of the HTML5 Web Storage API and might not be supported on older browsers. Before making a decision, make sure to check your application's browser support needs.

6. Security

Storing sensitive data like passwords or credit card information? Anyone using the browser can access all these storage options, so they're not the place for sensitive info.

But cookies have some extra security features, like the Secure flag, which makes sure they are only sent over HTTPS, and the HttpOnly flag, which stops client-side scripts from accessing them.

7. Legal and Regulatory Considerations

If you're serving users in the European Union, keep in mind that the General Data Protection Regulation (GDPR) requires user consent before setting cookies. Usually, these restrictions don't apply to local or session storage.

When it comes down to it, choosing the ideal storage method is about understanding the strengths and weaknesses of cookies, local storage, and session storage and considering how they fit your specific needs.

A combination of these methods can often be used to build a robust web application. So go ahead, experiment, and find the perfect mix for your app!


Test Your Knowledge: Quick Quiz Time

Let's put your knowledge to the test with a quick quiz.

  1. What's the main difference between Local Storage and Session Storage?
    a) The amount of data they can store.
    b) The data in Local Storage is sent back to the server with each HTTP request, while data in Session Storage is not.
    c) Local Storage data persists after the browser is closed, while Session Storage data does not.
    d) Session Storage can only be accessed via JavaScript, while Local Storage can be accessed via both JavaScript and HTML.

  2. Which of the following storage types sends data back to the server with every HTTP request?
    a) Cookies
    b) Local Storage
    c) Session Storage
    d) None of the above

  3. You want to store a small amount of data that should be sent back to the server with every HTTP request and should persist indefinitely. Which storage method would you use?
    a) Cookies
    b) Local Storage
    c) Session Storage
    d) None of the above


Further Readings and Resources

If you want to delve deeper into JavaScript and web development, these books are well worth a look:

Additional resources:


Wrapping Up Web Storage

Understanding the differences between cookies, local storage, and session storage is crucial for any web developer.

Each method has unique strengths and weaknesses, and the choice largely depends on your specific application needs, the nature of the data, and essential considerations around user privacy and security.

Always remember, the beauty of web development lies in these choices - in selecting the best tools and techniques that suit your unique context.

So, I encourage you to experiment with these storage methods and master managing user data effectively. Here's to building more intuitive and efficient web applications!

Note: Some links on this page might be affiliate links. If you make a purchase through these links, I may earn a small commission at no extra cost to you. Thanks for your support!

Top comments (0)