{"id":17118,"library":"prisma-nested-middleware","title":"Prisma Nested Middleware","description":"Prisma Nested Middleware is a utility library designed to extend Prisma's native middleware capabilities, specifically for handling nested write operations and relations within queries. While standard Prisma middleware (version 4.0.0 is the latest as of January 2024, with a consistent release cadence) is effective for top-level queries, it lacks the ability to intercept and modify operations on nested relations. This library addresses that limitation by providing a `createNestedMiddleware` function that wraps your middleware, allowing it to be called for every nested relation in a Prisma query. It exposes an enhanced `NestedParams` object, which includes critical context like `scope`, `modifier`, `logicalOperators`, and `relations` that are unavailable in standard Prisma middleware, enabling fine-grained control over complex data manipulations.","status":"active","version":"4.0.0","language":"javascript","source_language":"en","source_url":"https://github.com/olivierwilkinson/prisma-nested-middleware","tags":["javascript","prisma","client","middleware","typescript"],"install":[{"cmd":"npm install prisma-nested-middleware","lang":"bash","label":"npm"},{"cmd":"yarn add prisma-nested-middleware","lang":"bash","label":"yarn"},{"cmd":"pnpm add prisma-nested-middleware","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Required peer dependency for Prisma ORM functionality.","package":"@prisma/client","optional":false}],"imports":[{"note":"This is the primary function to wrap your custom middleware. The package primarily uses ESM, though CommonJS `require` might work with transpilation or specific Node.js configurations.","wrong":"const createNestedMiddleware = require('prisma-nested-middleware')","symbol":"createNestedMiddleware","correct":"import { createNestedMiddleware } from 'prisma-nested-middleware'"},{"note":"This TypeScript type extends `Prisma.MiddlewareParams` with additional fields like `scope`, `modifier`, `logicalOperators`, and `relations` for handling nested contexts.","symbol":"NestedParams","correct":"import type { NestedParams } from 'prisma-nested-middleware'"},{"note":"While not from this package, `PrismaClient` is essential for setting up the middleware with `$use` and is often mistakenly imported from `prisma-nested-middleware` by new users.","symbol":"PrismaClient","correct":"import { PrismaClient } from '@prisma/client'"}],"quickstart":{"code":"import { PrismaClient } from '@prisma/client';\nimport { createNestedMiddleware, NestedParams } from 'prisma-nested-middleware';\n\nconst prisma = new PrismaClient();\n\nprisma.$use(createNestedMiddleware(async (params: NestedParams, next) => {\n  console.log(`[${params.model}] Action: ${params.action}`);\n  if (params.scope) {\n    console.log('  Scope:', params.scope.parentParams?.model, '->', params.scope.relation?.to);\n  }\n  \n  // Example: Modify 'create' args for a nested operation\n  if (params.action === 'create' && params.model === 'Post' && params.scope) {\n    console.log('  Intercepted nested Post create:', params.args);\n    // Ensure params.args structure for nested creates, which can vary by version\n    if ('data' in params.args && typeof params.args.data === 'object') {\n      // For v2.x to <v3.0.0, data was inside params.args.data\n      params.args.data.title = `[Nested] ${params.args.data.title}`;\n    } else if (typeof params.args === 'object') {\n      // For v3.x onwards, data is directly in params.args\n      params.args.title = `[Nested] ${params.args.title}`;\n    }\n  }\n\n  const result = await next(params);\n\n  if (result) {\n    console.log(`[${params.model}] Result for ${params.action}:`, result);\n  }\n  return result;\n}));\n\nasync function main() {\n  await prisma.user.deleteMany({});\n  await prisma.post.deleteMany({});\n\n  const user = await prisma.user.create({\n    data: {\n      email: 'test@example.com',\n      name: 'Test User',\n      posts: {\n        create: [\n          { title: 'First Post', content: 'Content 1' },\n          { title: 'Second Post', content: 'Content 2' }\n        ],\n      },\n    },\n    include: { posts: true },\n  });\n  console.log('\\nCreated user with nested posts:', JSON.stringify(user, null, 2));\n}\n\nmain().catch(console.error).finally(() => prisma.$disconnect());","lang":"typescript","description":"This quickstart demonstrates how to apply `prisma-nested-middleware` to your Prisma client and shows an example of intercepting and modifying nested 'create' operations on 'Post' models, logging parameters and results. It also includes handling for varying `params.args` structures across major versions for nested 'create' actions."},"warnings":[{"fix":"Re-evaluate middleware logic for handling 'select' objects inside 'include' operations. You may need to manually traverse the `include` structure or adapt to alternative ways of modifying these specific nested selections, if applicable within your use case.","message":"Version 4.0.0 removed the ability for middleware to be called with the 'select' action for 'select' objects found within an 'include' statement. Middleware that relied on this specific call pattern will no longer function as expected for such scenarios.","severity":"breaking","affected_versions":">=4.0.0"},{"fix":"Update middleware for nested 'create' operations to access `params.args` directly for the data, removing any `.data` access that was added for v2.x compatibility. Example: `params.args.title` instead of `params.args.data.title`.","message":"In version 3.0.0, the structure for nested 'create' actions was reverted: `params.args` no longer moves its content into a `data` field. This directly reverses the breaking change introduced in v2.0.0. If you upgraded from v2.x, your middleware might be broken.","severity":"breaking","affected_versions":">=3.0.0 <4.0.0"},{"fix":"Update middleware for nested 'create' operations to access the data via `params.args.data`. Example: `params.args.data.title` instead of `params.args.title`.","message":"Version 2.0.0 introduced a breaking change where for nested 'create' actions, `params.args` would contain its content within a `data` field (e.g., `params.args.data`). Middleware written for prior versions would break, as they would expect `params.args` to directly hold the data.","severity":"breaking","affected_versions":">=2.0.0 <3.0.0"},{"fix":"Always import and type-check against `NestedParams` to ensure full access to the nested context. Refer to the library's documentation for the structure and purpose of `scope` and its sub-fields to correctly implement conditional logic for nested operations.","message":"The `NestedParams` object provided by this library extends `Prisma.MiddlewareParams` with additional fields like `scope`, `modifier`, `logicalOperators`, and `relations`. Not accounting for these enriched fields can lead to incomplete middleware logic or runtime errors when attempting to access them.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"If upgrading to Prisma ORM versions that deprecate or remove `$use` middleware, consider migrating to `prisma-extension-nested-operations`, which leverages Prisma Client Extensions for a more future-proof approach. The maintainer of `prisma-nested-middleware` also maintains `prisma-extension-nested-operations`.","message":"Prisma's built-in `$use` middleware is deprecated in Prisma ORM v4.16.0 and removed in v6.14.0. Users of `prisma-nested-middleware` should be aware that the underlying mechanism it leverages is being phased out by Prisma.","severity":"gotcha","affected_versions":">=4.16.0 of @prisma/client"}],"env_vars":null,"last_verified":"2026-04-22T00:00:00.000Z","next_check":"2026-07-21T00:00:00.000Z","problems":[{"fix":"Wrap your middleware function with `createNestedMiddleware` from this library and apply it to your `PrismaClient` using `$use`. This library specifically enables middleware execution for nested operations.","cause":"Prisma's native middleware (`prisma.$use`) is designed for top-level queries only and does not inherently intercept operations within nested `create`, `update`, or `connect` clauses.","error":"Prisma middleware not being called for nested writes"},{"fix":"Upgrade `prisma-nested-middleware` to version `3.0.2` or higher, which includes a fix for this issue. Additionally, ensure your `where` arrays adhere to Prisma's expected structure for logical operators.","cause":"Older versions of `prisma-nested-middleware` had a bug in parsing malformed logical `where` conditions (e.g., `AND`, `OR`, `NOT`).","error":"Error parsing invalid logical where arrays"},{"fix":"Upgrade `prisma-nested-middleware` to version `3.0.1` or higher. This version contains a fix for handling JSON `NullTypes` correctly.","cause":"A bug in older versions of `prisma-nested-middleware` affected queries involving Prisma's JSON `NullTypes`.","error":"Queries that use Json NullTypes are not working correctly"}],"ecosystem":"npm","meta_description":null}