Magento 2 Local Storage: Use Data Stack Module With Javascript
Looking to improve your Magento 2 store's performance? Magento 2 local storage allows you to store data locally on the browser, reducing load times and improving the user experience.
This tutorial will cover the basics of local storage in Magento 2 and how to implement it.
Key Takeaways
- Future scope of setting up and managing local storage on the frontend.
- Ways to get storage data in JS Magento 2.
- Overview of how to use local and cookie storage using JavasSript modules.
- Steps to set and get parameters of local storage using JQuery.
- Insights into configuring local storage abstraction using custom modules.
-
When To Seek Expert Help With Magento 2 Local Storage Plugin?
-
6 Steps To Use Local & Cookie Storage using JavaScript Modules In Magento 2
-
Tips To Set And Get Parameters Of Local Storage Using JQuery
-
Common Mistakes To Avoid With Magento 2 Local Storage Abstraction
Why Use Magento Local Storage Functionality?
Magento local storage lets you store data right in the user's browser.
Unlike cookies, local storage data doesn't get sent back to the server with every single request. It is like a persistent cookie that saves key-value pairs locally in the browser. It means faster load times and improved performance across the board. It makes it perfect for storing frontend stuff that the server doesn't need to worry about.
Consider the following key things to track:
- Page load times: Use browser tools or third-party services. See how long pages take to load before and after implementing local storage.
- Server requests: Keep an eye on how many requests are hitting your server - local storage.
- User engagement: Watch metrics like bounce rate, time on site, and pages per session to see if local storage boosts engagement.
- Conversion rates: Faster pages and better performance should lead to higher conversion rates.
Consider the following to analyze and optimize local storage usage for maximum benefits:
- Figure out which pages or components will benefit the most from local storage.
- Utilize different data structures and serialization techniques to find the most efficient approach.
- Check your local storage usage to clean up any unnecessary data or optimize where you can.
- Use local storage together with other performance boosters like lazy loading or caching for maximum impact.
How To Get Storage Data In JS Magento 2?
In Magento, when you add a new cart or perform any action like adding, editing, or deleting products, the data is temporarily stored using the localStorage object. This object allows you to save key/value pairs in the browser.
define([
'jquery',
'Magento_Customer/js/customer-data'
], function ($, customerData) {
'use strict';
var getData = function (type) {
return customerData.get(type);
};
// Example usage
var cartData = getData('cart');
var wishlistData = getData('wishlist');
var compareData = getData('compare-products');
});
<script type="text/javascript">
require(['jquery', 'Magento_Customer/js/customer-data', 'jquery/ui'], function($, customerData) {
'use strict';
// Cart
customerData.get('cart').subscribe(function (cartInfo) {
console.log(cartInfo['summary_count'] > 0 ? cartInfo['summary_count'] : '0');
}, this);
// Wishlist
customerData.get('wishlist').subscribe(function (wishlist) {
console.log(wishlist['counter'] > 0 ? wishlist['counter'] : '0');
}, this);
// Compare
customerData.get('compare-products').subscribe(function (compare) {
console.log(compare['count'] > 0 ? compare['count'] : '0');
}, this);
});
</script>
You can test and retrieve this data to create your own display. You can also change handlers by calling the relevant functions in a .phtml
file.
For example, you can call out the total number of products added to the cart. You can also access the compare and wish list data in a .js
file.
When To Seek Expert Help With Magento 2 Local Storage Plugin?
Scenario | Description | Action |
---|---|---|
Complex customization | If you're trying to implement a highly customized local storage solution that goes beyond the basics, it might be time to bring in a Magento 2 expert. | Reach out to a Magento 2 specialist or agency with experience in advanced local storage implementations. They can audit your code and provide guidance on the best way forward. |
Persistent bugs | If you've exhausted all your troubleshooting skills, seek help from the pros. | Post your issue on the Magento community forums or Stack Exchange. Chances are, someone else has encountered a similar problem and can offer a solution. If not, consider hiring a Magento 2 developer to dive deep into your code and find the root cause. |
Performance issues | If your local storage implementation causes performance problems like slow page loads or excessive browser memory usage, diagnose and fix on your own. | Bring in a Magento 2 performance expert to audit your local storage code and identify any bottlenecks or inefficiencies. They can recommend optimizations and best practices to get your site running again. |
Compatibility problems | If you're facing compatibility issues with other Magento 2 extensions or third-party tools, navigate the complexities and find the best approach. | Reach out to the extension vendors or the Magento community for help. They may have encountered similar issues and offer guidance on resolving the conflict. If not, consider hiring a Magento 2 integration specialist to untangle the mess. |
Suspected core bug | If you've ruled out all other possibilities and suspect that the issue lies with the core Magento 2 local storage code, escalate to the experts. | File an issue on the official Magento 2 GitHub repository. Provide as much detail as possible about the problem. The core developers will investigate and provide guidance on a resolution. |
6 Steps To Use Local & Cookie Storage using JavaScript Modules In Magento 2
- Create a JS file in your extension or theme.
- Create
customcookie.js
in:
app\code\Vendor\Extension\view\Frontend\Web\Js\customcookie.js
- Add the following code to the file:
define([
'jquery',
'uiComponent',
'jquery/jquery-storageapi'
],
function ($, Component) {
return Component.extend({
defaults: {
cookieMessages: []
},
initialize: function () {
this._super();
this.cookieMessages = $.cookieStorage.get('mage-string');
$.cookieStorage.set('mage-string', '');
}
});
});
- To use this feature, include both
jquery
andjquery/jquery-storageapi
. - Retrieve cookie information using:
$.cookieStorage.get('mage-string');
- You can also store information in local storage using
window.localStorage
:
window.localStorage.setItem('myname', 'Vendor');
window.localStorage.getItem('myname');
window.localStorage.removeItem('myname');
window.localStorage.clear();
Tips To Set And Get Parameters Of Local Storage Using JQuery
Tip | Description | Example |
---|---|---|
Store essential data only | - Utilize local storage for frontend-specific data that does not require server-side processing. - Maintain a minimalistic approach. |
$.localStorage.set('theme', 'dark'); |
Use descriptive and unique keys | - Assign clear and distinct names to local storage keys to prevent naming collisions. - Ensure each key is unique within the application. |
$.localStorage.set('cart_count', 5); |
Serialize complex data structures | - When storing objects or arrays, employ JSON serialization. - Ensure efficient storage and retrieval processes. |
$.localStorage.set('user', JSON.stringify(userObj)); |
Perform regular cleanup | - Regularly remove unused or outdated data from local storage. - Optimize space utilization and maintain data hygiene. |
$.localStorage.remove('old_promo_code'); |
Implement graceful error handling | - Enclose local storage operations within try/catch blocks. - Handle and manage any encountered errors. |
try { $.localStorage.set('key', 'value'); } catch (e) { console.log(e); } |
Validate data integrity | - Perform data validation before storing or retrieving information. - Ensure data consistency and adherence to expected formats. |
if (typeof value === 'string') { $.localStorage.set('key', value); } |
Implement comprehensive error logging | - Establish error handling mechanisms to capture and log any issues that arise during local storage operations. - Ensure effective debugging and troubleshooting. |
$.localStorage.set('key', 'value', function(err) { if (err) { console.log(err); } }); |
Prioritize data security | - Refrain from storing sensitive information, such as financial details, in local storage. - Maintain data security and protect user privacy. |
$.localStorage.set('password', '1234'); |
Optimize performance | - Exercise judicious use of local storage to prevent browser performance degradation. - Retrieve data only when absolutely necessary to minimize resource consumption. |
var value = $.localStorage.get('key'); |
8 Steps To Create Custom Modules In Magento 2 Local Storage
- Create a
module.xml
file atapp/code/module_name/CustomStorage/etc/module.xml
:
<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
<module name="module_name__CustomStorage" setup_version="1.0.0"/>
</config>
- Create the registration file at
app/code/module_name/CustomStorage/registration.php
:
<?php
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
'module_name_CustomStorage',
__DIR__
);
- Since local storage can only be accessed from the JS environment, create a JS file
custom-local-storage.js
atapp/code/module_name/CustomStorage/view/frontend/web/js/custom-local-storage.js
with the following code:
define([
'jquery',
'mage/storage',
'jquery/jquery-storageapi'
], function ($) {
'use strict';
var cacheKey = 'custom-local-storage-field',
storage = $.initNamespaceStorage('custom-local-storage').localStorage,
saveData = function (data) {
storage.set(cacheKey, data);
},
getData = function () {
if (!storage.get(cacheKey)) {
reset();
}
return storage.get(cacheKey);
},
reset = function () {
var data = {
'hasData': false,
'yourData': null
};
saveData(data);
};
return {
reset: function () {
reset();
},
getHasData: function () {
var obj = getData();
return obj.hasData;
},
setHasData: function (hasData) {
var obj = getData();
obj.hasData = hasData;
saveData(obj);
},
getYourData: function () {
var obj = getData();
return obj.yourData;
},
setYourData: function (yourData) {
var obj = getData();
obj.yourData = yourData;
saveData(obj);
}
};
});
- Follow the steps below to declare the Local Storage in Layout:
define([
'jquery',
'mage/storage',
'jquery/jquery-storageapi'
], function ($) {
'use strict';
var cacheKey = 'custom-local-storage-field',
storage = $.initNamespaceStorage('custom-local-storage').localStorage,
saveData = function (data) {
storage.set(cacheKey, data);
},
getData = function () {
if (!storage.get(cacheKey)) {
reset();
}
return storage.get(cacheKey);
},
reset = function () {
var data = {
'hasData': false,
'yourData': null
};
saveData(data);
};
return {
reset: function () {
reset();
},
getHasData: function () {
var obj = getData();
return obj.hasData;
},
setHasData: function (hasData) {
var obj = getData();
obj.hasData = hasData;
saveData(obj);
},
getYourData: function () {
var obj = getData();
return obj.yourData;
},
setYourData: function (yourData) {
var obj = getData();
obj.yourData = yourData;
saveData(obj);
}
};
});
- Create a template file to call the JS:
<?php
?>
<script type="text/x-magento-init">
{
"*": {
"module_name_CustomStorage/js/custom-storage": {}
}
}
</script>
- Create a JS file to handle events at
app/code/module_name/CustomStorage/view/frontend/web/js/custom-storage.js
:
define([
'jquery',
'module_name_CustomStorage/js/custom-local-storage'
], function ($, customStorage) {
'use strict';
$.widget('module_name.customStorage', {
options: {
signInButtonSelector: '.authorization-link'
},
_create: function () {
this._bind();
},
_bind: function () {
var self = this;
$(this.options.signInButtonSelector).on('click', function () {
customStorage.setYourData('YOUR DATA');
customStorage.setHasData(true);
});
$(document).ready(function () {
if (customStorage.getHasData()) {
alert('Have data on custom Local storage, your data is: ' + customStorage.getYourData());
}
});
}
});
return $.module_name.customStorage;
});
- Run the following commands in your Magento root folder:
php bin/magento cache:flush
php bin/magento setup:upgrade
php bin/magento setup:static-content:deploy -f
- Click on the 'Sign in' button.
Note: Data will be saved in local storage. The system will then alert that the local storage has data.
5 Steps To Configure Magento's Custom Cookie Storage
- Follow the same initial steps as the local storage setup to create and register the module.
Note: The same module will be used to allow data to be accessed and modified in both PHP and JS environments.
- Create a PHP class for cookie storage:
<?php
namespace module\_name\CustomStorage\Cookie;
use Magento\Framework\Session\SessionManagerInterface;
use Magento\Framework\Stdlib\Cookie\CookieMetadataFactory;
use Magento\Framework\Stdlib\Cookie\PublicCookieMetadata;
use Magento\Framework\Stdlib\CookieManagerInterface;
class Data
{
const COOKIE_NAME = 'YOUR_COOKIE_NAME';
protected $_cookieManager;
protected $_cookieMetadataFactory;
protected $_sessionManager;
public function __construct(
CookieManagerInterface $cookieManager,
CookieMetadataFactory $cookieMetadataFactory,
SessionManagerInterface $sessionManager
) {
$this->cookieManager = $cookieManager;
$this->_cookieMetadataFactory = $cookieMetadataFactory;
$this->_sessionManager = $sessionManager;
}
public function get()
{
$value = $this->_cookieManager->getCookie($this->getCookieName());
if ($this->isJson($value)) {
$value = json_decode($value, true);
}
return $value;
}
public function set($value, $duration = 3600)
{
$metadata = $this->_cookieMetadataFactory
->createPublicCookieMetadata()
->setDuration($duration)
->setPath($this->_sessionManager->getCookiePath())
->setDomain($this->_sessionManager->getCookieDomain());
if (is_array($value)) {
$value = json_encode($value);
}
$this->_cookieManager->setPublicCookie(
$this->getCookieName(),
$value,
$metadata
);
}
public function delete()
{
$this->_cookieManager->deleteCookie(
$this->getCookieName(),
$this->_cookieMetadataFactory
->createCookieMetadata()
->setPath($this->_sessionManager->getCookiePath())
->setDomain($this->_sessionManager->getCookieDomain())
);
}
public function getCookieName()
{
return self::COOKIE_NAME;
}
public function isJson($string)
{
json_decode($string);
return (json_last_error() == JSON_ERROR_NONE);
}
}
- Declare the
mage/cookies
library in your JS file. Updatecustom-storage.js
as follows:
define([
'jquery',
'module_name_CustomStorage/js/custom-local-storage',
'mage/cookies'
], function ($, customStorage) {
'use strict';
$.widget('module_name.customStorage', {
options: {
signInButtonSelector: '.authorization-link',
cookieName: 'YOUR_COOKIE_NAME'
},
_create: function () {
this._bind();
},
_bind: function () {
var self = this;
$(self.options.signInButtonSelector).on('click', function () {
customStorage.setYourData('YOUR DATA');
customStorage.setHasData(true);
self._setDataCookie('YOUR DATA');
});
$(document).ready(function () {
if (customStorage.getHasData()) {
alert('Have data on custom Local storage, your data is: ' + customStorage.getYourData());
}
if (self._getDataCookie()) {
alert('Have data on Cookie, your data is: ' + self._getDataCookie());
}
});
},
_setDataCookie: function (data) {
var self = this;
if (data instanceof Array) {
data = JSON.stringify(data);
}
$.cookie(self.options.cookieName, data);
},
_getDataCookie: function () {
var self = this,
cookieData = $.cookie(self.options.cookieName);
if (!cookieData) {
return null;
}
return self._jsonDecode(cookieData);
},
_deleteDataCookie: function () {
var self = this;
$.cookie(self.options.cookieName, '', {path: '/', expires: -1});
},
_jsonDecode: function (data) {
var decodedData;
try {
decodedData = JSON.parse(data);
} catch (e) {
return data;
}
return decodedData;
}
});
return $.module_name.customStorage;
});
- Execute the following commands in your Magento root folder:
php bin/magento cache:flush
php bin/magento setup:upgrade
php bin/magento setup:static-content:deploy -f
- Click on the 'Sign in' button.
Note: Data will be saved in both local storage and cookie storage. The system will alert you that the data has been saved.
Common Mistakes To Avoid With Magento 2 Local Storage Abstraction
Mistake | Description | Solution |
---|---|---|
Storing sensitive data | Never store passwords, credit card numbers, or other sensitive information in local storage. | Use server-side storage or encryption for sensitive data. |
Overloading storage | Stuffing too much data into local storage can slow down your Magento 2 site. Keep it lean and mean. | Clear out old data, compress what you store, and use IndexedDB for larger datasets. |
Relying on local storage | Remember, users can clear their local storage at any time. Don't rely on it for critical data. | Use server-side storage for important data and sync it with local storage as needed. |
Ignoring browser differences | Different browsers handle local storage slightly differently. Test thoroughly to avoid surprises. | Provide fallbacks and handle errors gracefully across different browsers. |
Forgetting to handle unavailability | Sometimes local storage just is not available. Make sure your Magento 2 store can handle it. | Check for local storage support and provide alternative storage methods if needed. |
Exceeding storage limits | Most browsers cap local storage at around "5MB" per domain. When you're getting close, it is time to make some changes. | Clear out unnecessary data, compress what you can, and look into IndexedDB for more space. |
Inconsistent data syncing | If you're syncing data between local storage and the server, make sure it is always consistent. | Implement robust synchronization logic and error handling to avoid data mismatches. |
Future Of Local Storage In Magento 2 And Ecommerce Frontend
Trend | Description | Impact |
---|---|---|
Enhanced local storage APIs | Expect to see improved APIs for interacting with local storage in Magento 2. Examples include better error handling and more granular control over data. | Developers will have more powerful tools for leveraging local storage. They will lead to more robust and efficient frontend experiences. |
Integration with other storage tech | Look for Magento 2 to integrate with other browser storage solutions like IndexedDB. It enables the handling of larger datasets beyond the limits of local storage. | Ecommerce sites will be able to store and manage more data on the client-side. It reduces server load and improves performance. |
Better developer tooling | Magento's Developer tools include enhanced support for debugging and optimizing local storage usage. | Developers will be able to identify and fix local storage issues easily. It will lead to smoother and more reliable frontend experiences. |
Syncing with server-side storage | Magento 2 provides syncing of local storage data with server-side storage. It enables a more seamless experience across devices. | Customers will enjoy a more consistent experience as their data is synchronized between their browser and the server. |
Rise of Progressive Web Apps | As PWAs become more prevalent, expect to see even greater reliance on local storage. It enables offline functionality and boosts performance. | Magento stores will leverage PWA technology to deliver app-like experiences online and off. |
Advancements in browser security | Browser-based encryption and security measures protect sensitive data stored locally. | Leverage local storage for use cases as the security of browser-based storage improves. |
Increased use of client-side caching | Look for increased use of client-side caching and storage to reduce server load. | Magento 2 frontend performance will get a boost as more data is cached and served by the client. |
New web storage standards | Keep an eye out for potential new web storage APIs or standards. Replace or augment the current local storage technology. | Magento 2 will need to stay nimble and adapt to any new storage technologies that emerge. |
FAQs
1. How can I add a comment to my local storage script in Magento 2?
Use JavaScript comment syntax. For single-line comments, use //
. For multi-line comments, use /* */
. Remember to use use strict;
at the beginning of your script for better error checking.
2. How many files do I need to create for a basic local storage module in Magento 2?
Usually, you'll need at least 3 files: a module declaration XML, a configuration XML, and a JavaScript file for your local storage logic.
3. How can I ensure my local storage script runs on every page in Magento 2?
Add your script to the default.xml
layout file in your theme or module. Place it inside a <script>
tag within a <head>
or <body>
section.
4. How can I combine Knockout.js (ko) observables with local storage?
You can create a Knockout.js viewmodel. It observes local storage for search data, updates a count, and displays it in a div element. For documentation, you can add inline comments in your JavaScript file. Also, you can create a separate markdown doc in your module's docs
folder. This approach allows for real-time updates to the UI. It maintains a record of searches in local storage, which persists across page reloads.
Summary
Magento 2 local storage is ideal for saving cart contents, user preferences, and more directly in the browser. It helps store admins to:
- Enhance your store’s performance and user experience.
- Reduce load times and improve responsiveness.
- Store and retrieve data quickly.
- Cut down on server requests for faster page load.
- Get access to a simple API for storing and retrieving values.
Implementing local storage can enhance your site’s efficiency with managed Magento hosting.