> ## Documentation Index
> Fetch the complete documentation index at: https://cockroachlabs.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Userscript Overview

export const InternalLink = ({version, path = "", children, ...props}) => {
  let detectedVersion = version || "stable";
  if (typeof window !== 'undefined' && !version) {
    const match = window.location.pathname.match(/\/docs\/([^/]+)/);
    if (match) {
      detectedVersion = match[1];
    }
  }
  const normalizedPath = path.startsWith("/") ? path.slice(1) : path;
  return <a href={`/docs/${detectedVersion}/${normalizedPath}`} {...props}>
      {children}
    </a>;
};

<InternalLink path="molt-replicator">MOLT Replicator</InternalLink> can apply *userscripts*, specified with the <InternalLink path="replicator-flags#userscript">`--userscript` flag</InternalLink>, to customize how data is processed and transformed as it moves through the live replication pipeline.

Userscripts are intended to address unique business or data transformation needs. They perform operations that cannot be handled by the source change data capture (CDC) stream, such as filtering out specific tables, rows, or columns; routing data from a single source table to multiple target tables; transforming column values or adding computed columns; and implementing custom error handling. For more examples of how userscripts can be used, refer to [Common uses](#common-uses).

Userscripts are <InternalLink path="userscript-cookbook">written in TypeScript</InternalLink> and run inside MOLT Replicator, giving you full programmatic control of your replication flow while maintaining type safety and consistency.

## Prerequisites

* <InternalLink path="molt-replicator">Install MOLT Replicator **v1.3.0 or later**</InternalLink> for full compatibility with the <InternalLink path="userscript-api">userscript API</InternalLink>.
* [Install TypeScript](https://www.typescriptlang.org/download/), and install a TypeScript-compatible IDE (for example, VS Code).
* Download the [userscript type definitions file](https://replicator.cockroachdb.com/userscripts/replicator@v2.d.ts) and the [tsconfig.json file](https://replicator.cockroachdb.com/userscripts/tsconfig.json). Place these files in your working directory to enable autocomplete, inline documentation, and real-time error detection directly in your IDE.

## How it works

Userscripts act as a customizable processing layer within MOLT Replicator's live replication lifecycle. They are used to intercept, inspect, and modify the flow of data as it moves from the source database to the target database, enabling full control over how rows are transformed, filtered, or written; as well as providing the ability to run custom transactional logic against the target database.

Userscripts are comparable to MOLT Fetch's <InternalLink path="molt-fetch#define-transformations">transformations</InternalLink>, which are used during the initial bulk load phase of a migration. However, userscripts provide much greater customizability. When performing an <InternalLink path="molt-replicator#forward-replication-after-initial-load">initial data load followed by live replication</InternalLink>, **apply equivalent transformations in both the Fetch command and Replicator userscript** to ensure data consistency.

The following diagram illustrates how userscripts fit into the replication pipeline:

<img src="https://mintcdn.com/cockroachlabs/bALSwIJ7kkDMfVP4/images/molt/userscript-flow.png?fit=max&auto=format&n=bALSwIJ7kkDMfVP4&q=85&s=9d6729a407c912c6a2a3e72bb2abb152" alt="Userscript flow" style={{ border: "1px solid #eee", maxWidth: "65%", display: "block", marginLeft: "auto", marginRight: "auto" }} width="1337" height="1600" data-path="images/molt/userscript-flow.png" />

1. **Source changefeed**: Replicator continuously listens to the source database's changefeed for row modification events.

2. **Userscript processing**: When Replicator receives change events from the source database, it passes them through the userscript in two phases, in the following sequence:

   1. Schema-level handlers (<InternalLink path="userscript-api#configure-target-schema-on-row-upsert">`onRowUpsert`</InternalLink>, <InternalLink path="userscript-api#configure-target-schema-on-row-delete">`onRowDelete`</InternalLink>) are invoked to transform, filter, or route rows before buffering them in a <InternalLink path="molt-replicator#terminology">staging database</InternalLink> for ordered processing.

   2. After rows are retrieved from the staging database, table-level handlers (<InternalLink path="userscript-api#configure-target-tables-on-row-upsert">`onRowUpsert`</InternalLink> and <InternalLink path="userscript-api#configure-target-tables-on-row-delete">`onRowDelete`</InternalLink>, followed by <InternalLink path="userscript-api#configure-target-tables-on-write">`onWrite`</InternalLink>) are invoked to apply final transformations and custom write logic.

   <Tip>
     For details on these handlers and other configuration functions, refer to <InternalLink path="userscript-api">Userscript API</InternalLink>.
   </Tip>

3. **Commit to target database**: Replicator commits the transformed rows to the target database in a single transactional write. Target database writes and logic will only be scheduled to be committed after `onWrite` returns, or all table-level handlers are run.

This allows you to precisely defines how data from your source system should look and behave once it reaches your target database, without needing to modify MOLT Replicator's core logic.

Userscripts run in a sandboxed JavaScript runtime inside <InternalLink path="molt-replicator">MOLT Replicator</InternalLink> that implements the core ECMAScript language but does **not** include the extended standard library APIs found in Node.js or web browsers (such as filesystem, networking, or timers). Learn more about [unsupported TypeScript features](#unsupported-typescript-features).

## Usage

To have MOLT Replicator apply a userscript, include the <InternalLink path="replicator-flags#userscript">`--userscript`</InternalLink> flag with any <InternalLink path="replicator-flags">Replicator command</InternalLink>. The flag accepts a path to a TypeScript filename.

```
--userscript 'path/to/script.ts'
```

For example, to apply a userscript named `table_filter.ts` during PostgreSQL replication:

```shell theme={"theme":{"light":"catppuccin-mocha","dark":"catppuccin-mocha"}}
replicator pglogical \
  --sourceConn $SOURCE \
  --targetConn $TARGET \
  ...
  --userscript 'table_filter.ts'
```

## Common uses

Userscripts customize the standard behavior of the source change data capture (CDC) stream consumed by Replicator. Common use cases include:

* <InternalLink path="userscript-cookbook#rename-tables">Renaming tables</InternalLink>: Map source table names to different names on the target.
* <InternalLink path="userscript-cookbook#rename-columns">Renaming columns</InternalLink>: Map source column names to different names on the target.
* <InternalLink path="userscript-cookbook#select-data-to-replicate">Row filtering</InternalLink>: Filter out specific rows based on conditions, such as excluding soft-deleted records or test data.
* <InternalLink path="userscript-cookbook#filter-multiple-tables">Table filtering</InternalLink>: Exclude specific tables from replication.
* <InternalLink path="userscript-cookbook#filter-columns">Column filtering</InternalLink>: Remove sensitive or unnecessary columns from replicated data.
* <InternalLink path="userscript-cookbook#compute-new-columns">Data transformation</InternalLink>: Transform column values, compute new columns, or change data types during replication.
* <InternalLink path="userscript-cookbook#route-table-partitions">Table partitioning</InternalLink>: Distribute rows from a single source table across multiple target tables based on partitioning rules.
* <InternalLink path="userscript-cookbook#implement-a-dead-letter-queue">Dead-letter queues</InternalLink>: Route failed operations to a separate (DLQ) table for offline inspection and recovery.

For ready-to-use templates that handle the preceding use cases, refer to the <InternalLink path="userscript-cookbook">userscript cookbook</InternalLink>.

## Unsupported TypeScript features

Userscripts are TypeScript files that support [ECMAScript 5.1](https://262.ecma-international.org/5.1/), with partial [ES6](https://262.ecma-international.org/6.0/) support.

The JavaScript execution environment in which userscripts run is intentionally minimal. It implements the core ECMAScript language but does not include the extended standard library APIs found in Node.js or web browsers. This ensures that userscripts remain lightweight, deterministic, and focused solely on processing data and executing transactional logic.

The following capabilities are not available within userscripts:

* **Filesystem**: No file reading or writing, directory listing, file streams, or `fs` module.
* **Networking**: No HTTP/HTTPS requests, sockets, WebSockets or `fetch`.
* **Process and operating system**: No `process` object, environment variables, subprocess execution, or OS-level access.
* **Timers and scheduling**: No `setTimeout` / `setInterval`.
* **Cryptography and binary utilities**: No hashing or HMAC, secure random generation, WebCrypto, or compression or binary buffers.
* **Workers and parallelism**: No Web Workers, threads, or shared memory.
* **Persistent storage**: No local/session storage, filesystem-backed persistence, built-in key–value store.

Your IDE will not recognize unsupported functions, and attempting to use any of the preceding features will result in a runtime error.

## See also

* <InternalLink path="molt-replicator">MOLT Replicator</InternalLink>
* <InternalLink path="userscript-quickstart">Userscript Quickstart</InternalLink>
* <InternalLink path="userscript-api">Userscript API</InternalLink>
* <InternalLink path="userscript-cookbook">Userscript Cookbook</InternalLink>
* <InternalLink path="userscript-metrics">Userscript Metrics</InternalLink>
