DEV Community

Ranjani R
Ranjani R

Posted on

JS-LOCAL STORAGE

Today I am going to explain about Local Storage which is a powerful feature in web development which allows us to store user preferences UI states or temporary data without requiring a server.

*Local Storage is part of the Web Storage API, which provides a way to store key-value pairs in a web browser. Unlike cookies, it doesn’t get sent to the server with every request, and it offers more space (usually around 5MB per origin). *

The key characteristics of this are:

  • Persistent: Data stays even after the browser is closed.
  • Synchronous: Operations block the main thread
  • String-based: Only strings can be stored — we’ll need JSON.stringify() and JSON.parse() for objects or arrays.
  • Same-origin: Data is accessible only to pages from the same domain.

Here are the common Local Storage methods:

// Save data
localStorage.setItem('username', 'Ranjani');

// Retrieve data
const name = localStorage.getItem('username'); // "Ranjani"

// Remove specific item
localStorage.removeItem('username');

// Clear all local storage
localStorage.clear();

Enter fullscreen mode Exit fullscreen mode

One main thing to remember is we should not use this to store sensitive data like passwords and tokens. The main reason for this is:

  1. Any script running on the browser can have access to the data in Local Storage and hence there is risk of malicious scripts hacking the tokens.

2.Sensitive data is stored as plain text and not encrypted.

3.There is no expiry date for Local Storage unlike cookies and so these data might remain even after user logs out.

4.Tools like browser dev tools or extensions can read it without restriction.

Hence we can use this storage to save temporary user states, form inputs etc.

That's all about Local Storage....see you all in the next post.

Top comments (0)