Add methods to Prisma Client

You can use the client Prisma Client extensions component to add top-level methods to Prisma Client. We introduced this feature in version 4.7.0.

Enable the preview feature

Before you create Prisma Client extensions, you must enable the clientExtensions feature flag in the generator block of your schema.prisma file, as follows:

generator client {
provider = "prisma-client-js"
previewFeatures = ["clientExtensions"]
}

Extend Prisma Client

Use the $extends client-level method to create an extended client. An extended client is a variant of the standard Prisma Client that is wrapped by one or more extensions. Use the client extension component to add top-level methods to Prisma Client.

To add a top-level method to Prisma Client, use the following structure:

const xprisma = prisma.$extends({
client?: { ... }
})

Example

The following example uses the client component to add two methods to Prisma Client:

  • $log outputs a message.
  • $totalQueries returns the number of queries executed by the current client instance. It uses the metrics feature to collect this information.

To use metrics in your project, you must enable the metrics feature flag in the generator block of your schema.prisma file. Learn more.

const prisma = new PrismaClient().$extends({
client: {
$log: (s: string) => console.log(s),
async $totalQueries() {
const index_prisma_client_queries_total = 0
// Prisma.getExtensionContext(this) in the following block
// returns the current client instance
const metricsCounters = await (
await Prisma.getExtensionContext(this).$metrics.json()
).counters
return metricsCounters[index_prisma_client_queries_total].value
},
},
})
async function main() {
prisma.$log('Hello world')
const totalQueries = await prisma.$totalQueries()
console.log(totalQueries)
}
Edit this page on GitHub