Cookies vs. Local Storage vs. Session Storage: What’s the difference?

In this article, we’re going to explore three types of storage methods: cookies, local storage, and session storage. We’ll take a look at some examples and explore their differences.

Cookies, Local Storage, and Session Storage

Cookies are small pieces of data stored on the client-side computer, usually in plain text. A cookie is typically sent to the server with each request so that the server can identify the user and provide personalized content. Cookies are typically used for authentication and storing user preferences.

Local storage is similar to cookies, but it stores data in a structured way, usually as key-value pairs. The data is stored on the client-side computer, and it remains there until it is manually cleared. Local storage is generally used for storing data that needs to persist even after the browser has been closed.

Session storage is similar to local storage, but it stores data only for the current session and is deleted once the browser is closed. Session storage is used for storing temporary data that is only needed while the user is on the website.

Think about a login system on a website. When a user logs in for the first time, the server can create a cookie to remember their login information. The cookie might contain information such as the user’s username and a unique session ID.

Here’s what the cookie might look like:

Name: login_cookie
Value: {username: "example_user", session_id: "abc123"}
Expires: 30 days from now

When the user visits the website again, their web browser sends the cookie back to the server with every request. The server can then use the information in the cookie to identify the user and personalize their experience on the site (e.g., showing them their account page instead of the login page).

It’s important to note that cookies can also be used for other purposes besides login information, such as tracking user behavior on the site or displaying personalized ads. However, cookies are often subject to privacy concerns, as they can be used to collect and share user data without their explicit consent.

Example of local storage

As an example, suppose you have a website that allows users to create and save notes. When a user saves a note, you can store it in local storage so that it persists even if the user closes their browser.

Here’s what the local storage might look like:

// To save a note:
const note = "This is my note";
localStorage.setItem("note1", note);

// To retrieve the note:
const retrievedNote = localStorage.getItem("note1");
console.log(retrievedNote); // Outputs: "This is my note"

In this example, the setItem method is used to save a note with the key “note1” and the value “This is my note” in local storage. The getItem method is used to retrieve the note with the key “note1” from local storage and log it to the console.

Note that local storage is limited to storing strings, so if you need to store more complex data types such as objects or arrays, you’ll need to use JSON.stringify to convert them to strings before storing them in local storage, and JSON.parse to convert them back to their original form when retrieving them from local storage.

Example of session storage

Suppose you have a website that allows users to create and save items to a shopping cart. When a user adds an item to their cart, you can store it in session storage so that it persists only for the duration of the user’s session on the website.

Here’s what the session storage might look like:

// To save an item to the cart:
const item = { name: "T-shirt", price: 20 };
sessionStorage.setItem("cartItem1", JSON.stringify(item));

// To retrieve the item from the cart:
const retrievedItem = JSON.parse(sessionStorage.getItem("cartItem1"));
console.log(retrievedItem); // Outputs: { name: "T-shirt", price: 20 }

In this example, the setItem method is used to save an item with the key “cartItem1” and the value { name: "T-shirt", price: 20 } in session storage. The getItem method is used to retrieve the item with the key “cartItem1” from session storage, and the JSON.parse method is used to convert the item from a string back into an object.

Note that session storage works similarly to local storage, but the main difference is that session storage is cleared when the user closes their browser, while local storage persists even after the browser is closed.

Key differences between the three

  • Cookies can be set to expire after a certain amount of time or be deleted manually, while local and session storage can be cleared only by the user or through a script.
  • Cookies are sent back to the server with every request, while local and session storage are not automatically sent to the server.
  • Cookies have a size limit of 4KB, while local and session storage have larger size limits (usually around 5-10MB).
  • Local and session storage are only accessible within the same domain, while cookies can be accessed by other domains that the user visits.

Overall, cookies, local storage, and session storage are all web storage technologies used in client-side web development, but they have different features and uses. In general, cookies are best suited for storing small amounts of data that need to be sent to the server with every request, while local and session storage are better for storing larger amounts of data that don’t need to be sent to the server.

Conclusion

In conclusion, cookies, local storage, and session storage are all ways to store data on the client side in web applications, but they have some key differences.

Cookies are small text files that are stored on the user’s device by the web server, and they are best suited for storing small amounts of data that need to be sent to the server with every request.

Local storage and session storage are both part of the Web Storage API and allow web applications to store data locally in the user’s browser. Local storage is persistent storage, meaning that the data is stored even after the browser is closed and reopened, while session storage is temporary storage, meaning that the data is only available for the duration of the user’s session on the website.

Local and session storage are better suited for storing larger amounts of data that don’t need to be sent to the server. Overall, the choice between cookies, local storage, and session storage depends on the specific needs of the web application and the data that needs to be stored.

Learn the basics of programming with Udacity’s Nanodegree program. You will learn HTML, CSS, Python, and JavaScript. Get extensive practice with hands-on exercises and projects that demonstrate your grasp of coding fundamentals, and build confidence in your ability to think and problem-solve like a programmer.

Get started programming with Udacity.

comments powered by Disqus

Related Posts

JavaScript’s Secret Weapon: Supercharge Your Web Apps with Web Workers

During an interview, I was asked how we could make JavaScript multi-threaded. I was stumped, and admitted I didn’t know… JavaScript is a single-threaded language.

Read more

Creating a NodeJS Budgeting Tool

In this article, we’re going to show you how to read and write to a .txt file using NodeJS by creating a small budgeting CLI (Command Line Interface).

Read more

Becoming a Hacker: Must Read Security & Cyber Crime Books

In our most recent publication, we delved into security and cyber crime blogs you should be reading to stay up-to-date with modern threats, bugs, and crimes.

Read more