@bernierllc/contentful-cache-service
v1.0.3
Published
Caches Contentful API responses with webhook-based invalidation, TTL expiration, and cache warming
Downloads
162
Readme
@bernierllc/contentful-cache-service
Caches Contentful API responses with webhook-based invalidation, TTL expiration, and cache warming. Reduces API calls and improves performance for frequently accessed content.
Features
- Response Caching: Cache entries, assets, and query results with configurable TTL
- Webhook Invalidation: Automatic cache invalidation via Contentful webhooks
- Cache Warming: Pre-fetch popular content to optimize cache hit rates
- Multi-Space Isolation: Separate cache namespaces for different Contentful spaces
- Cache Metrics: Track hits, misses, hit rate, and cache size
- NeverHub Integration: Optional integration with NeverHub for enhanced capabilities
Installation
npm install @bernierllc/contentful-cache-serviceUsage
Basic Setup
import { ContentfulCacheService } from '@bernierllc/contentful-cache-service';
const service = new ContentfulCacheService({
contentful: {
space: 'your-space-id',
accessToken: 'your-cda-token',
environment: 'master'
},
cache: {
ttl: 300000, // 5 minutes
maxSize: 1000,
strategy: 'lru'
}
});
await service.initialize();Fetching Entries (with caching)
// Get single entry (cached)
const entry = await service.getEntry('entryId');
// Get entry in specific locale
const localizedEntry = await service.getEntry('entryId', 'es-ES');
// Get multiple entries (cached)
const entries = await service.getEntries({
content_type: 'blogPost',
limit: 10,
order: '-sys.createdAt'
});Fetching Assets (with caching)
// Get single asset (cached)
const asset = await service.getAsset('assetId');
// Get multiple assets (cached)
const assets = await service.getAssets({
mimetype_group: 'image',
limit: 20
});Webhook-Based Cache Invalidation
// In your webhook endpoint
app.post('/webhooks/contentful', (req, res) => {
const topic = req.headers['x-contentful-topic'];
const payload = req.body;
service.handleWebhook(topic, payload);
res.status(200).send('OK');
});
// Supported topics:
// - ContentManagement.Entry.publish
// - ContentManagement.Entry.unpublish
// - ContentManagement.Entry.delete
// - ContentManagement.Asset.publish
// - ContentManagement.Asset.unpublish
// - ContentManagement.Asset.deleteManual Cache Invalidation
// Invalidate specific entry
await service.invalidateEntry('entryId');
// Invalidate specific asset
await service.invalidateAsset('assetId');
// Clear entire cache
await service.clearCache();Cache Warming
Pre-fetch popular content to improve cache hit rates:
// Warm cache with popular entries
const popularEntryIds = ['entry1', 'entry2', 'entry3'];
await service.warmCache(popularEntryIds);
// Warm cache for specific locale
await service.warmCache(popularEntryIds, 'en-US');Cache Metrics
// Get cache metrics
const metrics = await service.getMetrics();
console.log(`Hit rate: ${(metrics.hitRate * 100).toFixed(2)}%`);
console.log(`Cache size: ${metrics.size} entries`);
console.log(`Hits: ${metrics.hits}, Misses: ${metrics.misses}`);
console.log(`Evictions: ${metrics.evictions}, Expirations: ${metrics.expirations}`);
// Check cache size
const size = await service.getCacheSize();
// Check if entry is cached
const isCached = await service.isCached('entryId');Configuration
ContentfulCacheConfig
interface ContentfulCacheConfig {
contentful: {
space: string; // Contentful space ID (required)
accessToken: string; // Contentful CDA token (required)
environment?: string; // Environment (default: 'master')
host?: string; // API host (default: 'cdn.contentful.com')
};
cache?: {
ttl?: number; // TTL in milliseconds (default: 300000 = 5 min)
maxSize?: number; // Max entries (default: 1000)
keyPrefix?: string; // Cache key prefix (default: 'contentful:')
strategy?: 'lru' | 'lfu' | 'ttl'; // Eviction strategy (default: 'lru')
};
neverhub?: {
enabled?: boolean; // Enable NeverHub integration (default: auto-detect)
};
}Cache Key Strategy
The service generates deterministic cache keys based on:
- Space ID: Ensures multi-space isolation
- Environment: Separates staging/production content
- Resource Type: Entry, asset, entries query, assets query
- Resource ID: Specific entry or asset ID
- Locale: Optional locale for localized content
- Query Parameters: Hashed query params for consistent keys
Examples
Entry: contentful:space-id:master:entry:entryId
Entry (locale): contentful:space-id:master:entry:entryId:en-US
Asset: contentful:space-id:master:asset:assetId
Entries query: contentful:space-id:master:entries:<base64-query-hash>
Assets query: contentful:space-id:master:assets:<base64-query-hash>MECE Principles
What This Package DOES
- ✅ Cache Contentful API responses (CDA)
- ✅ Webhook-based cache invalidation
- ✅ TTL-based cache expiration
- ✅ Cache warming (pre-fetch)
- ✅ Multi-space cache isolation
- ✅ Cache hit/miss metrics
What This Package DOES NOT DO
- ❌ Database Caching: Use
@bernierllc/contentful-sync-servicefor persistent storage - ❌ Asset File Caching: CDN handles asset files (images, videos, etc.)
- ❌ Write-Through Caching: Contentful is the source of truth for writes
- ❌ Content Management API (CMA) Caching: Only caches CDA (published content)
Integration with Contentful Webhooks
Setup Webhook in Contentful
- Go to Settings > Webhooks in Contentful
- Create new webhook
- Set URL:
https://your-app.com/webhooks/contentful - Select topics:
Entry.publishEntry.unpublishEntry.deleteAsset.publishAsset.unpublishAsset.delete
- Save webhook
Webhook Handler Example
import express from 'express';
const app = express();
app.use(express.json());
app.post('/webhooks/contentful', (req, res) => {
const topic = req.headers['x-contentful-topic'] as string;
const payload = req.body;
// Validate webhook (recommended)
const signature = req.headers['x-contentful-webhook-signature'];
if (!validateSignature(signature, req.body)) {
return res.status(401).send('Unauthorized');
}
// Handle webhook
service.handleWebhook(topic, payload);
res.status(200).send('OK');
});
app.listen(3000);NeverHub Integration
The service supports optional NeverHub integration for enhanced capabilities:
const service = new ContentfulCacheService({
contentful: { /* ... */ },
neverhub: {
enabled: true // Auto-detect by default
}
});
await service.initialize();
// NeverHub registration happens automatically if availablePerformance Considerations
Cache Strategy Selection
- LRU (Least Recently Used): Best for general-purpose caching
- LFU (Least Frequently Used): Best when some content is accessed much more often
- TTL (Time To Live): Best when content freshness is critical
TTL Guidelines
- Frequently Updated Content: 1-5 minutes (60000-300000ms)
- Stable Content: 15-60 minutes (900000-3600000ms)
- Static Content: 1-24 hours (3600000-86400000ms)
Cache Size
Balance between memory usage and hit rate:
- Small sites: 100-500 entries
- Medium sites: 500-2000 entries
- Large sites: 2000-5000 entries
TypeScript
Full TypeScript support with type definitions included.
import type {
ContentfulCacheConfig,
CacheMetrics,
WebhookPayload
} from '@bernierllc/contentful-cache-service';License
Copyright (c) 2025 Bernier LLC
This file is licensed to the client under a limited-use license. The client may use and modify this code only within the scope of the project it was delivered for. Redistribution or use in other products or commercial offerings is not permitted without written consent from Bernier LLC.
Related Packages
- @bernierllc/contentful-cda-client - Contentful CDA client
- @bernierllc/contentful-sync-service - Persistent content sync
- @bernierllc/cache-manager - Generic cache manager
- @bernierllc/contentful-webhook-handler - Webhook validation
Support
For issues and questions, please open an issue on GitHub.
