{"id":17881,"library":"prisma-redis-middleware","title":"Prisma Redis Caching Middleware","description":"prisma-redis-middleware is a Prisma middleware designed to cache the results of Prisma queries in Redis, significantly improving application performance by reducing database load. It also provides an in-memory LRU cache as a fallback mechanism. The current stable version is 4.8.0, with frequent patch and minor releases, indicating active development and responsiveness to community needs. Key features include fine-grained cache invalidation, support for custom cache keys, persistence with Redis, and the ability to define specific caching rules for individual Prisma models and methods (e.g., `findUnique`, `findMany`, `count`, `aggregate`, `groupBy`). It allows developers to include or exclude certain models or query methods from being cached, and define custom cache times per model, distinguishing it from simpler caching solutions. The middleware internally leverages `async-cache-dedupe` for efficient request deduplication. Developers must provide their own Redis client implementation, such as `ioredis`, which is a common and recommended choice for robust Redis connectivity.","status":"active","version":"4.8.0","language":"javascript","source_language":"en","source_url":"https://github.com/Asjas/prisma-redis-middleware","tags":["javascript","prisma","redis","prisma-caching","redis-caching","prisma-middleware","caching","typescript"],"install":[{"cmd":"npm install prisma-redis-middleware","lang":"bash","label":"npm"},{"cmd":"yarn add prisma-redis-middleware","lang":"bash","label":"yarn"},{"cmd":"pnpm add prisma-redis-middleware","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Required for Redis storage. The middleware does not bundle a Redis client.","package":"ioredis","optional":false},{"reason":"Essential peer dependency as this is a Prisma middleware.","package":"@prisma/client","optional":false},{"reason":"Used for the 'Prisma' namespace and types (e.g., 'Prisma.Middleware').","package":"prisma","optional":false}],"imports":[{"note":"Primarily designed for ESM, though CommonJS `require` is also supported for older Node.js versions. TypeScript types are included.","wrong":"const { createPrismaRedisCache } = require('prisma-redis-middleware');","symbol":"createPrismaRedisCache","correct":"import { createPrismaRedisCache } from 'prisma-redis-middleware';"},{"note":"The `Prisma` namespace, particularly for types like `Prisma.Middleware`, is typically imported from the `prisma` package itself, not `@prisma/client`.","wrong":"import { Prisma } from '@prisma/client';","symbol":"Prisma","correct":"import Prisma from 'prisma';"},{"note":"An external Redis client like `ioredis` is required and must be installed separately. The example assumes `ioredis`.","wrong":"const Redis = require('ioredis');","symbol":"Redis","correct":"import Redis from 'ioredis';"}],"quickstart":{"code":"import Prisma from \"prisma\";\nimport { PrismaClient } from \"@prisma/client\";\nimport { createPrismaRedisCache } from \"prisma-redis-middleware\";\nimport Redis from \"ioredis\";\n\nconst redis = new Redis(process.env.REDIS_URL || 'redis://localhost:6379'); // Connects to Redis, uses REDIS_URL or default\n\nconst prisma = new PrismaClient();\n\nconst cacheMiddleware: Prisma.Middleware = createPrismaRedisCache({\n  models: [\n    { model: \"User\", excludeMethods: [\"findMany\"] },\n    { model: \"Post\", cacheTime: 180, cacheKey: \"article\" },\n  ],\n  storage: { type: \"redis\", options: { client: redis, invalidation: { referencesTTL: 300 }, log: console } },\n  cacheTime: 300,\n  excludeModels: [\"Product\", \"Cart\"],\n  excludeMethods: [\"count\", \"groupBy\"],\n  onHit: (key) => {\n    console.log(\"Cache HIT for key:\", key);\n  },\n  onMiss: (key) => {\n    console.log(\"Cache MISS for key:\", key);\n  },\n  onError: (key, error) => {\n    console.error(\"Cache ERROR for key:\", key, error);\n  }\n});\n\nprisma.$use(cacheMiddleware);\n\nasync function main() {\n  // Example usage: Caching a 'findUnique' query for a 'User' model\n  const user = await prisma.user.findUnique({\n    where: { id: 1 },\n  });\n  console.log('Fetched user:', user);\n\n  // Example usage: Querying 'Post' model with custom cache time\n  const posts = await prisma.post.findMany();\n  console.log('Fetched posts:', posts);\n}\n\nmain()\n  .catch((e) => {\n    console.error(e);\n    process.exit(1);\n  })\n  .finally(async () => {\n    await prisma.$disconnect();\n    redis.disconnect();\n  });","lang":"typescript","description":"Demonstrates how to initialize and apply the Prisma Redis caching middleware with `ioredis`, configuring specific model caching rules, excluding certain methods, and logging cache hits/misses."},"warnings":[{"fix":"Upgrade your Node.js environment to a supported version (16.x or 18.x) as specified in the package's `engines` field.","message":"`prisma-redis-middleware` requires Node.js versions 16.x or 18.x. Older or unsupported Node.js versions may lead to unexpected behavior or runtime errors.","severity":"breaking","affected_versions":">=4.0.0"},{"fix":"Install a compatible Redis client like `ioredis`: `npm install ioredis @types/ioredis` and pass an initialized client instance to the middleware configuration.","message":"This middleware requires a separate Redis client library (e.g., `ioredis`) for Redis storage. It does not bundle one. Failing to install and configure an external client will lead to runtime errors when `type: 'redis'` is selected for storage.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Consult the release notes for both `prisma-redis-middleware` and `@prisma/client` to verify compatibility. Update both packages concurrently if necessary, following official documentation.","message":"Ensure compatibility between `prisma-redis-middleware` and your `@prisma/client` version. Major Prisma upgrades can introduce breaking changes to the middleware API, potentially requiring an update to this package.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Thoroughly test your cache invalidation logic in development. Understand the implications of `cacheTime` for read operations and `referencesTTL` for write-triggered invalidations to prevent stale data.","message":"Proper cache invalidation, especially with options like `referencesTTL`, requires careful configuration. Misconfigured invalidation strategies can result in stale data being served from the cache, leading to data inconsistencies.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Experiment with the order of middleware in your `$use` chain. Caching middleware is often placed early for read operations and strategically for write operations to ensure proper invalidation. Refer to Prisma's middleware documentation for best practices.","message":"The order of applying Prisma middleware via `prisma.$use()` can impact application behavior. If you use other middleware alongside `prisma-redis-middleware`, their interaction might produce unexpected results.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-23T00:00:00.000Z","next_check":"2026-07-22T00:00:00.000Z","problems":[{"fix":"Install `ioredis` and its types: `npm install ioredis @types/ioredis`.","cause":"The `ioredis` package (or another Redis client) has not been installed or is not resolvable in your project.","error":"Error: Cannot find module 'ioredis'"},{"fix":"Update `@prisma/client` to a version that supports middleware (Prisma 2.x or newer). Ensure `new PrismaClient()` is called before attempting to apply middleware.","cause":"Your `@prisma/client` version is too old and does not support Prisma middleware, or the Prisma client instance (`prisma`) was not correctly initialized before calling `$use`.","error":"TypeError: prisma.$use is not a function"},{"fix":"Verify that your Redis server is running and accessible. Check the Redis client configuration (e.g., `REDIS_URL` environment variable or explicit options) for correct host, port, and authentication credentials.","cause":"The application failed to establish a connection with the Redis server. This usually means Redis is not running, is inaccessible from your host, or the connection details (host, port, auth) are incorrect.","error":"Redis connection error: connect ECONNREFUSED <IP>:<PORT>"},{"fix":"Ensure `import Prisma from 'prisma';` is used to import the `Prisma` namespace correctly. The `createPrismaRedisCache` function returns the middleware function, which is then assigned to a variable typed as `Prisma.Middleware`.","cause":"This error often occurs when the `Prisma` namespace for types is incorrectly imported or when the options object for `createPrismaRedisCache` is mistakenly passed directly where a `Prisma.Middleware` type (a function) is expected.","error":"TypeScript error: Argument of type '{ models: { model: string; excludeMethods: string[]; }[]; ... }' is not assignable to parameter of type 'Prisma.Middleware'."}],"ecosystem":"npm","meta_description":null,"install_score":null,"install_tag":null,"quickstart_score":null,"quickstart_tag":null}