Advertisement

a51dev | Canada

a51 Logo
a a a
Page | Scrolling

Platform & Context Isolation - Memorio

ℹ️ New in v2.7.0: Context isolation system for multi-tenant server-side applications

Memorio automatically detects the runtime environment and adapts its behavior accordingly. This document explains platform compatibility, session isolation, and the new context system.


Quick Reference: Client vs Server

Which Module to Use?

Scenario Recommended Module Persistence
UI State (React/components) state Memory
Temporary computed data cache Memory
User preferences store Browser localStorage
Auth tokens session Browser sessionStorage
Large offline data idb IndexedDB
Server request isolation memorio.createContext() Memory

Module Availability

Module Browser Node.js Deno Edge
state
cache
store ✅ (localStorage) ⚠️ (memory) ⚠️ (memory)
session ✅ (sessionStorage) ⚠️ (memory) ⚠️ (memory)
idb ⚠️
useObserver ⚠️ ⚠️
devtools

Platform Detection

Memorio automatically detects the environment on import:

import 'memorio';

// Check current platform
console.log(memorio.platform);   // 'browser' | 'node' | 'deno' | 'edge'
console.log(memorio.isPersistent); // true if using real storage

Available Platform APIs

// Check platform
memorio.isBrowser()    // true in browser
memorio.isNode()      // true in Node.js
memorio.isDeno()      // true in Deno
memorio.isEdge()      // true in Edge Workers

// Get capabilities
const caps = memorio.getCapabilities();
// caps.platform, caps.hasSessionStorage, caps.hasLocalStorage, etc.

Platform Compatibility Matrix

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

Client vs Server Usage

🖥️ Client-Side (Browser)

All features work with real browser storage:

// Store - persistent localStorage
store.set('preferences', { theme: 'dark' });
store.isPersistent; // true

// Session - temporary sessionStorage
session.set('token', 'jwt-token');
session.isPersistent; // true (survives refresh)

// IDB - large data storage
idb.db.create('myApp');

🖥️ Server-Side (Node.js/Deno)

Use state and cache for in-memory data. Store/session fall back to memory:

// State - in-memory global state
state.user = { name: 'Server User' };

// Cache - in-memory temporary cache
cache.set('apiResponse', data);

// Store - in-memory fallback (not persistent)
store.set('temp', data);
store.isPersistent; // false - data lost on restart

// Session - in-memory fallback
session.set('requestData', data);
session.isPersistent; // false - data lost on restart

Session Isolation

Each instance/session gets unique storage keys to prevent conflicts:

// Keys are prefixed with session ID
// store: "memorio_store_[sessionId]_key"
// session: "memorio_session_[sessionId]_key"

This ensures:

  • Multiple browser tabs don't share session data
  • Server-side requests are isolated

Context Isolation (Server-Side Multi-Tenancy)

⚠️ Server-Side Only: This feature is designed for multi-tenant server environments (Node.js, Deno). Not needed for client-side applications.

For server-side applications handling multiple tenants (e.g., different users/requests), use contexts to isolate data:

Creating a Context

// Create isolated context for a user/session
const ctx = memorio.createContext('user-123');

// Use context's isolated storage
ctx.state.user = { name: 'Isolated User' };
ctx.store.set('settings', { theme: 'dark' });
ctx.session.set('token', 'abc123');
ctx.cache.set('temp', data);

// Context is completely isolated from global state
console.log(state.user); // undefined - global state is separate

Managing Contexts

// List all contexts
const contexts = memorio.listContexts();
console.log(contexts); // ['user-123', 'user-456', ...]

// Delete a context (cleanup)
memorio.deleteContext('user-123');

// Shorthand for createContext
const ctx2 = memorio.isolate('tenant-A');

Context Use Cases

1. Per-Request Isolation (Express/Fastify)

// Middleware to isolate each request
app.use((req, res, next) => {
  const ctx = memorio.createContext(`req-${req.id}`);
  req.memorioContext = ctx;
  next();
});

// In route handler
app.get('/user', (req, res) => {
  const ctx = req.memorioContext;
  ctx.state.user = getUserData();
  // Each request has isolated state
});

2. Multi-Tenant SaaS

// Each tenant gets isolated storage
function handleTenant(tenantId) {
  const ctx = memorio.createContext(tenantId);

  ctx.state.config = getTenantConfig(tenantId);
  ctx.store.set('data', tenantData);

  return ctx;
}

Best Practices

Client-Side (Browser)

  1. Use store for persistent data (preferences, user settings)
  2. Use session for temporary data (auth tokens)
  3. Use cache for computed values
  4. Use state for reactive UI state

Server-Side (Node.js/Deno)

  1. Use memorio.createContext() for each request/tenant
  2. Don't use global state/store/session across requests
  3. Use cache for request-scoped caching
  4. Check store.isPersistent / session.isPersistent if persistence matters

Edge Workers

Same as browser - localStorage and sessionStorage are available.


API Reference

Global Functions

Function Returns Description
memorio.isBrowser() boolean Check if running in browser
memorio.isNode() boolean Check if running in Node.js
memorio.isDeno() boolean Check if running in Deno
memorio.isEdge() boolean Check if running in Edge
memorio.getCapabilities() object Get platform capabilities

Context Management

Function Returns Description
memorio.createContext(name?) Context Create isolated context
memorio.listContexts() string[] List all context IDs
memorio.deleteContext(id) boolean Delete a context
memorio.isolate(name?) Context Alias for createContext

Properties

Property Type Description
memorio.version string Memorio version
memorio.platform string Current platform
memorio._sessionId string Unique session identifier

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.