Introduction
Storing data in the browser is a common task in web applications, and there are many ways to do it, but the most common way is to use the localStorage
and sessionStorage
handlers.
But the problem with these handlers is that they are not typed, and you have to deal with the JSON.stringify
and JSON.parse
methods to store and retrieve data.
That's why we created Mongez Cache, a powerful storage for web applications that is based on the localStorage
and sessionStorage
handlers but with a better and more powerful API.
Installation
Using npm
npm i @mongez/cache
Using Yarn
yarn add @mongez/cache
Using pnpm
pnpm add @mongez/cache
Features
The package has many powerful features that can easily manage your data in the browser, here are some of them:
- You can store any type of data,
strings
,integers
,objects
,arrays
. - Has one api for both
localStorage
andsessionStorage
. - Can store data for a specific time.
- Has
5
drivers for storing data. - Can Encrypt data before storing it for more security.
- It is agnostic package, you can use it with any framework you want.
- Code is cleaner and easier to understand and maintain.
Usage
As mentioned above, the package is shipped with same API for any driver, that means you can easily switch between drivers without changing your code.
Setting up cache configurations
First off, let's setup our cache configurations, which is very simple, we can just start by setting the current cache driver.
import { PlainLocalStorageDriver, setCacheConfigurations } from "@mongez/cache";
setCacheConfigurations({
driver: new PlainLocalStorageDriver(),
});
Here we are using the PlainLocalStorageDriver
, but you can use any of the other drivers that will be listed later.
Now for using the cache, we can just import the cache
object and start using it.
import cache from "@mongez/cache";
// Storing data
cache.set("name", "Hasan");
To retrieve data, we can use the get
method.
// Retrieving data
const name = cache.get("name");
We can also define a default value to be returned if the key is not found.
// Retrieving data with default value
const email = cache.get("email", "your-email-address"); // your-email-address
For deleting a key, we can use the remove
method.
// Deleting a key
cache.remove("name");
Storing objects and arrays
As mentioned earlier, the package can store any type of data, so we can store objects and arrays as well.
// Storing an object
const user = {
id
name: "Hasan",
email: "hassanzohdy@gmail.com",
};
cache.set("user", user);
Now we can retrieve the object.
// Retrieving an object
const user = cache.get("user");
It will automatically be parsed to an object.
Same applies on arrays as well.
// Storing an array
const users = [
{
id: 1,
name: "Hasan",
},
{
id: 2,
name: "Ahmed",
},
];
cache.set("users", users);
Now we can retrieve the array.
// Retrieving an array
const users = cache.get("users", []);
Storing data for a specific time
As Local Storage stores data without expiration time, we can pass third parameter to the set
method to set the expiration time for the data.
// Storing data for 1 hour
cache.set("name", "Hasan", 60 * 60);
Third argument accepts time in seconds, so in the above example, the data will be stored for 1 hour.
If you tried to retrieve the data after the expiration time, it will return null
.
Data won't be deleted automatically, it will be deleted when you try to retrieve it.
Drivers
Here are the available drivers:
- Plain Local Storage Driver
- Encrypted Local Storage Driver
- Plain Session Storage Driver
- Encrypted Session Storage Driver
- RunTime Driver
Encrypted Data
As you can see, there are encrypted
drivers, which means we need a converters for encrypting and decrypting data, you can use Mongez Encryption package to do that.
Just install it
npm i @mongez/encryption
OR
yarn add @mongez/encryption
OR
pnpm add @mongez/encryption
To make this work, make sure that you've set encryption key in Encryption Configuration.
import { encrypt, decrypt setEncryptionConfigurations } from "@mongez/encryption";
import {
EncryptedLocalStorageDriver,
setCacheConfigurations,
} from "@mongez/cache";
// make sure to set the encryption key at some point in your application
setEncryptionConfigurations({
key: "app-key",
});
setCacheConfigurations({
driver: new EncryptedLocalStorageDriver(),
// add encryption handlers
encryption: {
encrypt,
decrypt,
}
});
// The value will be stored as encrypted value something like store-name: asdfgtrhy54rewqsdaftrgyujiy67t54re3wqsd
cache.set("name", "Hasan");
console.log(cache.get("name")); // Hasan
From now, Any encrypted driver can be used safely to encrypt and decrypt data.
You can use any encryption library you want, as long as you provide the
encrypt
anddecrypt
methods.
Now let's head to our drivers.
Plain Local Storage Driver
The plain local storage implements Local Storage of the browser.
The driver name is: PlainLocalStorageDriver
import {
PlainLocalStorageDriver,
setCacheConfigurations,
} from "@mongez/cache";
setCacheConfigurations({
driver: new PlainLocalStorageDriver(),
});
cache.set("name", "Hasan");
console.log(cache.get("name")); // Hasan
Encrypted Local Storage Driver
Works exactly same as Plain Local Storage Driver except that values are encrypted when stored in the storage.
import { encrypt, decrypt setEncryptionConfigurations } from "@mongez/encryption";
import {
EncryptedLocalStorageDriver,
setCacheConfigurations,
} from "@mongez/cache";
// make sure to set the encryption key at some point in your application
setEncryptionConfigurations({
key: "app-key",
});
setCacheConfigurations({
driver: new EncryptedLocalStorageDriver(),
// add encryption handlers
encryption: {
encrypt,
decrypt,
}
});
// The value will be stored as encrypted value something like store-name: asdfgtrhy54rewqsdaftrgyujiy67t54re3wqsd
cache.set("name", "Hasan");
console.log(cache.get("name")); // Hasan
Plain Session Storage Driver
The plain session storage implements Session Storage of the browser.
The driver name is: PlainSessionStorageDriver
import {
PlainSessionStorageDriver,
setCacheConfigurations,
} from "@mongez/cache";
setCacheConfigurations({
driver: new PlainSessionStorageDriver(),
});
cache.set("name", "Hasan");
console.log(cache.get("name")); // Hasan
Encrypted Session Storage Driver
Works exactly same as Plain session Storage Driver except that values are encrypted when stored in the storage.
import { encrypt, decrypt setEncryptionConfigurations } from "@mongez/encryption";
import {
EncryptedSessionStorageDriver,
setCacheConfigurations,
} from "@mongez/cache";
// make sure to set the encryption key at some point in your application
setEncryptionConfigurations({
key: "app-key",
});
setCacheConfigurations({
driver: new EncryptedLocalStorageDriver(),
// add encryption handlers
encryption: {
encrypt,
decrypt,
}
});
// The value will be stored as encrypted value something like store-name: asdfgtrhy54rewqsdaftrgyujiy67t54re3wqsd
cache.set("name", "Hasan");
console.log(cache.get("name")); // Hasan
Runtime Driver
If you just want to cache the data in the runtime (memory), use RunTimeDriver
instead.
import cache, { RunTimeDriver, setCacheConfigurations } from "@mongez/cache";
setCacheConfigurations({
driver: new RunTimeDriver(),
});
cache.set("name", "Hasan");
console.log(cache.get("name")); // Hasan
The data will be lost when the page is refreshed or closed.
This could be useful for caching data that you want to cache it temporarily.
Conclusion
That's it, Actually this is a very useful package, I use it in any project i work on, and I hope you will find it useful too.
☕♨️ Buy me a Coffee ♨️☕
If you enjoy my articles and see it useful to you, you may buy me a coffee, it will help me to keep going and keep creating more content.
🚀 Project Repository
You can find the latest updates of this project on Github
😍 Join our community
Join our community on Discord to get help and support (Node Js 2023 Channel).
📚 Bonus Content 📚
You may have a look at these articles, it will definitely boost your knowledge and productivity.
General Topics
- Event Driven Architecture: A Practical Guide in Javascript
- Best Practices For Case Styles: Camel, Pascal, Snake, and Kebab Case In Node And Javascript
- After 6 years of practicing MongoDB, Here are my thoughts on MongoDB vs MySQL
Packages & Libraries
- Collections: Your ultimate Javascript Arrays Manager
- Supportive Is: an elegant utility to check types of values in JavaScript
- Localization: An agnostic i18n package to manage localization in your project
React Js Packages
Courses (Articles)
Top comments (0)