Advertisement

a51dev | Canada

a51 Logo
a a a
Page | Scrolling

memorio

A lightweight, type-safe state management library for JavaScript applications

version install size downloads

Snyk Known Vulnerabilities Socket Badge

Node.js React Javascript TypeScript esbuild

Jest ESLint Playwright

GitBook


Table of Contents

Features

  • Reactive state management with observer pattern
  • Persistent storage with Store API
  • Session management for temporary data
  • Type-safe with full TypeScript support
  • Comprehensive test coverage
  • Easy debugging with proxy-based state
  • Cross-platform: Works in Browser, Node.js, Deno, and Edge Workers
  • Session Isolation: Each session/request gets isolated state namespace
  • Context System: Multi-tenant server-side isolation with memorio.createContext()

⚠️ Enterprise Use

For enterprise-level applications requiring advanced state management, we recommend using @biglogic/rgs instead of Memorio.

RGS provides:

  • Enhanced scalability for large applications
  • Advanced middleware support
  • Enterprise-grade security features
  • Professional support and maintenance

Memorio is ideal for small to medium projects, prototypes, and learning purposes.

Installation

npm i -D memorio

All test suites are passing

  • Basic functionality tests
  • State management tests
  • Store operations tests
  • Cache operations tests
  • Observer pattern tests
  • useObserver pattern tests

Total: 28 tests passed across 5 test suites

Quick Start

/*
 IMPORTANT!
 Add import only at first start of your SPA. Became global!.
 You don't need to import any time you need to use memorio
*/

import 'memorio';

// State Management
state.counter = 0;
state.active = false;
state.name = "john";
state.user = { name: 'John', age: 30 };
state.hours = [2,3,10,23]

// Observer Pattern
// Example: if you change the state.counter you get a console.log
observer(
  'state.counter',
    (newValue, oldValue) => {
    console.log(`Counter changed from ${oldValue} to ${newValue}`);
  }
);

// useObserver Pattern
// Example: if you change the state.counter you get a console.log
useObserver(
    (newValue, oldValue) => {
      console.log(`Counter changed from ${oldValue} to ${newValue}`);
    },
    [state.counter]
);


// Store (Persistent Storage)
store.set('preferences', { theme: 'dark' });
const preferences = store.get('preferences');

// Session Storage
session.set('token', 'user-jwt-token');
const token = session.get('token');

API Reference

State Management

State in Memorio is globally accessible and reactive:

// Setting state
state.user = { name: 'John' };

// Getting state
const userName = state.user.name;

// Listing all states
console.log(state.list);

// Removing state
state.remove('user');

// Clearing all states
state.removeAll();

Observer

⚠️ Deprecated: For React applications, use useObserver instead. The observer function is kept for non-React contexts.

useObserver

useObserver is a React hook for observing Memorio state changes with auto-discovery:


// Basic useObserver - array syntax with state path
useObserver(
  (newValue, oldValue) => {
    console.log('User updated:', newValue);
  },
  [state.user]
);

// Multiple states
useObserver(
  (newValue, oldValue) => {
    console.log('State changed:', newValue);
  },
  [state.user, state.counter, state.settings]
);

Key differences from observer:

  1. Uses array syntax [state.property] instead of string path 'state.property'
  2. Automatically cleans up on component unmount
  3. Works only inside React components
  4. Callback receives (newValue, oldValue) parameters

Store

Persistent storage for your application:

// Setting values
store.set('config', { theme: 'dark', language: 'en' });

// Getting values
const config = store.get('config');

// Removing specific value
store.remove('config');

// Getting store size
const size = store.size();

// Clearing store
store.removeAll();

Session

Temporary storage that persists during page sessions:

// Setting session data
session.set(
  'userSession', {
    id: 'user123',
    lastActive: Date.now()
  }
);

// Getting session data
const userData = session.get('userSession');

// Checking session size
const activeItems = session.size();

// Removing session data
session.remove('userSession');

// Clearing all session data
session.removeAll();

Cache

In-memory cache for temporary data storage:

// Setting cache data
cache.set('tempData', { computed: true, value: 42 });

// Getting cache data
const cached = cache.get('tempData');

// Checking cache size
const cacheSize = cache.size();

// Removing cache data
cache.remove('tempData');

// Clearing all cache data
cache.removeAll();

Note: Cache data is stored in memory and will be lost on page refresh.

idb

Permanent storage using browser database:

Create database

idb.db.create("Database")

Set data into table

idb.data.set("Database","table", { id: 1, data:{...} } )

Get data from table

[in development]

idb.data.get("Database","table", 1 )

Delete database / table

[in development]

idb.db.delete("Database") // Remove DB
idb.table.delete("Database","table") // Remove only "table"

Testing

Test suites are passing

  • Basic functionality tests
  • State management tests
  • Store operations tests
  • Cache operations tests
  • Observer pattern tests

Total: 25 tests passed across 5 test suites

Security

Security scans and reports are available at:

License

MIT License

Copyrigth © Dario Passariello


Cross-Platform Support

Memorio is designed to work across multiple JavaScript environments:

Platform Compatibility

Feature Browser Node.js Deno Edge Workers
state
observer
useObserver ⚠️ ⚠️
cache
store ✅ (localStorage) ⚠️ (memory) ⚠️ (memory) ✅ (localStorage)
session ✅ (sessionStorage) ⚠️ (memory) ⚠️ (memory) ✅ (sessionStorage)
idb ⚠️
  • ✅ Full support
  • ⚠️ Partial support (fallback to in-memory)
  • ❌ Not available

Session Isolation

Memorio provides automatic session isolation to prevent state leakage between different requests or contexts:

  • Unique Session IDs: Each import gets a unique session identifier
  • Namespaced Storage: store and session keys are prefixed with session ID
  • State Isolation: state is isolated per-instance

This ensures that in server-side environments (Node.js/Deno), different requests don't share state data.

Best Practices

  1. For Client-Side: Use all features freely - store, session, idb work with real browser storage
  2. For Server-Side: Use state and cache for in-memory data; store/session fall back to memory
  3. For Edge Workers: Same as browser; localStorage/sessionStorage available

Checking Platform

import { isBrowser, isNode, isDeno, getCapabilities } from 'memorio';

console.log('Browser:', isBrowser());      // true in browser
console.log('Node.js:', isNode());          // true in Node.js
console.log('Deno:', isDeno());             // true in Deno

const caps = getCapabilities();
console.log('Platform:', caps.platform);    // 'browser' | 'node' | 'deno' | 'edge'
console.log('Persistent:', store.isPersistent); // true if using real storage

Disclaimer
All content on this website, including text and images, has been generated using artificial intelligence technologies. While every effort is made to ensure quality and coherence, I do not assume responsibility for any inaccuracies, errors, or interpretations resulting from the use of this material.

Copyright and Intellectual property
All content on this website is copyrighted. Any copying, reproduction, distribution, or use of materials in any form is strictly forbidden without prior written permission. Violations will be subject to legal action in accordance with copyright law. We appreciate your understanding and compliance.