📚 StoneJS Developer Guide
Complete reference for building modern web applications with the StoneJS Framework
⚡ Caching
Cache System
StoneJS includes a powerful built-in in-memory cache for improving application performance. The cache supports component-level caching and data caching patterns.
Cache Methods
| Method | Description | Returns |
|---|---|---|
set(key, value, ttl) |
Store value in cache with TTL in seconds | void |
get(key) |
Retrieve cached value by key | value or undefined |
delete(key) |
Remove specific key from cache | void |
has(key) |
Check if key exists in cache | boolean |
clear() |
Remove all cached items | void |
remember(key, ttl, fn) |
Cache result of async function (most useful) | Promise<value> |
cacheSelf(options) |
Cache entire component output (Mason-style) | Promise<boolean> |
getStats() |
Get cache statistics | {hits, misses, hitRate, size} |
Basic Cache Operations
Remember Pattern (Recommended)
The remember() method is the most elegant caching pattern. It automatically handles cache misses by executing your function and storing the result.
✅ How it works: If the key exists in cache, return cached value. Otherwise, execute the function, cache the result, and return it.
Example: Database Query Caching
Example: External API Caching
Example: User-Specific Caching
💡 Pro Tip: Use prefixes in cache keys to organize related data: user-profile-123, api-weather-nyc, db-all-users
Component Caching (cacheSelf)
Cache entire page/component output with Mason-style cacheSelf() method:
💡 Learn More: See the complete cache documentation for cacheSelf() options, busy lock patterns, and advanced examples.
Cache Invalidation
When data changes, invalidate related cached entries to ensure freshness:
⚠️ Cache Invalidation Strategy: Delete all cache keys affected by data changes. Missing an invalidation can show stale data to users.
Cache Statistics
Monitor cache performance with built-in statistics:
| Statistic | Description |
|---|---|
hits |
Number of successful cache lookups |
misses |
Number of cache misses (had to fetch data) |
hitRate |
Percentage of requests served from cache (0-1) |
size |
Current number of cached items |
Best Practices
- Use
remember()pattern for expensive operations - Set appropriate TTL based on data freshness needs
- Use descriptive cache keys (prefix with context)
- Invalidate cache when underlying data changes
- Monitor cache hit rates in production
- Don't cache user-specific data with shared keys
Need more help?