Mongez Cache, a powerful storage manager for web applications
Tags: localstorage, sessionstorage, cache, typescript
Published: 2023-02-23 10:17:06

---
title: Mongez Cache, a powerful storage manager for web applications
published: true
description: 
tags: localStorage, sessionStorage, cache, typescript
# cover_image: https://direct_url_to_image.jpg
# Use a ratio of 100:42 for best results.
---

## 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` and `sessionStorage`.
- 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.

```ts
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.

```ts
import cache from "@mongez/cache";

// Storing data
cache.set("name", "Hasan");
```

To retrieve data, we can use the `get` method.

```ts
// Retrieving data
const name = cache.get("name");
```

We can also define a default value to be returned if the key is not found.

```ts
// 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.

```ts
// 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.

```ts
// Storing an object
const user = {
  id
  name: "Hasan",
  email: "hassanzohdy@gmail.com",
};

cache.set("user", user);
```

Now we can retrieve the object.

```ts
// Retrieving an object
const user = cache.get("user");
```

It will automatically be parsed to an object.

Same applies on arrays as well.

```ts
// Storing an array
const users = [
  {
    id: 1,
    name: "Hasan",
  },
  {
    id: 2,
    name: "Ahmed",
  },
];

cache.set("users", users);
```

Now we can retrieve the array.

```ts
// Retrieving an array
const users = cache.get("users", []);
```

### Storing data for a specific time

As [Local Storage](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage) stores data without expiration time, we can pass third parameter to the `set` method to set the expiration time for the data.

```ts
// 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](#plain-local-storage-driver)
- [Encrypted Local Storage Driver](#encrypted-local-storage-driver)
- [Plain Session Storage Driver](#plain-session-storage-driver)
- [Encrypted Session Storage Driver](#encrypted-session-storage-driver)
- [RunTime 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](https://github.com/hassanzohdy/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](https://github.com/hassanzohdy/mongez-encryption#encryption-configurations).

```ts
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` and `decrypt` methods.

Now let's head to our drivers.

### Plain Local Storage Driver

The plain local storage implements [Local Storage](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage) of the browser.

The driver name is: `PlainLocalStorageDriver`

```ts
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](#plain-local-storage-driver) except that values are encrypted when stored in the storage.

```ts
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](https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage) of the browser.

The driver name is: `PlainSessionStorageDriver`

```ts
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](#plain-session-storage-driver) except that values are encrypted when stored in the storage.

```ts
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.

```ts
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](https://www.paypal.com/paypalme/hassanzohdy), 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](https://github.com/hassanzohdy/nodejs-2023)

## 😍 Join our community

Join our community on [Discord](https://discord.gg/pb2vmdfhGf) 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](https://dev.to/hassanzohdy/event-driven-architecture-the-best-paradigm-that-i-love-to-work-with-in-javascript-and-node-js-1gnk)
- [Best Practices For Case Styles: Camel, Pascal, Snake, and Kebab Case In Node And Javascript](https://dev.to/hassanzohdy/best-practices-for-case-styles-camel-pascal-snake-and-kebab-case-in-node-and-javascript-55oi)
- [After 6 years of practicing MongoDB, Here are my thoughts on MongoDB vs MySQL
](https://dev.to/hassanzohdy/after-6-years-of-practicing-mongodb-here-are-my-thoughts-on-mongodb-vs-mysql-574b)

Packages & Libraries

- [Collections: Your ultimate Javascript Arrays Manager](https://dev.to/hassanzohdy/collections-your-ultimate-javascript-array-handler-3o15)
- [Supportive Is: an elegant utility to check types of values in JavaScript](https://dev.to/hassanzohdy/supportive-is-an-elegant-utility-to-check-types-of-values-in-javascript-1b3e)
- [Localization: An agnostic i18n package to manage localization in your project](https://dev.to/hassanzohdy/mongez-localization-the-simplest-way-to-translate-your-website-regardless-your-favorite-framework-4gi3)

 React Js Packages

- [useFetcher: easiest way to fetch data in React Js](https://dev.to/hassanzohdy/usefetcher-the-easiest-way-to-fetch-data-in-react-45o9)

Courses (Articles)

- [OOP In JS And TS From The Very Beginning](https://dev.to/hassanzohdy/jsts-oop-course-1-introduction-2ld)
- [ES6++: The Ultimate Guide to ES6 and Beyond](https://dev.to/hassanzohdy/es6-1-introduction-h3e)
- [React Js: Let"s Create File Manager With React Js and Node Js](https://dev.to/hassanzohdy/lets-create-a-file-manager-from-scratch-with-react-and-typescript-chapter-i-a-good-way-to-expand-your-experience-5g4k)