In this tutorial, we will show you 7 easy steps to use Magento 2 Local Storage and 4 simple steps to utilize Magento 2 Cookie Storage. Let’s figure it out now!
A. Custom Magento 2 Local Storage
Step 1: Create a module.xml file: app/code/Tigren/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="Tigren_CustomStorage" setup_version="1.0.0"/> </config>
Step 2: Create Registration file of the Module: app/code/Tigren/CustomStorage/registration.php
<?php \Magento\Framework\Component\ComponentRegistrar::register( \Magento\Framework\Component\ComponentRegistrar::MODULE, 'Tigren_CustomStorage', __DIR__ );
Because the Local Storage can only set and get from JS environment, so we will need a JS file to create function.
Step 3: Create the file custom-local-storage.js: app/code/Tigren/CustomStorage/view/frontend/web/js/custom-local-storage.js Add the following code to initialize a local storage:
define([ 'jquery', 'mage/storage', 'jquery/jquery-storageapi' ], function ($) { 'use strict'; var cacheKey = 'custom-local-storage-field', // define field cache key of storage // define local storage namespace storage = $.initNamespaceStorage('custom-local-storage').localStorage, /** * @param {Object} data */ saveData = function (data) { storage.set(cacheKey, data); }, /** * @return {*} */ getData = function () { if (!storage.get(cacheKey)) { reset(); } return storage.get(cacheKey); }, reset = function () { var data = { 'hasData': false, // all data have been defined below 'yourData': null }; saveData(data); }; return { // use reset function to reset all data saved in storage reset : function () { reset(); }, // define getter, setter of data to save in local storage 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); } }; });
Step 4: Declare the local storage in layout default
define([ 'jquery', 'mage/storage', 'jquery/jquery-storageapi' ], function ($) { 'use strict'; var cacheKey = 'custom-local-storage-field', // define field cache key of storage // define local storage namespace storage = $.initNamespaceStorage('custom-local-storage').localStorage, /** * @param {Object} data */ saveData = function (data) { storage.set(cacheKey, data); }, /** * @return {*} */ getData = function () { if (!storage.get(cacheKey)) { reset(); } return storage.get(cacheKey); }, reset = function () { var data = { 'hasData': false, // all data have been defined below 'yourData': null }; saveData(data); }; return { // use reset function to reset all data saved in storage reset : function () { reset(); }, // define getter, setter of data to save in local storage 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); } }; });
Step 5: Create a template file for calling JS
<?php /** * @copyright Copyright (c) 2019 www.tigren.com */ ?> <script type="text/x-magento-init"> { "*": { "Tigren_CustomStorage/js/custom-storage": {} } } </script>
Step 6: Create JS file to handler event click, trigger save data, example When clicking on the Sign in button, the system will save data to the custom local storage app/code/Tigren/CustomStorage/view/frontend/web/js/custom-storage.js
define([ 'jquery', 'Tigren_CustomStorage/js/custom-local-storage' ], function ($, customStorage) { 'use strict'; $.widget('tigren.customStorage', { options: { signInButtonSelector: '.authorization-link' // class of Sign in button }, _create: function () { this._bind(); }, _bind: function () { var self = this; // Add on click event handler for sign in button $(this.options.signInButtonSelector).on('click', function () { // save data to custom local storage customStorage.setYourData('YOUR DATA'); customStorage.setHasData(true); // You can use below function to reset all data saved // customStorage.reset(); }); // Get data $(document).ready(function () { // check if Local storage has data if (customStorage.getHasData()) { // I will use alert to check alert('Have data on custom Local storage, your data is: ' + customStorage.getYourData()); } }); } }); return $.tigren.customStorage; });
Step 7: Run following commands on your Magento root folder php bin/magento cache:flush php bin/magento setup:upgrade php bin/magento setup:static-content:deploy -f Now, your custom local storage is initialized:

When clicking on the Sign in button, data will be saved on this storage, then the system will alert that the Local storage has data.

B. Custom Magento 2 Cookie Storage
We will use the same module to create a custom Cookie storage, so we will pass through step 1 and step 2. With the Cookie storage, different from the Local storage, you can get and set data from both PHP and JS environments.
Step 1 & 2: Similar to the first two steps of Local storage
Step 3: With PHP: create PHP class
<?php /** * @copyright Copyright (c) 2019 www.tigren.com */ namespace Tigren\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 { // You can define your own cookie name const COOKIE_NAME = 'YOUR_COOKIE_NAME'; /** * @var \Magento\Framework\Stdlib\CookieManagerInterface */ protected $_cookieManager; /** * @var \Magento\Framework\Stdlib\Cookie\CookieMetadataFactory */ protected $_cookieMetadataFactory; /** * @var \Magento\Framework\Session\SessionManagerInterface */ protected $_sessionManager; /** * Data constructor. * @param CookieManagerInterface $cookieManager * @param CookieMetadataFactory $cookieMetadataFactory * @param SessionManagerInterface $sessionManager */ public function __construct( CookieManagerInterface $cookieManager, CookieMetadataFactory $cookieMetadataFactory, SessionManagerInterface $sessionManager ) { $this->_cookieManager = $cookieManager; $this->_cookieMetadataFactory = $cookieMetadataFactory; $this->_sessionManager = $sessionManager; } /** * @return null|string */ public function get() { $value = $this��'_cookieManager�'getCookie($this��'getCookieName()); // Decode json data if data is json type if ($this->isJson($value)) { $value = json_decode($value, true); } return $value; } /** * @param $value * @param int $duration * @throws \Magento\Framework\Exception\InputException * @throws \Magento\Framework\Stdlib\Cookie\CookieSizeLimitReachedException * @throws \Magento\Framework\Stdlib\Cookie\FailureToSendException */ public function set($value, $duration = 3600) { $metadata = $this->_cookieMetadataFactory ->createPublicCookieMetadata() ->setDuration($duration) ->setPath($this->_sessionManager->getCookiePath()) �'setDomain($this��'_sessionManager�'getCookieDomain()); // Encode data to json type if data is array if (is_array($value)) { $value = json_encode($value); } $this->_cookieManager->setPublicCookie( $this->getCookieName(), $value, $metadata ); } /** * @throws \Magento\Framework\Exception\InputException * @throws \Magento\Framework\Stdlib\Cookie\FailureToSendException */ public function delete() { $this->_cookieManager->deleteCookie( $this->getCookieName(), $this->_cookieMetadataFactory ->createCookieMetadata() ->setPath($this->_sessionManager->getCookiePath()) ->setDomain($this->_sessionManager->getCookieDomain()) ); } /** * Used to get cookies name (key) by which data can be set or get * * @return string */ public function getCookieName() { return self::API_COOKIE_NAME; } /** * Check string is valid JSON * * @source http://stackoverflow.com/questions/6041741/fastest-way-to-check-if-a-string-is-json-in-php * @param $string * @return bool */ public function isJson($string) { json_decode($string); return (json_last_error() == JSON_ERROR_NONE); } }
Step 3′: With JS: Declare ‘mage/cookies’ lib in JS file. We will declare it in custom-storage.js file on the above example and handler event on click Sign in button will save data to Cookie. Now the file will be:
define([ 'jquery', 'Tigren_CustomStorage/js/custom-local-storage', 'mage/cookies' ], function ($, customStorage) { 'use strict'; $.widget('tigren.customStorage', { options: { signInButtonSelector: '.authorization-link', // class of Sign in button cookieName: 'YOUR_COOKIE_NAME' // declare your cookie name }, _create: function () { this._bind(); }, _bind: function () { var self = this; // Add on click event handler for sign in button $(self.options.signInButtonSelector).on('click', function () { // save data to custom local storage customStorage.setYourData('YOUR DATA'); customStorage.setHasData(true); // save data to Cookie storage self._setDataCookie('YOUR DATA'); }); // Get data $(document).ready(function () { // check if Local storage has data if (customStorage.getHasData()) { // I will use alert to check alert('Have data on custom Local storage, your data is: ' + customStorage.getYourData()); } // check if Cookie has data if (self._getDataCookie()) { // alert Cookie data alert('Have data on Cookie, your data is: ' + self._getDataCookie()); } }); }, // function to set cookie _setDataCookie: function (data) { var self = this; // Encode data to JSON if data is array if (data instanceof Array) { data = JSON.stringify(data); } // Set cookie data $.cookie(self.options.cookieName, data); }, // function to get cookie _getDataCookie: function () { var self = this, cookieData = $.cookie(self.options.cookieName); if (!cookieData) { return null; } return self._jsonDecode(cookieData); }, // function to delete cookie _deleteDataCookie: function () { var self = this; $.cookie(self.options.cookieName, '', {path: '/', expires: -1}); }, // function to check if data is JSON or not _jsonDecode: function (data) { var decodedData; try { decodedData = JSON.parse(data); } catch (e) { return data; } return decodedData; } }); return $.tigren.customStorage; });
Step 4: Run following commands on your Magento root folder php bin/magento cache:flush php bin/magento setup:upgrade php bin/magento setup:static-content:deploy -f Now, when you click on the Sign in button, Cookie will be saved at the same time.

Read More:
How To Display Order Information In Checkout Success Page In Magento 2?
How To Add Contact Form To CMS Page In Magento 2?
How To Add Extension Attribute To Order In Magento 2?
How To Set Up Multi Magento 2 Cash On Delivery Options?
Quick Solutions To Your Magento 2 Migration Issues
How To Display Order Information In Checkout Success Page In Magento 2?