Using LocalStorage with Next.js: A Beginner’s Guide

Anisha Dahal
wesionaryTEAM
Published in
5 min readMar 28, 2023

--

Local storage is a type of web storage that allows web applications to store data locally within the user’s browser. This web API allows developers to store key-value pairs in the browser’s memory. It is a simple yet powerful tool that can be used to persist data across browser sessions and page refreshes. This can be useful for saving user preferences, creating offline experiences, or storing data for later use.

In this article, we will take a look at some use cases of local storage and know how to use local storage in a Next.js web application.

Where can we use local storage?

There are various use scenarios where we can use local storage in our applications. Let’s understand a few use cases for local storage.

  • Storing user preferences: In an e-commerce application, we can use local storage to save the user’s preferred currency and automatically display prices in that currency every time they visit the website.
  • Saving temporary data: In a task management application, we can use local storage to save the tasks that the user has added to their “to-do” list but hasn’t yet completed. This way, if they close the browser or navigate away from the page, their progress is not lost.
  • Saving form data: In a job application form, we can use local storage to save the user’s inputted data, so they can come back to the form later without losing their progress.
  • Caching data: In a weather application, we can use local storage to save the current weather conditions, so the user can access them even when they’re offline.
  • Storing authentication information: In a social media application, we can use local storage to save the user’s authentication token, so they don’t have to log in every time they open the application. (Storing sensitive data in local storage without encrypting them is not recommended at all. To see how we can handle sensitive data encryption you can see this article.)

Local Storage Object

To use local storage, we can use the localStorage object provided by the browser. This object has several methods for working with local storage.

Methods

The following are the methods available in localStorage:

  • setItem(key, value): This method is used to add a key-value pair to local storage. The key is a string and the value can be any string or JavaScript object, which will be automatically converted to a string before being saved.
localStorage.setItem('username', 'Anisha');
localStorage.setItem('userId', '12345');
  • getItem(key): This method is used to retrieve the value of a key from local storage. It takes a key as a parameter and returns the corresponding value as a string.
localStorage.getItem('username');
localStorage.getItem('userId');
  • removeItem(key): This method is used to remove a key-value pair from local storage. It takes a key as a parameter and removes the corresponding key-value pair from local storage.
 localStorage.removeItem('username');
localStorage.removeItem('userId');
  • clear(): This method is used to remove all key-value pairs from local storage.
localStorage.clear();
  • key(index): This method is used to retrieve the key of a key-value pair at a specific index in the local storage. It takes an index as a parameter and returns the corresponding key as a string.
const key = localStorage.key(0); //getting key of 0th index
  • length: This is a read-only property that returns the number of key-value pairs currently stored in local storage.
const numOfItemsInLocalStorage = localStorage.length()

Example of Local Storage Implementation

Here’s a complete example of how you might use all the localStorage methods in a Next.js application:

First, we create states for each of the items that we are going to store in localStorage and for the keys and the number of items in local storage.

const [username, setUsername] = useState<string | null>(null);
const [userId, setUserId] = useState<string | null>(null);
const [userData, setUserData] = useState<{email: string, age: number} | null>(null);
const [keys, setKeys] = useState<string[]>([]);
const [length, setLength] = useState<number>(0);

Now we use the useEffect hook to check whether the browser's localStorage API is available, and to retrieve the values of the key-value pairs stored in localStorage when the component is first rendered.

useEffect(() => {
if (typeof window !== 'undefined' && window.localStorage) {
let username = localStorage.getItem('username');
let userId = localStorage.getItem('userId');
let userData = JSON.parse(localStorage.getItem('userData'));
let keys: string[] = [];
for (let i = 0; i < localStorage.length; i++) {
keys.push(localStorage.key(i)!);
}
setUsername(username);
setUserId(userId);
setUserData(userData);
setKeys(keys);
setLength(localStorage.length);
}
}, []);

We have three event handlers handleSave, handleRemove, handleClear to save, remove, and clear the data from local storage respectively.

In the handleSave function, we use the setItem method to save some key-value pairs to local storage. We then fetch those values using getItem method and use the setUsername, setUserId, setUserData setKeys and setLength to update the state with the new values.

function handleSave() {
if (typeof window !== "undefined" && window.localStorage) {
localStorage.setItem("username", "Anisha");
localStorage.setItem("userId", "12345");
localStorage.setItem("userData", JSON.stringify({ email: "anisha@example.com", age: 25 }));

let username = localStorage.getItem("username");
let userId = localStorage.getItem("userId");
let userData = JSON.parse(localStorage.getItem("userData")!);
let keys: string[] = [];
for (let i = 0; i < localStorage.length; i++) {
keys.push(localStorage.key(i)!);
}

setUsername(username);
setUserId(userId);
setUserData(userData);
setKeys(keys);
setLength(localStorage.length);
}
}

You can view the values in local storage by opening the browser’s developer tools and navigating to the Application tab. Under LocalStorage, you will be able to see all of the key-value pairs that are currently stored.

In the handleRemove function, we use the removeItem method to remove the 'username' key-value pair from local storage and use the setUsername to update the state with the new value.

function handleRemove() {
if (typeof window !== 'undefined' && window.localStorage) {
localStorage.removeItem('username');
setUsername(null);
}
}

In the handleClear function, we use the clear method to remove all key-value pairs from local storage and use the setUsername, setUserId, setUserData , setKeys , setLength to update the state with the new values.

function handleClear() {
if (typeof window !== 'undefined' && window.localStorage) {
localStorage.clear();
setUsername(null);
setUserId(null);
setUserData(null);
}
}

Finally, in the render method, we display the values of the key-value pairs stored in localStorage and provide buttons to interact with the local storage.

<div>
<button onClick={handleSave}>Save to localStorage</button>
<button onClick={handleRemove}>Remove from localStorage</button>
<button onClick={handleClear}>Clear localStorage</button>
<p>Username: {username}</p>
<p>UserId: {userId}</p>
<p>UserData: {JSON.stringify(userData)}</p>
<p>List of Keys: {keys.join(", ")}</p>
<p>Total Items in Local Storage: {length}</p>
</div>

For a more detailed look at the code, feel free to check out my GitHub repository.

Security concerns while using Local Storage

One of the downsides of using local storage is that the data stored in it is in the form of plain text, which means that it can be accessed easily by a malicious script. This means that if an attacker is able to gain access to the user’s device, they could potentially access the data stored in local storage.

To know how we can encrypt sensitive data in a Next.js application, here is Part II of this article. Securing Sensitive Data in LocalStorage in a Next.js App

--

--