Browser storage - Localstorage,  cookies and session

Browser storage - Localstorage, cookies and session

Introduction

In web development, there are a lot of times when we have to store some user data on the browser storage to make our website more user-friendly. Data like user preferences(like dark or light theme, website language, etc.), session management, and user tokens. This makes knowing about browser storage an essential part of web development.

This blog aims to provide a detailed overview of browser storage mechanisms, specifically localStorage, cookies, and sessions. We will explore their differences, use cases, and provide code examples to help you understand and utilize them effectively in your web applications.

What is Browser Storage?

Before diving into specific storage mechanisms, it's essential to understand the concept of browser storage. Browser storage refers to the ability of web browsers to store and retrieve data on the client side, i.e., the user's device. This data can persist across browser sessions and is accessible by web applications.

  1. LocalStorage

LocalStorage is an API provided by modern web browsers that allow web applications to store key-value pairs persistently on the client side. The data stored in localStorage remains intact even after closing the browser or restarting the device.

Storing and Retrieving Data

To store data in localStorage, you can use the setItem() method, providing a key-value pair. To retrieve data, use the getItem() method, passing the key associated with the desired value.

// Storing data in localStorage
localStorage.setItem("username", "JohnDoe");

// Retrieving data from localStorage
const username = localStorage.getItem("username");
console.log(username); // Output: JohnDoe

Tips and Best Practices

  • Use localStorage for storing non-sensitive data, such as user preferences or cached data.

  • Remember that localStorage has a storage limit of around 5MB per domain. Avoid storing excessively large or unnecessary data.

  1. Cookies

Cookies are small pieces of data that websites store on a user's device. They are sent back and forth between the web server and the browser on each request, allowing the server to maintain stateful information about the user.

Storing and Retrieving Data:

Cookies can be set by the server or manipulated directly by JavaScript. To set a cookie, you need to include a Set-Cookie header in the server's response. To read a cookie value, use the document.cookie property.

// Setting a cookie
document.cookie = "username=JohnDoe; expires=Sun, 26 May 2024 00:00:00 UTC; path=/";

// Retrieving a cookie value
const cookies = document.cookie.split("; ");
const usernameCookie = cookies.find

(cookie => cookie.startsWith("username="));
const username = usernameCookie.split("=")[1];
console.log(username); // Output: JohnDoe

Tips and Best Practices

  • Use cookies when you need to maintain session-related information or pass data between the client and the server.

  • Be cautious with storing sensitive information in cookies. Consider encryption or session tokens to enhance security.

  1. Sessions

Sessions provide a way to store user-specific data on the server-side while associating it with a unique session identifier stored on the client-side (usually as a cookie). Session data is typically stored in server memory, a database, or an external data store.

Storing and Retrieving Data

To store and retrieve session data, the server generates a session ID and associates it with the user's data on the server-side. The session ID is sent back to the client and stored as a cookie. On subsequent requests, the client sends the session ID, allowing the server to identify and retrieve the associated session data.

// Server-side pseudocode (using Express.js)
const sessions = {};

app.post("/login", (req, res) => {
  // Perform authentication and user retrieval
  const user = { id: 1, username: "JohnDoe" };

  // Generate a session ID
  const sessionId = generateSessionId();

  // Store user data in session
  sessions[sessionId] = user;

  // Set the session ID as a cookie
  res.cookie("sessionId", sessionId);

  // Redirect to the home page
  res.redirect("/");
});

// Retrieving session data
app.get("/", (req, res) => {
  const sessionId = req.cookies.sessionId;
  const user = sessions[sessionId];

  // Use the user data as needed
});

4.4. Tips and Best Practices:

  • Sessions are suitable for storing sensitive user data securely on the server-side.

  • Implement proper session management, including session expiration and secure session handling practices.

Which storage you should choose?

  1. What is your use-case?

  • localStorage: Ideal for storing non-sensitive user preferences or caching data on the client-side.

  • Cookies: Useful for maintaining session-related information, user identification, and tracking.

  • Sessions: Recommended for storing sensitive user data securely on the server-side.

  1. Security and Privacy

  • localStorage: Data stored in localStorage is accessible by any script running in the same origin. Be cautious with sensitive information.

  • Cookies: Can be marked as secure and have additional security options. However, cookies are vulnerable to attacks like cross-site scripting (XSS) and cross-site request forgery (CSRF).

  • Sessions: Storing data on the server-side provides better security compared to client-side storage mechanisms. However, proper session management is crucial to prevent session hijacking and other vulnerabilities.

Conclusion

In this article, we explored localStorage, cookies, and sessions, discussing their differences, use cases, and best practices with code examples.

Thanks for being till the end. Checkout my other blogs below👇

yashnirmal.hashnode.dev

Also, if you guys want me to write a blog on any other javascript topic, write in the comments. Also, share your views on how this article was.

Did you find this article valuable?

Support Yash Nirmal by becoming a sponsor. Any amount is appreciated!