Onjsdev

Share


Javascript Browser Storage


By onjsdev

Apr 15th, 2024

When developing a web application with Javascript, we may need to not only store data in databases, but also store some information in users’ browsers. At this point, we have different options of storage in browser enviroment. In this article we will discuss each of them by considering their pros and cons, as well as, difference between them.

Javascript Browser Storage


Before we continue with implementing them with code, we should understand some key points about browser storage. Understanding these points would be helpful in deciding on the best storage options for saving data while developing an application.

What is Browser Storage?

Browser storage refers to the ability of a web browser to locally store data on the user’s device, which can be accessed by JavaScript code running on web pages and used in different parts of the application. The primary mechanism for browser storage is provided by the Web Storage API. In addition to the Web Storage API, there are other ways to store data on the user’s device, such as cookies and IndexedDB

Why We Need Them?

Modern web applications consist of client and backend sides that communicate with each other using the HTTP protocol, which is stateless and does not maintain any information about previous requests between the client and the server. This situation requires saving information on the client-side to persist some processes such as authentication and payment processes. As result of this, browser storage come into the play.

Local Storage

Local Storage is a type of web storage that allows you to store key-value pairs in the browser and is persistent, meaning it remains even after the browser is closed or the computer is restarted. The data is only removed when the user manually clears their browser data or you remove the data programmatically.

Usage

The Local Storage API provides two methods for setting and getting data – setItem(key, value) and getItem(key).

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

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

In addition to these methods, we also have localStorage.clear() method to delete all items in the storage

localStorage.clear()

What To Store

Local storage can be used to store data that persists across multiple sessions of a web application, such as user preferences, settings, etc. However, it’s important to note that sensitive data, such as passwords and credit card details, should not be stored in Local Storage or should be encrypted, as it is accessible to any JavaScript code running on the page and can also be vulnerable to cross-site scripting (XSS) attacks.

Limitations

Although Local Storage is a powerful tool for storing data in browsers, it has some limitations that you should be aware of:

  • Local Storage has a maximum capacity of 5-10 MB per domain, depending on the browser.
  • Local Storage can only store strings. To store objects or arrays, you need to serialize them using JSON.stringify() and deserialize them using JSON.parse().

Session Storage

Session Storage is similar to Local Storage, but it has a shorter lifespan. Session Storage only lasts as long as the current session – once the user closes their browser or navigates away from your website, the data stored in Session Storage is removed.

Usage

Session Storage works in the same way as Local Storage, but with a different API. You can set and get data using sessionStorage.setItem(key, value) and sessionStorage.getItem(key).

// Storing data in session storage
sessionStorage.setItem("username", "JohnDoe");

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

Also, session storage has clear method for removing all data in the session storage.

sessionStorage.clear()

What To Store

Session storage is used to store temporary data that is needed for the duration of a user’s session on a website. This can include data such as the user’s shopping cart contents, form data that is being filled out, or other session-specific information.

Limitations

  • Just like Local Storage, Session Storage has a limit on the amount of data that can be stored. This limit varies between browsers, but typically ranges from 5-10 MB.
  • Once the user closes the browser window or navigates away from the website, the data in Session Storage is deleted automatically. This means that it may not be the best option for storing data that needs to persist across multiple sessions or visits to a website.

Cookies

Cookies are another way to store data on a user’s web browser, but they have some differences when compared to Web Storage API in JavaScript. Because:

  • By setting the HttpOnly flag on cookies, they become accessible only to the server and not to any JavaScript code that might be running in the user’s browser.
  • Unlike to localStorage or sessionStorage, the information stored in cookies is sent to the server with each HTTP request automatically.
  • Similar to localStorage, cookies persist in memory, meaning that even if the web page is refreshed or the browser window or tab is closed and reopened, the stored data will not be erased.

Usage

To set a cookie in JavaScript, we use the document.cookie property. The syntax for setting a cookie is as follows:

document.cookie = "name=value; expires=date; path=path; domain=domain; secure";

Properties

Cookies have several properties that can be set to customize their behavior:

  • Expires: The expires property is used to set an expiration date for the cookie. When a cookie is created, it can be given an expiration date that determines when it will be deleted from the user’s browser. After the expiration date has passed, the cookie is no longer valid and is automatically deleted by the browser.
  • Path: The path property is used to specify the path on the website where the cookie will be used. By default, cookies are available to all pages on the website. If the path is set, the cookie will only be available to pages that are within that path.
  • Domain: The domain property is used to specify the domain where the cookie will be used. By default, cookies are available to the domain that created them. If the domain is set, the cookie will be available to all subdomains of that domain.
  • Secure: The secure property is a boolean value that indicates whether the cookie can only be accessed over a secure connection (HTTPS). If the “secure” property is set, the cookie will only be sent to the server over a secure connection
  • HttpOnly: The HttpOnly property is a boolean value that indicates whether the cookie can be accessed by JavaScript. If the “HttpOnly” property is set, the cookie can only be accessed by the server and cannot be read or modified by JavaScript.

Create Cookies By Server

As we said, cookies can be created by a server for saving some informations user’s browser and sent it to client. We will provide an example of a node&expressjs application to show you how send cookies to the users’ browsers.

Setting cookies in an Express application is straightforward. You can use the res.cookie() method provided by the Express framework to set a cookie in the response.

const express = require("express");
const app = express();

app.get("/", (req, res) => {
  res.cookie("username", "JohnDoe", { 
    expires: new Date(Date.now() + 900000), // expires in 15 minutes
    httpOnly: true // prevents client-side JavaScript from accessing the cookie
  });
  res.send("Cookie set!");
});

app.listen(3000, () => {
  console.log("Server listening on port 3000");
});

Read Cookie In Server

To read a cookie in Express, you can use the req.cookies object. Here’s an example:

app.get("/", (req, res) => {
  const username = req.cookies.username;
  res.send(`Hello ${username}!`);
});

It’s important to note that you need to install and configure the cookie-parser middleware in your Express application to be able to use req.cookies. Here’s how to do it:

const express = require("express");
const app = express();
const cookieParser = require("cookie-parser");

app.use(cookieParser());

// Your routes here

app.listen(3000, () => {
  console.log("Server listening on port 3000");
});

Remove A Cookie In Server

To remove a cookie in an Expressjs server, you can use the res.clearCookie() method. This method takes the name of the cookie to be removed as its argument.

app.get('/logout', function(req, res) {
  res.clearCookie('myCookie');
});

Limitations

  • Cookies are limited to storing up to 4KB of data, which means that they are not suitable for storing large amounts of data.

Security Concerns On Browser Storage

These storage options are very useful. However, storing sensitive information on the client-side can also increase security risks. Here are some common security concerns on browser storage and ways to reduce these risks.

Cross-site Scripting (XSS) attacks

XSS attacks occur when an attacker injects malicious code into a web page, which can then execute in the user’s browser.This can happen when we include vulnerable HTML tags into our site because attackers can pass a script code to element along with their source.

To mitigate XSS attacks, it is important to validate and escape user input before processing and we must add trusted sources to our site.

Cross-site Request Forgery (CSRF) attacks

Cookies are susceptible to cross-site request forgery (CSRF) attacks because they are automatically sent to the server with every HTTP request. In a CSRF attack, the attacker can trick the user into performing an unintended HTTP request to a website where the user is already authenticated.

To mitigate CSRF attacks, it is important to use some techniques. These techniques involve generating a unique token on the server-side and including it in both a hidden form field and a cookie. When the form is submitted, the server verifies that the tokens match, ensuring that the request is legitimate.

Conclusion

Overall, the Javascript Browser Storage API and cookies are powerful ways to store data in a user’s web browser. By considering security concerns, data can be stored using localStorage, sessionStorage and cookies. This allows us to persist information for communication with the server or to take action when a page is refreshed.