Signup/Sign In
PUBLISHED ON: MAY 27, 2024

How to use LocalStorage in NextJS?

If you want to store some data on the client side i.e. the browser, then you can use the localStorage. Local Storage is available in the browser, where you can store data in key-value pairs. Local Storage can be used to store information on the browser so that it can be utilized across browser sessions and page refreshes. Yes, once you store some data in the local storage it will stay there until and unless you remove it or the user cleans it up.

Local Storage can be used to store user information, user preference, track not-logged in users, store the URLs visited by the user to map the user journey into some actionable event, etc.

In this article, we will learn all about localStorage, the different methods available in localStorage Web API, and different use cases where you can use localStorage. So let's get started.

What is LocalStorage?

Local Storage is a type of web storage available in the browser. You can store data in the form of key-value pairs in the Local storage. The localstorage can be accessed in the Application tab of the Developer's tool in the chrome browser.

localstorage in chrome

Under the Local storage option, you will find the name of the current website, when you click on it, you will get the list of key-value pairs stored in the localstorage for that domain name.

When to use LocalStorage?

There are many use cases for localstorage. Mainly, localstorage is used to store any data that you may want to use across sessions, or page refreshes. Here are a few popular use cases:

  1. Tracking user activity, like pages (URLs) viewed, especially for users who are not logged into your application.

  2. Storing user preferences like country, currency, light/dark mode, etc.

  3. Data that we may not want to store into the database, can be stored in the local storage.

  4. Local storage can be used to store the form data, in case of refresh, to save the data input by the user, so that the user doesn't have to fill the form again.

  5. Useful data can be cached into Local storage.

  6. Authentication information can be stored into local storage.

The LocalStorage Object

The window interface provides the localStorage object, and this object comes with multiple methods to engage with the local storage.

setItem(key, value):

This method is used to store key-value pair in the localstorage. The key should be a string, and the value should also be a string, or it can be a JavaScript object, which is automatically converted into a string, or you can use the JSON.stringify method for any custom object.

For example,

localStorage.setItem("name", "Abhishek");

getItem(key):

This method is used to access the value stored against a key in the local storage.

For example,

localStorage.getItem("name");

removeItem(key):

This method can be used to remove the key-value pair from the local storage.

For example,

localStorage.removeItem("name");

clear():

This method is used to clear out the entire local storage and remove all the key-value pairs stored in it.

For example,

localStorage.clear();

length:

It is a property of localStorage object, which is used to get the total count of the key-value pairs stored in the local storage.

For example,

localStorage.length;

Using Local Storage in NextJS

In NextJS, you can directly use the localStorage object to interact with the Local Storage of the browser.

All the methods listed above can be used in the NextJS application. Although it is recommended that if you have to access anything that is outside of ReactJS, then you should do that inside of useEffect, so ideally, you should access local storage inside useEffect only.

For example,

useEffect(() => {
    if (typeof window !== 'undefined' && window.localStorage) {
        localStorage.setItem('username', "Abhishek");
    }

}, []);

This is just an example. Ideally, when the application loads, you should first check if data is available in the local storage, if yes, then you use that data in your application.

For example, if you store the Cart information in local storage, so that the user who is not logged in, can access the cart even after page refresh. In that case, you would want to read the local storage to check for "cart" key in it, and if found, you should load the information in the cart, otherwise, just show the cart as empty.

One this that you should always do is, to check if the window object is available.

if (typeof window !== 'undefined' && window.localStorage) {
    localStorage.setItem('username', "Abhishek");
}

Just like setItem, you can use other methods of the localStorage object. When you get any data from the local storage, you should store that data in some state variable so that you can trigger a re-render of the component and then use the data from the local storage on the user interface.



About the author:
I like writing content about C/C++, DBMS, Java, Docker, general How-tos, Linux, PHP, Java, Go lang, Cloud, and Web development. I have 10 years of diverse experience in software development. Founder @ Studytonight