npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@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-service

Usage

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.delete

Manual 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-service for 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

  1. Go to Settings > Webhooks in Contentful
  2. Create new webhook
  3. Set URL: https://your-app.com/webhooks/contentful
  4. Select topics:
    • Entry.publish
    • Entry.unpublish
    • Entry.delete
    • Asset.publish
    • Asset.unpublish
    • Asset.delete
  5. 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 available

Performance 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

Support

For issues and questions, please open an issue on GitHub.