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 🙏

© 2026 – Pkg Stats / Ryan Hefner

request-cache-middleware

v1.0.0

Published

Plug-and-play caching middleware for Express and Fastify - Reduce DB load and improve API performance

Readme

request-cache-middleware

lightning Plug-and-play caching middleware for Express and Fastify that automatically caches API responses to reduce database load and improve performance.

Features

  • Zero Configuration - Works out of the box with sensible defaults
  • 🎯 Framework Agnostic - Works with Express and Fastify
  • 💾 Multiple Stores - Memory or Redis cache
  • 🔐 User-Specific Caching - Automatically includes user context in cache keys
  • 📦 Compression Support - Optional gzip compression for cached data
  • 🎛️ Flexible Configuration - Custom keys, exclusions, debug mode
  • 📝 TypeScript Support - Full type definitions included
  • 🚀 Performance - Reduces DB queries and improves response times

Installation

npm install request-cache-middleware

For Redis support (optional):

# Using ioredis
npm install ioredis

# Or using redis v4
npm install redis

Quick Start

Express

const express = require('express');
const cache = require('request-cache-middleware');

const app = express();

// Cache for 60 seconds (memory store)
app.get('/api/users', cache(60), async (req, res) => {
  const users = await User.findAll();
  res.json({ success: true, data: users });
});

Fastify

const fastify = require('fastify');
const cache = require('request-cache-middleware');

fastify.get('/api/users', {
  preHandler: cache(60),
}, async (request, reply) => {
  const users = await User.findAll();
  return { success: true, data: users };
});

User-Specific Caching

The middleware automatically handles user-specific responses by including user context in the cache key:

// Different users get different cached responses automatically
app.get('/api/profile', cache(300), async (req, res) => {
  // req.user.id is automatically included in cache key
  const profile = await Profile.findByUserId(req.user.id);
  res.json({ success: true, data: profile });
});

The cache key includes:

  • HTTP method
  • Full URL
  • User ID (from req.user.id, req.session.userId, or req.headers['x-user-id'])
  • Authorization token (first 8 chars for differentiation)

Cache Stores

1. Memory Store (Default)

Simple in-memory cache, perfect for single-server deployments:

app.get('/api/data', cache(60), handler);

2. Redis Store

Use Redis for distributed caching across multiple servers:

const Redis = require('ioredis');
const redisClient = new Redis();

app.get('/api/data', cache(300, {
  store: 'redis',
  redisClient: redisClient,
}), handler);

Supports both ioredis and redis v4 clients.

Options

interface CacheOptions {
  store?: 'memory' | 'redis';             // Cache store type
  redisClient?: RedisClient;              // Redis client (for Redis store)
  key?: (req) => string;                  // Custom cache key generator
  exclude?: (string | RegExp)[];          // Paths to exclude from caching
  debug?: boolean;                        // Enable debug logging
  compress?: boolean;                     // Compress cached data with gzip
}

Advanced Examples

Custom Cache Key

app.get('/api/user/:id', cache(600, {
  key: (req) => `user:${req.params.id}:${req.user?.id}`,
}), handler);

Exclude Paths

app.get('/api/*', cache(60, {
  exclude: ['/api/auth', '/api/admin', /^\/api\/sensitive/],
}), handler);

Compression

app.get('/api/large-data', cache(300, {
  compress: true,  // Compress large responses before caching
}), handler);

Debug Mode

app.get('/api/data', cache(60, {
  debug: true,  // Logs cache hits/misses to console
}), handler);

Response Headers

The middleware adds an X-Cache header to responses:

  • X-Cache: HIT - Response was served from cache
  • X-Cache: MISS - Response was generated fresh (and cached)

Important Notes

  1. Only GET requests are cached - POST, PUT, PATCH, DELETE are automatically skipped
  2. User-specific caching - User context is automatically included in cache keys
  3. Status codes - Only 2xx responses are cached
  4. JSON responses - Works with res.json() and res.send()

TypeScript Support

import cache from 'request-cache-middleware';

app.get('/api/users', cache(60, {
  store: 'redis',
  debug: true,
}), handler);

API Reference

cache(duration, options?)

Creates a cache middleware.

  • duration: Cache duration in seconds
  • options: Configuration options (see above)

Returns middleware function compatible with Express and Fastify.

Examples

See the examples/ directory for complete examples:

  • express-example.js - Express basic usage
  • fastify-example.js - Fastify basic usage
  • redis-example.js - Redis store configuration
  • user-specific-example.js - User-specific caching patterns

Performance Tips

  1. Use Redis for multi-server deployments
  2. Enable compression for large responses
  3. Set appropriate TTLs based on data freshness requirements
  4. Exclude dynamic endpoints that shouldn't be cached
  5. Monitor cache hit rates using debug mode

License

MIT

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.