What is LocalStorage and How to Use LocalStorage with Next.js?
Creating seamless web experiences requires careful management of client-side state. One method for doing this is to use the browser feature local storage, which allows you to store data on the user's device. What is Local Storage and How does it work? Local Storage is a feature that enables websites to store key-value pairs in a web browser with no expiry date. This means the stored data remains accessible even after the user closes the browser or shuts down the system. If you’re storing data, it means you may need to retrieve it later. Now, we’ll explore exactly how local storage works. Here’s a quick review of how it works, setItem(): Adds key and value to local storage. getItem(): Retrieves/gets items from local storage. removeItem(): Removes an item from local storage. clear(): Clears all data from local storage. key(): Passes a number to retrieve the key of a local storage. Advantages and Disadvantages of Local Storage Advantages: Persistent Storage: Information stays as it is even when the browser is closed or reloaded. Straight-forward API: User-friendly with functions such as setItem, getItem, and removeItem. No Server Reliance: Functions completely on the client side, lessening server strain. Extensively Supported: Compatible with nearly all contemporary browsers. Disadvantages: Size Limitation: It can store only 5-10 MB of data depending on the browser. Not Safe: Information is kept in plain text, exposing it to XSS attacks. Synchronous API: Operations stops the progress, potentially affecting performance. No Expiration: The data stays forever unless someone decides to delete it, which can lead to it piling up over time. Challenges of Using LocalStorage in Next.js It can store only 5-10 MB of data depending on the browser. The data should be specific to the origin [domain] of the respective page. For any complex data, you should do some JSON because the stored data is just string form. Always use local storage on the client side; on the server side, you get the error “Local storage is not defined”. Remember to serialize and deserialize your objects when storing and retrieving them. Do not store any sensitive data, as local storage is accessible by any scripts on the same domain. Common issues with local storage “Local storage is not defined” error occurs when you are trying to access the local storage during any serverside rendering. if (typeof window !== 'undefined') { // LocalStorage code here } You can use lazy load your client component, make sure it's a client component, or disable pre-rendering on the server so it's only rendered on the client. If your data is not persisting make sure that you have not accidentally cleared or you are in private browsing mode or an incognito tab. As we discussed earlier, the local storage stores everything in a string format, so make sure you are parsing your data in the correct form, const someValue = JSON.parse(localStorage.getItem('lorem') || '{}') If you got quota exceeded error then please consider cleaning up your old or unnecessary data or take a look into using indexedDB for larger storage needs. Solution: You can wrap your localstorage code into try-catch block, try { localStorage.setItem('myKey', 'myValue') } catch (e) { if (e instanceof DOMException && e.name === 'QuotaExceededError') { console.log("Storage full, let's make some room!") // Handle the error (see strategies below) }} Remove old data, const removeOldestItem = () => { if (localStorage.length > 0) { const oldestKey = Object.keys(localStorage)[0] localStorage.removeItem(oldestKey) }} How to Use LocalStorage in Next.js In Next.js, you can use local storage in the same way as you would in a standard React application. However, because Next.js supports Server-Side Rendering (SSR), be aware that localStorage is only accessible on the client-side (within the browser). On the server-side, there is no localStorage, so you should make sure you're accessing it only in the client environment. Below are the steps to properly use local storage in next.js, Step 1 : Check for client side rendering Please first ensure that you're accessing localStorage only on the client side because it’s not available during SSR. You can do this by checking whether the code is being run in the browser (i.e., after the component mounts). Step 2: Set up local storage access in a component Create a new component or page where you want to use local storage. Use the useEffect hook to ensure client-side rendering. Inside the useEffect, you can safely access localStorage because this will run only in the browser after the initial render. Below is an example of how to use local storage in a Next.js app, import { useEffect, useState } from 'react'; const LocalStorageExample = () => { // State to store the retrieved value from localStorage const [name, setName] = useS
Creating seamless web experiences requires careful management of client-side state. One method for doing this is to use the browser feature local storage, which allows you to store data on the user's device.
What is Local Storage and How does it work?
Local Storage is a feature that enables websites to store key-value pairs in a web browser with no expiry date. This means the stored data remains accessible even after the user closes the browser or shuts down the system.
If you’re storing data, it means you may need to retrieve it later. Now, we’ll explore exactly how local storage works. Here’s a quick review of how it works,
- setItem(): Adds key and value to local storage.
- getItem(): Retrieves/gets items from local storage.
- removeItem(): Removes an item from local storage.
- clear(): Clears all data from local storage.
- key(): Passes a number to retrieve the key of a local storage.
Advantages and Disadvantages of Local Storage
Advantages:
- Persistent Storage: Information stays as it is even when the browser is closed or reloaded.
- Straight-forward API: User-friendly with functions such as setItem, getItem, and removeItem.
- No Server Reliance: Functions completely on the client side, lessening server strain.
- Extensively Supported: Compatible with nearly all contemporary browsers.
Disadvantages:
- Size Limitation: It can store only 5-10 MB of data depending on the browser.
- Not Safe: Information is kept in plain text, exposing it to XSS attacks.
- Synchronous API: Operations stops the progress, potentially affecting performance.
- No Expiration: The data stays forever unless someone decides to delete it, which can lead to it piling up over time.
Challenges of Using LocalStorage in Next.js
- It can store only 5-10 MB of data depending on the browser.
- The data should be specific to the origin [domain] of the respective page.
- For any complex data, you should do some JSON because the stored data is just string form.
- Always use local storage on the client side; on the server side, you get the error “Local storage is not defined”.
- Remember to serialize and deserialize your objects when storing and retrieving them.
- Do not store any sensitive data, as local storage is accessible by any scripts on the same domain.
Common issues with local storage
“Local storage is not defined” error occurs when you are trying to access the local storage during any serverside rendering.
if (typeof window !== 'undefined') {
// LocalStorage code here
}
You can use lazy load your client component, make sure it's a client component, or disable pre-rendering on the server so it's only rendered on the client.
If your data is not persisting make sure that you have not accidentally cleared or you are in private browsing mode or an incognito tab.
As we discussed earlier, the local storage stores everything in a string format, so make sure you are parsing your data in the correct form,
const someValue = JSON.parse(localStorage.getItem('lorem') || '{}')
If you got quota exceeded error then please consider cleaning up your old or unnecessary data or take a look into using indexedDB for larger storage needs.
Solution:
You can wrap your localstorage code into try-catch block,
try {
localStorage.setItem('myKey', 'myValue')
} catch (e) {
if (e instanceof DOMException && e.name === 'QuotaExceededError') {
console.log("Storage full, let's make some room!")
// Handle the error (see strategies below)
}}
Remove old data,
const removeOldestItem = () => {
if (localStorage.length > 0) {
const oldestKey = Object.keys(localStorage)[0]
localStorage.removeItem(oldestKey)
}}
How to Use LocalStorage in Next.js
In Next.js, you can use local storage in the same way as you would in a standard React application. However, because Next.js supports Server-Side Rendering (SSR), be aware that localStorage is only accessible on the client-side (within the browser). On the server-side, there is no localStorage, so you should make sure you're accessing it only in the client environment.
Below are the steps to properly use local storage in next.js,
Step 1 : Check for client side rendering
Please first ensure that you're accessing localStorage only on the client side because it’s not available during SSR. You can do this by checking whether the code is being run in the browser (i.e., after the component mounts).
Step 2: Set up local storage access in a component
Create a new component or page where you want to use local storage.
Use the useEffect hook to ensure client-side rendering. Inside the useEffect, you can safely access localStorage because this will run only in the browser after the initial render.
Below is an example of how to use local storage in a Next.js app,
import { useEffect, useState } from 'react';
const LocalStorageExample = () => {
// State to store the retrieved value from localStorage
const [name, setName] = useState('');
// Read from localStorage after the component mounts
useEffect(() => {
if (typeof window !== 'undefined') {
const storedName = localStorage.getItem('name');
if (storedName) {
setName(storedName);
}
}
}, []);
// Save to localStorage when the name changes
const handleNameChange = (event) => {
const newName = event.target.value;
setName(newName);
if (typeof window !== 'undefined') {
localStorage.setItem('name', newName);
}
};
return (
Welcome, {name || 'User Name'}
);
};
export default LocalStorageExample;
Below is the explanation of the above code,
- useEffect Hook: This hook is used to ensure that the code inside it is run only on the client-side, because local-storage is not available on the server during SSR. It only runs after the initial render, so it is safe to access local-storage here.
- localStorage.getItem(): This retrieves the value from the browser's local storage. If the value exists, it's used to set the state.
- localStorage.setItem(): This saves the updated value back to localStorage whenever the input changes.
- Conditional Check (typeof window !== 'undefined'): This ensures that the code is only executed in the client environment (browser) and not during server-side rendering.
Suggestions for Utilizing LocalStorage in Next.js
- Avoid Saving Sensitive Data: Avoid saving sensitive information such as tokens or passwords in local storage due to security risks.
- Manage Fallbacks Smoothly: Always verify the availability of local storage to address situations such as private browsing.
- Maintain Minimal Data: Retain solely lightweight, non-sensitive information to prevent performance problems.
- Remove Unused Data: Frequently clean up local storage to avoid unwanted data.
Conclusion
LocalStorage is the storage of data directly in a user's web browser within Next.js applications. It keeps things like user preferences or settings, even after a user leaves the page or refreshes it.
When implementing it in Next.js, it's crucial to understand the distinction between server-side rendering (SSR) and client-side rendering (CSR). LocalStorage operates solely on the client side, which means it cannot be accessed during server-side rendering, so it should be used cautiously to avoid errors.
While LocalStorage is not suitable for storing sensitive data (such as passwords), it is excellent for saving preferences like a user's theme selection, language choice, or other non-sensitive settings. It's user-friendly and preserves data even after a page refresh.
What's Your Reaction?