Skip to content

api-craft/cache

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

5 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

@api-craft/cache

Unified caching middleware for Express.js supporting in-memory, Redis, and Memcached cache stores.
Part of the API Craft ecosystem.


Features

  • Cache all GET requests automatically with minimal setup
  • Support for multiple backends:
    • In-memory (default, simple & fast for single server or dev)
    • Redis (recommended for production & distributed caching)
    • Memcached (high-performance distributed caching)
  • Flexible configuration with TTL, route prefix filtering, and exclusions
  • Automatic X-Cache response headers to help debugging cache hits/misses

Installation

pnpm add @api-craft/cache

or with npm

npm install @api-craft/cache

Note: redis and memcached clients are dependencies installed automatically.

Usage

import express from 'express';
import cacheMiddleware from '@api-craft/cache';

const app = express();

app.use(cacheMiddleware({
  storeType: 'redis', // 'memory' | 'redis' | 'memcached'
  ttlSeconds: 120,    // Cache time-to-live in seconds
  prefix: '/api/',    // Only cache routes starting with '/api/'
  exclude: ['/api/auth'], // Exclude these route substrings from caching
  redisOptions: {
    url: 'redis://localhost:6379'
  },
  // memcachedServers: 'localhost:11211' // For Memcached store
}));

app.get('/api/data', (req, res) => {
  // Simulate slow operation
  setTimeout(() => {
    res.json({ message: 'Hello from cached endpoint', time: new Date() });
  }, 1000);
});

app.listen(3000, () => {
  console.log('Server listening on http://localhost:3000');
});

Configuration Options

Option Type Default Description
storeType 'memory' | 'redis' | 'memcached' 'memory' Cache backend to use.
ttlSeconds number 60 Cache expiration time in seconds.
exclude string[] [] Array of URL substrings to exclude from caching.
prefix string '' Cache only routes starting with this prefix.
redisOptions Object {} Options for Redis client (see node-redis)
memcachedServers string | string[] 'localhost:11211' Memcached server(s) address(es).

Response Headers

X-Cache: HIT — Response served from cache

X-Cache: MISS — Response generated fresh and cached

Notes

  • Redis and Memcached clients are bundled as dependencies and installed automatically.

  • Memcached does not support authentication by default.

  • In-memory caching is suitable for development or single-server environments.

  • For production, Redis or Memcached is recommended for distributed caching.

  • Only caches GET requests by default.

Contributing

Contributions, issues, and feature requests are welcome! Feel free to check issues page.

License

MIT © 2025 Thamilselven

Links

About

Unified Chaching Solution

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published