Skip to main content

Overview

Custom plugins allow you to extend Kysely’s functionality by intercepting queries before execution and transforming results after execution. This guide covers everything you need to know to create powerful, reusable plugins.

Basic Plugin Structure

Every plugin must implement the KyselyPlugin interface:

Simple No-Op Plugin

The simplest plugin does nothing - it just returns the query and result unchanged:
Source: ~/workspace/source/src/plugin/noop-plugin.ts:10

Result Transformation Plugin

Plugins that only transform results can leave transformQuery as a no-op:

Query Transformation with OperationNodeTransformer

For complex query transformations, extend OperationNodeTransformer:

Sharing Data Between transformQuery and transformResult

Use a WeakMap to share data between the two methods:
Always use WeakMap instead of Map because transformQuery is not always matched by a call to transformResult, which would leave orphaned items in a regular Map and cause a memory leak.

Plugin with Configuration Options

Make plugins configurable with options:

Advanced: Row-Level Transformation

Transform individual rows with recursive processing:

Advanced: Schema Transformation Plugin

Example of a complex plugin that modifies query structure:

Testing Plugins

Best Practices

1. Use WeakMap for State

Always use WeakMap to store state between transformQuery and transformResult:

2. Handle Null/Undefined Results

Always check if results exist before transforming:

3. Preserve Immutability

Create new objects instead of mutating:

4. Make Plugins Configurable

Provide options with sensible defaults:

5. Document Your Plugin

Provide clear documentation and examples:

Common Use Cases

Logging Plugin

Soft Delete Plugin

Encryption Plugin

See Also