본문 바로가기

Try Computer Science

Vocabulary App: Why I need localStorage in JavaScript

# Before I start

Recently, I started a project for an English Vocabulary website that would be deployed as a form of web-view application on mobile. Developing a web-view application is not a traditional form of making a mobile app. Still, as I do not want to spend too much time studying specific languages like Kotiln, I picked web-view as this is "good enough".

영어 단어장 앱: 단어 수와 외운 단어의 퍼센트지를 저장, 즉 중요한 데이터가 아니기에 client side에 저장해도 됨. Access된 파일이 있다면, 단어 수를 체킹한다. 그러므로 다른 파일을 일일이 파악하지 않아도 되며, localStorage로 빠른 전달을 할 수 있다.

 


 

# Short Explanation on why I need a localStorage

Since my program is built for a hackathon, the user interface is less important than the main engine. When deploying, I would be using a free domain server that gives 5GB of free storage space. 

To solve this storage problem, localStorage offers persistent, client-side browser storage that holds data with no expiration date. The data will be stored until it is specifically deleted.

LocalStorage is a web storage API that manipulates data storage on the client side. Largely, there are two main storage APIs: localStorage and sessionStorage. localStorage stores data even when the website/tab is closed. However, the sessionStorage only holds the data when the website/tab is available.

 

# How to view localStorage

  • First, go to the developer tool, usually by F12 key or right-click to "Inspect".
  • Click the more tabs icon and find "Application".

  • Find your local storage for a website, in my case, as I am still developing, it shows my development server.
  • From there, you will find the origin (website), key, value, and data format.

 

# Demonstration of viewing

This is a bootstrap HTML website, modified from an open-source dashboard template. From here, the "Folders" section should store the user's Excel files for vocabularies.

Entry form
It shows the folder name has been successfully stored
The values are shown on the developer tool view.

 

      // storing data onto the localStorage!
      function saveTableData() {
        var tableBody = document.getElementById('fileTableBody'); // the key
        var rows = tableBody.querySelectorAll('tr'); // table function
        var tableData = [];

        rows.forEach(function (row) {
          var rowData = {
            name: row.querySelector('h6').innerText,
            words: row.querySelector('#wordsID').innerText, // #retrieves data in that ID
            completion: row.querySelector('#progressID').innerText,
          };
          tableData.push(rowData);
        });

        localStorage.setItem('fileTableData', JSON.stringify(tableData));
      }

On this code, the final line shows the key and the value it would store on the client side. localStorage can only store string data format, so everything must be passed by JSON.stringify( ). In this case, the array has been converted into string format.

 function loadTableData() {
 	// every row are recognised by []
    var tableData = JSON.parse(localStorage.getItem('fileTableData')) || [];
    tableData.forEach(function (rowData) {
      addTableRowFromData(rowData);
    });
  }

JSON.parse converts the strings into javascript object format, so it can be processed.

There are more useful methods,

 

  • setItem(): This adds a key-value pair to localStorage.
  • getItem(): Use this to fetch an item from localStorage.
  • removeItem(): This deletes a specific item from localStorage.
  • clear(): It wipes out all the data in localStorage.
  • key(): This retrieves the key of an item in localStorage based on its index.

 

 


 

# Main Advantages

The advantages are fairly obvious.

  • It is easy to implement,
  • fast to retrieve,
  • offers more storage space than cookies,
  • persistent.

The reason why I chose localStorage is to decrease the burden on server-side storage. At the same time, the data that would be stored on the client side are not private. Something that is not affected by potential disadvantages...

 

# Potential Disadvantages

1. Security Risks

  • Data Exposure: as the user can access, modify, and delete the data, it is sometimes unreliable to use the data stored on the client side. Additionally, if any private information such as passwords and credentials are stored, people who have access to the user's device and take their data.
  • Insecure Storage: it is not secure as their data is not automatically encrypted and then stored. Their raw data can easily be accessed through malware.

2. Data Integrity and Synchronisation

  • Inconsistent Data: if the user accesses data from different devices, then their data may not be synchronised across devices. This leads to inconsistency.
  • Data Loss: as you can check from the development tool, the user can clear the browser cache, clearing all the client-side data. If there is no backup from the server-side storage, your data is lost.

3. Limited Storage Capacity

  • Size Constraints: the development tool shows the maximum capacity. The total of mine is "0 B used out of 149583 MB storage quota", and it is usually 5-10MB per domain.

 

There are many more disadvantages of storing data on the client-side storage. And they are usually related to data security and integrity problems. 

In my case, the web-view application would show the domain but as the vocabulary files are stored on the user's side device, it means that it cannot be retrieved from other devices (such as their laptop).

This synchronisation problem can easily be resolved by using MySQL to centralise data storage on the server side. Whenever a change occurs, it can pass that change to the localStorage. In that case, every device can access the same data. There are many other synchronisation mechanisms other than MySQL, such as WebSockets and periodic synchronisation. 

 


 

# What can I improve

If this was not a hackathon project and had to put more effort into maintenance, then centralising the database by MySQL would have been vital to ensure its consistency and integrity. In fact, due to the characteristics of the data I store, it is not private, so does not need to be encrypted.

However, I did not choose localStorage because my data were not as important to be encrypted. So next time, I believe it is essential to look into the data's properties and consider different approaches as all user data needs to be stored securely.