> {
> commentAnnotations.map((commentAnnotation) => {
> return (
>
position: 'absolute',
> left: commentAnnotation.context.position.x + dragPosition.x,
> top: commentAnnotation.context.position.y + dragPosition.y,
> transform: 'translate(0%, -100%)'
> }}>
>
>
> )
> })
> }
>
> )
> ```
> [tab] Other Frameworks
>
> ## 1. Add custom metadata when comment is added
>
> Use the `onCommentAdd` method to add custom metadata to a comment when a new comment is being added.
>
> This metadata can be used later to set the position of the Comment Pin.
> You need to set the mandatory `commentType: 'manual'` property to the metadata object.
>
> ```js theme={null}
> const veltCommentsTag = document.querySelector('velt-comments');
>
> veltCommentsTag?.addEventListener('onCommentAdd', (event) => {
> console.log('*** onCommentAdd ***');
> console.log(event.detail);
> event.detail?.addContext({ customKey: 'customValue', commentType: 'manual'});
> });
>
> ```
>
> ## 2. Retrieve all Comment Annotations
>
> Retrieve all existing `Comment Annotations` using the `getAllCommentAnnotations()` method.
>
> To learn more about the `getAllCommentAnnotations` method, [read here](/docs/async-collaboration/comments/customize-behavior#getcommentannotations).
>
> ```js theme={null}
> const commentElement = Velt.getCommentElement();
> let subscription = commentElement.getAllCommentAnnotations().subscribe((commentAnnotations) => {
> // console.log(commentAnnotations);
> });
> ```
>
> To unsubscribe from the subscription:
>
> ```jsx theme={null}
> subscription?.unsubscribe()
> ```
>
> ## 3. Render the Velt Comment Pin component and set the position
>
> Add the `Velt Comment Pin` component and pass in the `Comment Annotation Id`.
> Now retrieve the `context` to retrieve the custom metadata you set earlier and use it to set the position of the `Comment Pin`.
>
> ```js theme={null}
> const commentElement = Velt.getCommentElement();
>
> let subscription = commentElement.getAllCommentAnnotations().subscribe((commentAnnotations) => {
> renderCommentAnnotations(commentAnnotations);
> });
>
> const commentsContainer = document.getElementById('comments-container');
>
> function renderCommentAnnotations(commentAnnotations) {
> commentAnnotations.forEach((commentAnnotation) => {
> if (!document.getElementById(`comment-pin-container-${commentAnnotation.annotationId}`)) {
> // Add Comment Pin if it doesn't exist
> const { x, y } = commentAnnotation.context.position;
> var commentPinContainer = document.createElement('div');
> commentPinContainer.className = 'comment-pin-container';
> commentPinContainer.id = `comment-pin-container-${commentAnnotation.annotationId}`;
> commentPinContainer.style.left = x + 'px';
> commentPinContainer.style.top = y + 'px';
> commentPinContainer.innerHTML = ` yourMethod(event)} />
{
commentAnnotations.map((commentAnnotation) => {
return (
)
})
}
)
}
```
```html HTML theme={null}
```
# Overview
Source: https://velt.dev/docs/async-collaboration/comments/setup/canvas-comments/overview
Within any charts library you have the option to manually set the position of a Comment Annotation using the `Comment Pin` component.
## How to Use
Use `Comment Pin` in combination with the following:
1. `onCommentAdd`: Add custom metadata when adding a comment. This metadata can be used later to set the position of the Comment Pin. [Learn more](/docs/async-collaboration/comments/customize-behavior#event-subscription)
2. `getAllCommentAnnotations`: Get all Comment Annotations with the custom metadata you set using above. Render the Comment Pin component and use the custom metadata to set its position yourself.
Note for react developers hooks are also available. [Learn more](/docs/async-collaboration/comments/customize-behavior#getcommentannotations)
# ChartJS Comments Setup
Source: https://velt.dev/docs/async-collaboration/comments/setup/chart-comments-setup/chartjs

> [tab] React / Next.js
>
> ## 1. Import Components from Chart.js
>
> ```jsx theme={null}
> import { Chart as ChartJS, BarElement } from 'chart.js';
> import { Bar } from 'react-chartjs-2'
> ```
>
> ## 2. Import Comments Components and Hooks from Velt
>
> * Add `VeltComments` to the root of your app. This component is required to render comments in your app.
> * Add the `VeltCommentTool` component wherever you want to show the comment tool button. Clicking on it initiates comment mode & changes your mouse cursor to a comment pin.
>
> 
>
> ```jsx theme={null}
> import { useCommentModeState, VeltCommentPin, VeltCommentTool, VeltComments } from '@veltdev/react';
> ```
>
> ## 3. Create a ref for the ChartJS component
>
> * Create a `ref` and pass it into the `ref` property of the `ChartJS` component.
>
> ```jsx theme={null}
> const chartRef = useRef(null);
>
>
> ```
>
> ## 4. Add a container div for the ChartJS component
>
> 1. Apply `position: relative` style to the div. This ensures accurate positioning of Velt Comment Pins.
>
> 2. Set `data-velt-manual-comment-container` to `true`. This:
>
> * informs Velt which div to use for positioning
>
> * disables Velt's automatic comment positioning system within this div, allowing for manual positioning of comment pins
>
> 3. Give a unique ID to the chart to scope comments to the specific chart, isolating them from other charts.
>
> ```jsx theme={null}
> const chartId = 'dataAnalyticsChart'; // Unique ID for the chart
> ```
>
> ```jsx theme={null}
> return (
> onClick={handleChartClick}
> data-velt-manual-comment-container="true">
>
>
>
> );
> ```
>
> ## 5. Add a Comment when the user clicks on the chart
>
> 1. Handle chart click to find nearest data point and add a comment. *(Check `handleChartClick() method` on the right)*
>
> 2. Create `context` object which contains the information about the series, x-axis value, y-axis value, chartId and anything else that's relevant. This will be used when rendering the comment pin. *(Check `handleChartClick() method` on the right)*
>
> 3. Add comment with the `context` data. *(Check `addManualComment() method` on the right)*
>
> * Only add a comment if the Velt `commentModeState` is true and the Velt `client` is available.
>
> ## 6. Render the Velt Comment Pins and set its position
>
> 1. Get all comment annotations.
> 2. Loop through it and render the comment pin.
> 3. Use the `context` data in `CommentAnnotation`, to set the position of the comment pin. *(Check `showCommentPin() method` on the right)*
>
> ```jsx theme={null}
> const commentAnnotations = useCommentAnnotations(); // Get Velt comment annotations
> const [chartCommentAnnotations, setChartCommentAnnotations] = React.useState([]); // Store annotations for this chart
>
> useEffect(() => {
> // Filter and store comments for the current chart, using unique chart ID
> const chartCommentAnnotations = commentAnnotations?.filter((comment) => comment.context?.chartId === chartId);
> setChartCommentAnnotations(chartCommentAnnotations as any || []);
> }, [commentAnnotations]);
>
> return (
> ... {/* Rest of the container code. */}
>
> {/* Loop through comment annotations and render the comment pin. */}
> {chartCommentAnnotations.map((comment, index) => showCommentPin(comment))}
>
> ... {/* Rest of the container code. */}
> );
> ```
> [tab] HTML (coming soon)
>
> Coming Soon
```js React / Next.js theme={null}
import React, { useEffect, useRef, useMemo } from 'react';
import { Chart as ChartJS, CategoryScale, LinearScale, PointElement, BarElement, Title, Tooltip, Legend, Filler,} from 'chart.js';
import { Bar } from 'react-chartjs-2';
import { useVeltClient, useCommentAnnotations, useCommentModeState, VeltCommentPin } from '@veltdev/react';
// Register the necessary Chart.js components
ChartJS.register(CategoryScale, LinearScale, PointElement, BarElement, Title, Tooltip, Legend, Filler);
// Define the data for the chart
const scores = [6, 5, 5, 5, 3, 4, 6, 4, 5];
const labels = [100, 200, 300, 400, 500, 600, 700];
// Set the options for the chart
const options: any = {
// your chart options
};
const BarChart = () => {
const chartId = 'dataAnalyticsChart'; // Unique ID for the chart
const chartRef = useRef(null); // Reference to the chart instance
const { client } = useVeltClient(); // Get Velt client
const commentModeState = useCommentModeState(); // Get Velt comment mode state
const commentAnnotations = useCommentAnnotations(); // Get Velt comment annotations
const [chartCommentAnnotations, setChartCommentAnnotations] = React.useState([]); // State for chart comments
// Update chart comments when annotations change
useEffect(() => {
// Filter comments for the current chart, using unique chart ID
const chartCommentAnnotations = commentAnnotations?.filter((comment) => comment.context?.chartId === chartId);
setChartCommentAnnotations(chartCommentAnnotations as any || []);
}, [commentAnnotations]);
// Handle chart clicks to find nearest data point and add a comment
const handleChartClick = (event: any) => {
const chart: any = chartRef.current;
if (chart) {
// Get the nearest element to the click event
const elements = chart.getElementsAtEventForMode(event.nativeEvent, 'nearest', { intersect: true }, false);
if (elements.length > 0) {
const element = elements[0];
const datasetIndex = element.datasetIndex;
const index = element.index;
const dataset = chart.data.datasets[datasetIndex];
const xValue = chart.data.labels[index];
const yValue = dataset.data[index];
const context = { seriesId: dataset.label, xValue, yValue, chartId };
addManualComment(context); // Add a comment at the nearest data point with the context data
}
}
};
// Add a manual comment to the chart
const addManualComment = (context: any) => {
try {
if (client && commentModeState) {
const commentElement = client.getCommentElement();
commentElement.addManualComment({ context }); // Add a Velt comment
}
} catch (error) {
console.error('Error adding manual comment', error);
}
};
// Find the exact point on the chart to place a comment pin
const findPoint = (seriesId: any, xValue: any, yValue: any) => {
const chart: any = chartRef.current;
if (chart) {
const dataset = chart.data.datasets.find((dataset: any) => dataset.label === seriesId);
const index = chart.data.labels.indexOf(xValue);
if (dataset && index !== -1) {
const yValueInDataset = dataset.data[index];
if (yValueInDataset === yValue) {
return { x: chart.scales.x.getPixelForValue(index), y: chart.scales.y.getPixelForValue(yValue) }; // Set the x, y position for the comment pin
}
}
}
return null;
};
// Show the comment pin on the chart at the specified point
const showCommentPin = (commentAnnotation: any) => {
const context = commentAnnotation.context || {};
const point = findPoint(context.seriesId, context.xValue, context.yValue);
if (point) {
const { x, y } = point;
return (
{/* Velt comment pin component */}
);
}
return null;
};
// Memoize the chart data
const data = useMemo(() => {
return {
datasets: [
{
label: 'Mis datos',
tension: 0.3,
data: scores,
borderColor: 'rgb(75, 192, 192)',
backgroundColor: 'rgba(75, 192, 192, 0.3)',
},
],
labels,
};
}, []);
return (
Bar Chart With Comments
{/* Keep the parent div as relative, as comment pin will be placed with absolute position */}
{/* Set "data-velt-manual-comment-container" to true, so that comment pin will know which div to consider while positioning */}
{/* Render the Bar chart */}
{chartCommentAnnotations.map((comment, index) => showCommentPin(comment))} {/* Show all comment pins */}
);
};
export default BarChart;
```
# Custom Charts Setup
Source: https://velt.dev/docs/async-collaboration/comments/setup/chart-comments-setup/custom-charts

> [!NOTE]
>
> Here we have used ChartJS as an example library, you can follow the approach for any other charting library
> [tab] React / Next.js
>
> ## 1. Import Components from your Charts Library
>
> ```jsx theme={null}
> import { Chart as ChartJS, BarElement } from 'chart.js';
> import { Bar } from 'react-chartjs-2'
> ```
>
> ## 2. Import Comments Components and Hooks from Velt
>
> * Add `VeltComments` to the root of your app. This component is required to render comments in your app.
> * Add the `VeltCommentTool` component wherever you want to show the comment tool button. Clicking on it initiates comment mode & changes your mouse cursor to a comment pin.
>
> 
>
> ```jsx theme={null}
> import { useCommentModeState, VeltCommentPin, VeltCommentTool, VeltComments } from '@veltdev/react';
> ```
>
> ## 3. Create a ref for the Chart component
>
> * Create a `ref` and pass it into the `ref` property of the `ChartJS` component.
>
> ```jsx theme={null}
> const chartRef = useRef(null);
>
>
> ```
>
> ## 4. Add a container div for the Chart component
>
> 1. Apply `position: relative` style to the div. This ensures accurate positioning of Velt Comment Pins.
>
> 2. Set `data-velt-manual-comment-container` to `true`. This:
>
> * informs Velt which div to use for positioning
>
> * disables Velt's automatic comment positioning system within this div, allowing for manual positioning of comment pins
>
> 3. Give a unique ID to the chart to scope comments to the specific chart, isolating them from other charts.
>
> ```jsx theme={null}
> const chartId = 'dataAnalyticsChart'; // Unique ID for the chart
> ```
>
> ```jsx theme={null}
> return (
> onClick={handleChartClick}
> data-velt-manual-comment-container="true">
>
>
>
> );
> ```
>
> ## 5. Add a Comment when the user clicks on the chart
>
> 1. Handle chart click to find nearest data point and add a comment. *(Check `handleChartClick() method` on the right)*
>
> 2. Create `context` object which contains the information about the series, x-axis value, y-axis value, chartId and anything else that's relevant. This will be used when rendering the comment pin. *(Check `handleChartClick() method` on the right)*
>
> 3. Add comment with the `context` data. *(Check `addManualComment() method` on the right)*
>
> * Only add a comment if the Velt `commentModeState` is true and the Velt `client` is available.
>
> ## 6. Render the Velt Comment Pins and set its position
>
> 1. Get all comment annotations.
> 2. Loop through it and render the comment pin.
> 3. Use the `context` data in `CommentAnnotation`, to set the position of the comment pin. *(Check `showCommentPin() method` on the right)*
>
> ```jsx theme={null}
> const commentAnnotations = useCommentAnnotations(); // Get Velt comment annotations
> const [chartCommentAnnotations, setChartCommentAnnotations] = React.useState([]); // Store annotations for this chart
>
> useEffect(() => {
> // Filter and store comments for the current chart, using unique chart ID
> const chartCommentAnnotations = commentAnnotations?.filter((comment) => comment.context?.chartId === chartId);
> setChartCommentAnnotations(chartCommentAnnotations as any || []);
> }, [commentAnnotations]);
>
> return (
> ... {/* Rest of the container code. */}
>
> {/* Loop through comment annotations and render the comment pin. */}
> {chartCommentAnnotations.map((comment, index) => showCommentPin(comment))}
>
> ... {/* Rest of the container code. */}
> );
> ```
> [tab] HTML (coming soon)
>
> Coming Soon
```js React / Next.js theme={null}
import React, { useEffect, useRef, useMemo } from 'react';
import { Chart as ChartJS, CategoryScale, LinearScale, PointElement, BarElement, Title, Tooltip, Legend, Filler,} from 'chart.js';
import { Bar } from 'react-chartjs-2';
import { useVeltClient, useCommentAnnotations, useCommentModeState, VeltCommentPin } from '@veltdev/react';
// Register the necessary Chart.js components
ChartJS.register(CategoryScale, LinearScale, PointElement, BarElement, Title, Tooltip, Legend, Filler);
// Define the data for the chart
const scores = [6, 5, 5, 5, 3, 4, 6, 4, 5];
const labels = [100, 200, 300, 400, 500, 600, 700];
// Set the options for the chart
const options: any = {
// your chart options
};
const BarChart = () => {
const chartId = 'dataAnalyticsChart'; // Unique ID for the chart
const chartRef = useRef(null); // Reference to the chart instance
const { client } = useVeltClient(); // Get Velt client
const commentModeState = useCommentModeState(); // Get Velt comment mode state
const commentAnnotations = useCommentAnnotations(); // Get Velt comment annotations
const [chartCommentAnnotations, setChartCommentAnnotations] = React.useState([]); // State for chart comments
// Update chart comments when annotations change
useEffect(() => {
// Filter comments for the current chart, using unique chart ID
const chartCommentAnnotations = commentAnnotations?.filter((comment) => comment.context?.chartId === chartId);
setChartCommentAnnotations(chartCommentAnnotations as any || []);
}, [commentAnnotations]);
// Handle chart clicks to find nearest data point and add a comment
const handleChartClick = (event: any) => {
const chart: any = chartRef.current;
if (chart) {
// Get the nearest element to the click event
const elements = chart.getElementsAtEventForMode(event.nativeEvent, 'nearest', { intersect: true }, false);
if (elements.length > 0) {
const element = elements[0];
const datasetIndex = element.datasetIndex;
const index = element.index;
const dataset = chart.data.datasets[datasetIndex];
const xValue = chart.data.labels[index];
const yValue = dataset.data[index];
const context = { seriesId: dataset.label, xValue, yValue, chartId };
addManualComment(context); // Add a comment at the nearest data point with the context data
}
}
};
// Add a manual comment to the chart
const addManualComment = (context: any) => {
try {
if (client && commentModeState) {
const commentElement = client.getCommentElement();
commentElement.addManualComment({ context }); // Add a Velt comment
}
} catch (error) {
console.error('Error adding manual comment', error);
}
};
// Find the exact point on the chart to place a comment pin
const findPoint = (seriesId: any, xValue: any, yValue: any) => {
const chart: any = chartRef.current;
if (chart) {
const dataset = chart.data.datasets.find((dataset: any) => dataset.label === seriesId);
const index = chart.data.labels.indexOf(xValue);
if (dataset && index !== -1) {
const yValueInDataset = dataset.data[index];
if (yValueInDataset === yValue) {
return { x: chart.scales.x.getPixelForValue(index), y: chart.scales.y.getPixelForValue(yValue) }; // Set the x, y position for the comment pin
}
}
}
return null;
};
// Show the comment pin on the chart at the specified point
const showCommentPin = (commentAnnotation: any) => {
const context = commentAnnotation.context || {};
const point = findPoint(context.seriesId, context.xValue, context.yValue);
if (point) {
const { x, y } = point;
return (
{/* Velt comment pin component */}
);
}
return null;
};
// Memoize the chart data
const data = useMemo(() => {
return {
datasets: [
{
label: 'Mis datos',
tension: 0.3,
data: scores,
borderColor: 'rgb(75, 192, 192)',
backgroundColor: 'rgba(75, 192, 192, 0.3)',
},
],
labels,
};
}, []);
return (
Bar Chart With Comments
{/* Keep the parent div as relative, as comment pin will be placed with absolute position */}
{/* Set "data-velt-manual-comment-container" to true, so that comment pin will know which div to consider while positioning */}
{/* Render the Bar chart */}
{chartCommentAnnotations.map((comment, index) => showCommentPin(comment))} {/* Show all comment pins */}
);
};
export default BarChart;
```
# Highcharts Comments Setup
Source: https://velt.dev/docs/async-collaboration/comments/setup/chart-comments-setup/highcharts

> [tab] React / Next.js
>
> ## 1. Import components from Highcharts
>
> ```jsx theme={null}
> import Highcharts from 'highcharts';
> import HighchartsReact from 'highcharts-react-official';
> ```
>
> ## 2. Import Comment components from Velt
>
> * Add `VeltComments` once to the root of your app. This component is required to render comments in your app.
>
> ```jsx theme={null}
> import { VeltHighChartComments, VeltComments } from '@veltdev/react';
> ```
>
> ## 3. Create a ref for the HighchartsReact component
>
> * Create a `ref` and pass it into the `ref` property of the `HighchartsReact` component.
> * This ref object will be used by Velt to get the Chart data and add comment pin to it.
>
> ```jsx theme={null}
> const chartComponentRef = useRef(null);
>
> highcharts={Highcharts}
> options={options}
> ref={chartComponentRef}
> />
> ```
>
> ## 4. Add a container div for the HighchartsReact component
>
> * Give it a `position: relative` style. This will help position the Velt Comment Pins accurately.
>
> ```jsx theme={null}
>
> highcharts={Highcharts}
> options={options}
> ref={chartComponentRef}
> />
>
> ```
>
> ## 5. Add VeltHighChartComments component in the same container
>
> * Conditionally render `VeltHighChartsComments` in the same container div as the `HighchartsReact` component.
> * Set a unique `id` in the VeltHighChartsComments component to scope comments to the specific chart, isolating them from other charts.
> * Pass the `chartComputedData` prop with the `ref` you created earlier.
>
> ```jsx theme={null}
>
> highcharts={Highcharts}
> options={options}
> ref={chartComponentRef}
> />
> {
> chartComponentRef.current &&
> }
>
> ```
>
> ## 6. (Optional) Customize the Chart Metadata displayed in the Comment Dialog
>
> * Pass an array to the `dialogMetadataTemplate` prop in the VeltHighChartsComments component.
> * This array determines the chart metadata displayed in the comment dialog, representing the data point (e.g., x-axis and y-axis values) on which the comment was added.
> * Customize the order of the keys or remove unnecessary keys to control how the metadata is presented in the comment dialog.
>
> `Default: ['groupId', 'label', 'value']`
>
> For example:
>
> ```jsx theme={null}
> id="HighChartsLineChartExample"
> chartComputedData={chartComputedData}
> dialogMetadataTemplate={['label', 'value', 'groupId']} />
> ```
> [tab] HTML (coming soon)
>
> Coming Soon
```js React / Next.js theme={null}
import React, { useEffect, useRef, useState } from 'react';
import { VeltHighChartComments } from '@veltdev/react';
import Highcharts from 'highcharts';
import HighchartsReact from 'highcharts-react-official';
function HighChartsLineChartExample() {
const [data, setData] = useState(CHART_DATA);
const chartComponentRef = useRef(null);
const options = {
// your chart options
};
return (
{
chartComponentRef.current &&
}
);
}
```
# NivoCharts Comments Setup
Source: https://velt.dev/docs/async-collaboration/comments/setup/chart-comments-setup/nivo-charts

> [tab] React / Next.js
>
> ## 1. Import components from Nivo Charts
>
> ```jsx theme={null}
> import { ResponsiveLine } from '@nivo/line';
> ```
>
> ## 2. Import VeltNivoChartComments component from Velt
>
> * Add `VeltComments` once to the root of your app. This component is required to render comments in your app.
>
> ```jsx theme={null}
> import { VeltNivoChartComments, VeltComments } from '@veltdev/react';
> ```
>
> ## 3. Add a container div for the Nivo Chart component
>
> * Add a `nivo-chart-container` class to it. This will help us position the Velt Comment Pins accurately.
>
> ```jsx theme={null}
>
> data={data}
> layers={[
> 'grid', 'markers', 'axes', 'areas', 'crosshair',
> 'lines', 'slices', 'legends', 'points',
> ]}
> />
>
> ```
>
> ## 4. Add VeltNivoChartComments to the Nivo Chart component
>
> * Add a custom function as a layer inside your Nivo Chart component and return `VeltNivoChartComments` component.
> * Set a unique `id` in the VeltNivoChartComments component to scope comments to the specific chart, isolating them from other charts.
> * Pass the `chartComputedData` props to it.
>
> ```jsx theme={null}
> data={data}
> layers={[
> 'grid', 'markers', 'axes', 'areas', 'crosshair',
> 'lines', 'slices', 'legends', 'points',
> // Add this function with VeltNivoChartComments
> // component to allow Velt comments inside the Chart
> (chartComputedData) => {
> return (
>
> )
> }
> ]}
> />
> ```
>
> ## 5. (Optional) Customize the Chart Metadata displayed in the Comment Dialog
>
> * Pass an array to the `dialogMetadataTemplate` prop in the VeltHighChartsComments component.
> * This array determines the chart metadata displayed in the comment dialog, representing the data point (e.g., x-axis and y-axis values) on which the comment was added.
> * Customize the order of the keys or remove unnecessary keys to control how the metadata is presented in the comment dialog.
>
> `Default: ['groupId', 'label', 'value']`
>
> For example:
>
> ```jsx theme={null}
> id="NivoLineChartExample"
> chartComputedData={chartComputedData}
> dialogMetadataTemplate={['label', 'value', 'groupId']} />
> ```
> [tab] HTML (coming soon)
>
> Coming Soon
```js React / Next.js theme={null}
import { ResponsiveLine } from '@nivo/line';
import { VeltNivoChartComments } from '@veltdev/react';
import { useState } from 'react'
function YourComponent() {
const [data, setData] = useState(CHART_DATA);
return (
// add nivo-chart-container class to the parent element of your NivoChart
{
return (
)
}
]}
/>
)
}
```
# CKEditor Setup
Source: https://velt.dev/docs/async-collaboration/comments/setup/ckeditor
Add Velt comments to a CKEditor 5 editor with the Velt CKEditor comments plugin.

## Setup
#### Step 1: Add Comment components
* Add the `Velt Comments` component to the root of your app.
* This component is required to render comments in your app.
* Set the `text mode` prop to `false` to hide the default text comment tool.
* CKEditor selections are handled by `@veltdev/ckeditor-velt-comments`.
* Authenticate the user with `authProvider` and set the Velt document before users add comments.
* Add `VeltCommentsSidebar` if you want a Google Docs-style comment sidebar.
> [tab] React / Next.js
>
> ```tsx theme={null}
> import { VeltComments, VeltCommentsSidebar, VeltProvider, useSetDocument } from '@veltdev/react';
>
> const user = {
> userId: 'user-1',
> organizationId: 'org-1',
> name: 'User One',
> email: 'user@example.com',
> };
>
> function VeltSetup() {
> useSetDocument('document-id', { documentName: 'Document name' });
> return null;
> }
>
> function App() {
> return (
>
>
>
>
> {/* Your app content */}
>
> );
> }
> ```
#### Step 2: Install the Velt CKEditor extension
```bash theme={null}
npm i @veltdev/ckeditor-velt-comments @ckeditor/ckeditor5-react ckeditor5
```
`ckeditor5` is a peer dependency of the Velt CKEditor package and must be provided by your app. Import the CKEditor CSS once in your app so the editor and the Velt overlay render correctly.
> [tab] React / Next.js
>
> ```tsx theme={null}
> import 'ckeditor5/ckeditor5.css';
> ```
#### Step 3: Configure the CKEditor editor with the Velt Comments plugin
Add `VeltCommentsPlugin` to the CKEditor `plugins` list and configure it with `veltComments`. Capture the editor instance from `onReady`, then render Velt comment annotations into that instance with `renderComments`.
> [tab] React / Next.js
>
> ```tsx theme={null}
> import { useEffect, useState } from 'react';
> import { CKEditor } from '@ckeditor/ckeditor5-react';
> import {
> ClassicEditor,
> Essentials,
> Paragraph,
> Heading,
> Bold,
> Italic,
> Link,
> List,
> BlockQuote,
> type Editor,
> } from 'ckeditor5';
> import { useCommentAnnotations } from '@veltdev/react';
> import {
> VeltCommentsPlugin,
> renderComments,
> } from '@veltdev/ckeditor-velt-comments';
> import 'ckeditor5/ckeditor5.css';
>
> const EDITOR_ID = 'my-editor';
>
> function CKEditorWithComments() {
> const [editor, setEditor] = useState(null);
> const annotations = useCommentAnnotations();
>
> useEffect(() => {
> if (!editor) return;
>
> renderComments({
> editor,
> editorId: EDITOR_ID,
> commentAnnotations: annotations ?? [],
> });
> }, [editor, annotations]);
>
> return (
> editor={ClassicEditor}
> config={{
> licenseKey: 'GPL',
> plugins: [
> Essentials,
> Paragraph,
> Heading,
> Bold,
> Italic,
> Link,
> List,
> BlockQuote,
> VeltCommentsPlugin,
> ],
> toolbar: [
> 'undo',
> 'redo',
> '|',
> 'heading',
> '|',
> 'bold',
> 'italic',
> 'link',
> '|',
> 'bulletedList',
> 'numberedList',
> '|',
> 'blockQuote',
> ],
> initialData: 'Select text, then add a comment.
',
> veltComments: { editorId: EDITOR_ID },
> }}
> onReady={(nextEditor) => setEditor(nextEditor)}
> onAfterDestroy={() => setEditor(null)}
> />
> );
> }
> ```
#### Step 4: Add a comment button to your CKEditor editor
Add a button that users can click to add comments after selecting text in the CKEditor editor.
**Important:** Use `onMouseDown` with `preventDefault()` so the browser does not move focus away from the editor before `addComment` reads the current selection. Keep the actual `addComment` call in `onClick`.
> [tab] React / Next.js
>
> ```tsx theme={null}
> import { addComment } from '@veltdev/ckeditor-velt-comments';
>
> const handleAddComment = () => {
> if (!editor) return;
>
> void addComment({
> editor,
> editorId: EDITOR_ID,
> });
> };
>
> onMouseDown={(event) => event.preventDefault()}
> onClick={handleAddComment}
> >
> Add Comment
>
> ```
#### Step 5: Call `addComment` to add a comment
* Call this method to add a comment to selected text in the CKEditor editor.
* Params: [`AddCommentRequest`](/docs/api-reference/sdk/models/data-models#ckeditor-addcommentrequest). It has the following properties:
* `editor`: CKEditor 5 `Editor` instance from `onReady`.
* `editorId`: Id of the editor. Use this if you have multiple CKEditor editors on the same page. (optional)
* `context`: [`CommentAnnotationContext`](/docs/api-reference/sdk/models/data-models#ckeditor-commentannotationcontext) for custom metadata to attach to the Comment Annotation. [Learn more](/docs/async-collaboration/comments/customize-behavior#metadata). (optional)
* Returns: `Promise`.
> [tab] React / Next.js
>
> ```tsx theme={null}
> import { addComment } from '@veltdev/ckeditor-velt-comments';
>
> const addCommentRequest = {
> editor,
> editorId: 'EDITOR_ID',
> context: {
> storyId: 'story-id',
> storyName: 'story-name',
> },
> };
>
> void addComment(addCommentRequest);
> ```
The library automatically writes `context.textEditorConfig` with the selected text, its occurrence index in the document, and the editor ID when one is provided.
#### Step 6: Render comments in CKEditor editor
* Get the comment data from Velt SDK and render it in the CKEditor editor.
* Params: [`RenderCommentsRequest`](/docs/api-reference/sdk/models/data-models#ckeditor-rendercommentsrequest). It has the following properties:
* `editor`: CKEditor 5 `Editor` instance.
* `editorId`: Id of the editor. Use this if you have multiple CKEditor editors on the same page. (optional)
* `commentAnnotations`: Array of [`CommentAnnotation`](/docs/api-reference/sdk/models/data-models#commentannotation) objects.
* Returns: `void`.
> [tab] React / Next.js
>
> ```tsx theme={null}
> import { useEffect } from 'react';
> import { useCommentAnnotations } from '@veltdev/react';
> import { renderComments } from '@veltdev/ckeditor-velt-comments';
>
> const commentAnnotations = useCommentAnnotations();
>
> useEffect(() => {
> if (!editor) return;
>
> renderComments({
> editor,
> editorId: 'EDITOR_ID',
> commentAnnotations: commentAnnotations ?? [],
> });
> }, [editor, commentAnnotations]);
> ```
#### Step 7: Re-apply highlights after reloading content
Comment highlights are view-only overlay elements positioned over the commented text. They are not stored in the CKEditor document, so your saved HTML, schema, and undo history stay clean.
Highlight positions are tracked with CKEditor model ranges and re-positioned as the document changes.
Call `renderComments` whenever the editor is recreated or its content is replaced. The `useEffect` in Step 6 handles this automatically when the `editor` instance or the annotation list changes.
#### Step 8: Style the commented text
* Comment highlights are rendered as `velt-comment-text` overlay markers.
* You can override the marker styles in your app CSS.
```css theme={null}
velt-comment-text {
background-color: rgba(255, 212, 0, 0.4);
border-bottom: 2px solid #ffd400;
cursor: pointer;
}
velt-comment-text:hover,
velt-comment-text[comment-selected="true"],
velt-comment-text.velt-comment-selected {
background-color: rgba(255, 212, 0, 0.7);
}
```
## Complete Example
[https://sample-apps-ckeditor-comments-demo.vercel.app/](https://sample-apps-ckeditor-comments-demo.vercel.app/)
## APIs
#### [VeltCommentsPlugin](/docs/api-reference/sdk/api/api-methods#ckeditor-veltcommentsplugin)
The CKEditor 5 plugin that powers Velt comments. Add it to the `` component's `config.plugins` list and configure it with `config.veltComments`.
* Config: [`VeltCommentsPluginConfig`](/docs/api-reference/sdk/models/data-models#ckeditor-veltcommentspluginconfig)
* Returns: CKEditor plugin class
> [tab] React / Next.js
>
> ```tsx theme={null}
> import { VeltCommentsPlugin } from '@veltdev/ckeditor-velt-comments';
>
> editor={ClassicEditor}
> config={{
> plugins: [Essentials, Paragraph, VeltCommentsPlugin],
> veltComments: { editorId: 'my-editor' },
> }}
> />
> ```
#### [addComment()](/docs/api-reference/sdk/api/api-methods#ckeditor-addcomment)
Creates a comment annotation for the currently selected text in CKEditor.
* Signature: `async (request:` [`AddCommentRequest`](/docs/api-reference/sdk/models/data-models#ckeditor-addcommentrequest)`) => Promise`
* Params: `request:` [`AddCommentRequest`](/docs/api-reference/sdk/models/data-models#ckeditor-addcommentrequest)
* Returns: `Promise`
> [tab] React / Next.js
>
> ```tsx theme={null}
> import { addComment } from '@veltdev/ckeditor-velt-comments';
>
> void addComment({
> editor,
> editorId: 'my-editor',
> });
> ```
#### [renderComments()](/docs/api-reference/sdk/api/api-methods#ckeditor-rendercomments)
Resolves and highlights Velt comment annotations in CKEditor.
* Signature: `(request:` [`RenderCommentsRequest`](/docs/api-reference/sdk/models/data-models#ckeditor-rendercommentsrequest)`) => void`
* Params: `request:` [`RenderCommentsRequest`](/docs/api-reference/sdk/models/data-models#ckeditor-rendercommentsrequest)
* Returns: `void`
> [tab] React / Next.js
>
> ```tsx theme={null}
> import { renderComments } from '@veltdev/ckeditor-velt-comments';
>
> renderComments({
> editor,
> editorId: 'my-editor',
> commentAnnotations: annotations ?? [],
> });
> ```
# CodeMirror Setup
Source: https://velt.dev/docs/async-collaboration/comments/setup/codemirror

## Setup
#### Step 1: Add Comment components
* Add the `Velt Comments` component to the root of your app.
* This component is required to render comments in your app.
* Set the `text mode` prop to `false` to hide the default text comment tool.
> [tab] React / Next.js
>
> ```js theme={null}
>
>
>
> ```
> [tab] Other Frameworks
>
> ```html theme={null}
>
>
>
> ```
#### Step 2: Install the Velt CodeMirror extension
```bash theme={null}
npm i @veltdev/codemirror-velt-comments
```
#### Step 3: Configure the CodeMirror editor with the Velt Comments extension
> [tab] React / Next.js
>
> ```js theme={null}
> import { EditorView, basicSetup } from 'codemirror';
> import { CodemirrorVeltComments } from '@veltdev/codemirror-velt-comments';
>
> const view = new EditorView({
> doc: 'Your initial content here',
> extensions: [
> basicSetup,
> CodemirrorVeltComments(),
> // ... other extensions
> ],
> parent: editorRef.current,
> });
> ```
> [tab] Other Frameworks
>
> ```js theme={null}
> import { EditorView, basicSetup } from 'codemirror';
> import { CodemirrorVeltComments } from '@veltdev/codemirror-velt-comments';
>
> const editorView = new EditorView({
> doc: 'Your initial content here',
> extensions: [
> basicSetup,
> CodemirrorVeltComments(),
> // ... other extensions
> ],
> parent: document.querySelector('#editor'),
> });
> ```
#### Step 4: Add a comment button to your CodeMirror editor
Add a button that users can click to add comments after selecting text.
**Important:** When clicking a button, the browser moves focus to the button which clears the editor selection. You need to save the selection on `mousedown` (before focus changes) and restore it before adding the comment.
> [tab] React / Next.js
>
> ```js theme={null}
> import { useRef, useState, useEffect } from 'react';
> import { EditorView, basicSetup } from 'codemirror';
> import { CodemirrorVeltComments, addComment } from '@veltdev/codemirror-velt-comments';
>
> function CodeMirrorEditor() {
> const editorRef = useRef(null);
> const [editorView, setEditorView] = useState(null);
> const savedSelectionRef = useRef(null);
> const annotations = useCommentAnnotations();
>
> useEffect(() => {
> if (!editorRef.current) return;
>
> const view = new EditorView({
> doc: 'Your initial content here',
> extensions: [
> basicSetup,
> CodemirrorVeltComments(),
> ],
> parent: editorRef.current,
> });
>
> setEditorView(view);
> return () => view.destroy();
> }, []);
>
> const saveSelection = () => {
> if (editorView) {
> const { from, to } = editorView.state.selection.main;
> if (from !== to) {
> savedSelectionRef.current = { from, to };
> }
> }
> };
>
> const handleAddComment = () => {
> if (editorView) {
> if (savedSelectionRef.current) {
> const { from, to } = savedSelectionRef.current;
> if (from !== to) {
> editorView.dispatch({
> selection: { anchor: from, head: to }
> });
> }
> }
> addComment({ editor: editorView });
> savedSelectionRef.current = null;
> }
> };
>
> return (
>
>
onMouseDown={(e) => {
> e.preventDefault();
> saveSelection();
> }}
> onClick={handleAddComment}
> >
> Add Comment
>
>
>
> );
> }
> ```
> [tab] Other Frameworks
>
> ```html theme={null}
>
>
>
> ```
>
> ```js theme={null}
> import { EditorView, basicSetup } from 'codemirror';
> import { CodemirrorVeltComments, addComment } from '@veltdev/codemirror-velt-comments';
>
> const editorView = new EditorView({
> doc: 'Your initial content here',
> extensions: [
> basicSetup,
> CodemirrorVeltComments(),
> ],
> parent: document.querySelector('#editor'),
> });
>
> let savedSelection = null;
>
> const saveSelection = () => {
> if (editorView) {
> const { from, to } = editorView.state.selection.main;
> if (from !== to) {
> savedSelection = { from, to };
> }
> }
> };
>
> const addCommentToEditor = () => {
> if (editorView) {
> if (savedSelection && savedSelection.from !== savedSelection.to) {
> editorView.dispatch({
> selection: { anchor: savedSelection.from, head: savedSelection.to }
> });
> }
> addComment({ editor: editorView });
> savedSelection = null;
> }
> };
>
> const addCommentBtn = document.getElementById('add-comment-btn');
> addCommentBtn.addEventListener('mousedown', (e) => {
> e.preventDefault();
> saveSelection();
> });
> addCommentBtn.addEventListener('click', addCommentToEditor);
> ```
#### Step 5: Call `addComment` to add a comment
* Call this method to add a comment to selected text in the CodeMirror editor. You can use this when the user clicks on the comment button or presses a keyboard shortcut.
* Params: [`AddCommentRequest`](/docs/api-reference/sdk/models/data-models#addcommentrequest-4). It has the following properties:
* `editor`: instance of the CodeMirror EditorView.
* `editorId`: Id of the CodeMirror editor. Use this if you have multiple CodeMirror editors on the same page in your app. (optional)
* `context`: Add any custom metadata to the Comment Annotation. [Learn more](/docs/async-collaboration/comments/customize-behavior#metadata). (optional)
> [tab] React / Next.js
>
> ```js theme={null}
> import { addComment } from '@veltdev/codemirror-velt-comments';
>
> const addCommentRequest = {
> editor: editorView,
> editorId: 'EDITOR_ID',
> context: {
> storyId: 'story-id',
> storyName: 'story-name',
> },
> };
>
> addComment(addCommentRequest);
> ```
> [tab] Other Frameworks
>
> ```js theme={null}
> import { addComment } from '@veltdev/codemirror-velt-comments';
>
> const addCommentRequest = {
> editor: editorView,
> editorId: 'EDITOR_ID',
> context: {
> storyId: 'story-id',
> storyName: 'story-name',
> },
> };
>
> addComment(addCommentRequest);
> ```
#### Step 6: Render comments in CodeMirror editor
* Get the comment data from Velt SDK and render it in the CodeMirror editor.
* Params: [`RenderCommentsRequest`](/docs/api-reference/sdk/models/data-models#rendercommentsrequest-4). It has the following properties:
* `editor`: Instance of the CodeMirror EditorView.
* `editorId`: Id of the CodeMirror editor. Use this if you have multiple CodeMirror editors on the same page in your app. (optional)
* `commentAnnotations`: Array of Comment Annotation objects.
> [tab] React / Next.js
>
> ```js theme={null}
> import { renderComments } from '@veltdev/codemirror-velt-comments';
> import { useCommentAnnotations } from '@veltdev/react';
>
> const annotations = useCommentAnnotations();
>
> useEffect(() => {
> if (editorView && annotations?.length) {
> const renderCommentsRequest = {
> editor: editorView,
> editorId: 'EDITOR_ID',
> commentAnnotations: annotations,
> };
> renderComments(renderCommentsRequest);
> }
> }, [editorView, annotations]);
> ```
> [tab] Other Frameworks
>
> ```js theme={null}
> import { renderComments } from '@veltdev/codemirror-velt-comments';
>
> const commentElement = Velt.getCommentElement();
> commentElement.getAllCommentAnnotations().subscribe((annotations) => {
> if (editorView && annotations?.length) {
> const renderCommentsRequest = {
> editor: editorView,
> editorId: 'EDITOR_ID',
> commentAnnotations: annotations,
> };
> renderComments(renderCommentsRequest);
> }
> });
> ```
#### Step 7: Persist Velt Comment Marks (optional)
* By default, Velt comment marks (``) are persisted in the CodeMirror editor by Velt SDK. When the editor loads and the Velt SDK initializes, the marks will be automatically added to the editor.
* If you plan to store the contents of the CodeMirror editor on your end with the comment marks already included, you can disable this feature.
* Default: `true`
```js theme={null}
const editorView = new EditorView({
extensions: [
CodemirrorVeltComments({
persistVeltMarks: false,
}),
// ... other extensions
],
parent: editorRef.current,
});
```
#### Step 8: Style the commented text
* You can style the commented text by adding CSS for the `velt-comment-text` element.
```css theme={null}
velt-comment-text {
background-color: rgba(255, 255, 0, 0.3);
border-bottom: 2px solid #ffcc00;
cursor: pointer;
}
velt-comment-text:hover {
background-color: rgba(255, 255, 0, 0.5);
}
velt-comment-text.velt-comment-selected {
background-color: rgba(255, 255, 0, 0.5);
}
```
## APIs
#### [CodemirrorVeltComments()](/docs/api-reference/sdk/api/api-methods#codemirrorveltcomments)
Creates the Velt Comments extension for CodeMirror.
* Params: `config?:` [CodemirrorVeltCommentsConfig](/docs/api-reference/sdk/models/data-models#codemirrorveltcommentsconfig)
* `editorId?: string` - Unique identifier for this editor instance (for multi-editor scenarios)
* `persistVeltMarks?: boolean` - Whether to persist Velt marks. Default: `true`
* Returns: CodeMirror `Extension`
> [tab] React / Next.js
>
> ```tsx theme={null}
> import { EditorView } from 'codemirror';
> import { CodemirrorVeltComments } from '@veltdev/codemirror-velt-comments';
>
> const view = new EditorView({
> extensions: [
> CodemirrorVeltComments({
> editorId: 'my-editor',
> persistVeltMarks: true,
> }),
> ],
> parent: editorRef.current,
> });
> ```
> [tab] Other Frameworks
>
> ```tsx theme={null}
> import { EditorView } from 'codemirror';
> import { CodemirrorVeltComments } from '@veltdev/codemirror-velt-comments';
>
> const editorView = new EditorView({
> extensions: [
> CodemirrorVeltComments({
> editorId: 'my-editor',
> persistVeltMarks: true,
> }),
> ],
> parent: document.body,
> });
> ```
#### [addComment()](/docs/api-reference/sdk/api/api-methods#addcomment-4)
Creates a comment annotation for the currently selected text in the editor.
* Params:
* `request:` [AddCommentRequest](/docs/api-reference/sdk/models/data-models#addcommentrequest-4)
* `editor: EditorView`
* `editorId?: string`
* `context?: object`
* Returns: `Promise`
> [tab] React / Next.js
>
> ```tsx theme={null}
> import { addComment } from '@veltdev/codemirror-velt-comments';
>
> onMouseDown={(e) => {
> e.preventDefault();
> addComment({
> editor: editorView,
> editorId: 'my-editor',
> context: { customData: 'value' }
> });
> }}
> >
> Comment
>
> ```
> [tab] Other Frameworks
>
> ```tsx theme={null}
> import { addComment } from '@veltdev/codemirror-velt-comments';
>
> addComment({
> editor: editorView,
> editorId: 'my-editor',
> context: { customData: 'value' },
> });
> ```
#### [renderComments()](/docs/api-reference/sdk/api/api-methods#rendercomments-4)
Renders and highlights comment annotations in the editor.
* Params:
* `request:` [RenderCommentsRequest](/docs/api-reference/sdk/models/data-models#rendercommentsrequest-4)
* `editor: EditorView`
* `editorId?: string`
* `commentAnnotations?:` [CommentAnnotation\[\]](/docs/api-reference/sdk/models/data-models#commentannotation)
* Returns: `void`
> [tab] React / Next.js
>
> ```tsx theme={null}
> import { useEffect } from 'react';
> import { renderComments } from '@veltdev/codemirror-velt-comments';
> import { useCommentAnnotations } from '@veltdev/react';
>
> const annotations = useCommentAnnotations();
>
> useEffect(() => {
> if (editorView && annotations) {
> renderComments({
> editor: editorView,
> editorId: 'my-editor',
> commentAnnotations: annotations,
> });
> }
> }, [editorView, annotations]);
> ```
> [tab] Other Frameworks
>
> ```tsx theme={null}
> import { renderComments } from '@veltdev/codemirror-velt-comments';
>
> const commentElement = Velt.getCommentElement();
> commentElement.getAllCommentAnnotations().subscribe((annotations) => {
> if (editorView && annotations) {
> renderComments({
> editor: editorView,
> editorId: 'my-editor',
> commentAnnotations: annotations,
> });
> }
> });
> ```
# DraftJS Setup
Source: https://velt.dev/docs/async-collaboration/comments/setup/draftjs

## Setup
#### Step 1: Add Comment components
* Add the `Velt Comments` component to the root of your app.
* This component is required to render comments in your app.
* Set the `text mode` prop to `false` to hide the default text comment tool.
> [tab] React / Next.js
>
> ```js theme={null}
>
>
>
> ```
#### Step 2: Install the Velt DraftJS extension
```bash theme={null}
npm i @veltdev/draftjs-velt-comments draft-js
```
#### Step 3: Configure the DraftJS editor with the Velt Comments extension
Use `DraftJSVeltEditor` instead of the standard DraftJS `Editor`. This wrapper component handles the DraftJS decorator setup, content change detection, and annotation tracking.
> [tab] React / Next.js
>
> ```js theme={null}
> import { useState } from 'react';
> import { EditorState } from 'draft-js';
> import { DraftJSVeltEditor } from '@veltdev/draftjs-velt-comments';
>
> function DraftJSEditor() {
> const [editorState, setEditorState] = useState(() =>
> EditorState.createEmpty()
> );
>
> return (
> editorState={editorState}
> onChange={setEditorState}
> placeholder="Start typing..."
> />
> );
> }
> ```
#### Step 4: Add a comment button to your DraftJS editor
* Add a button that users can click after selecting text in the DraftJS editor.
* Use `onMouseDown` with `preventDefault()` so the browser does not move focus away from the editor and clear the current text selection.
> [tab] React / Next.js
>
> ```js theme={null}
> import { useCallback, useEffect, useRef, useState } from 'react';
> import { EditorState } from 'draft-js';
> import {
> DraftJSVeltEditor,
> addComment,
> } from '@veltdev/draftjs-velt-comments';
>
> function DraftJSEditor() {
> const [editorState, setEditorState] = useState(() =>
> EditorState.createEmpty()
> );
>
> const editorRef = useRef({ editorState, setEditorState });
>
> useEffect(() => {
> editorRef.current = { editorState, setEditorState };
> }, [editorState]);
>
> const handleAddComment = useCallback(() => {
> addComment({ editor: editorRef.current });
> }, []);
>
> return (
>
> onMouseDown={(event) => event.preventDefault()}
> onClick={handleAddComment}
> >
> Add Comment
>
>
> editorState={editorState}
> onChange={setEditorState}
> placeholder="Start typing..."
> />
>
> );
> }
> ```
#### Step 5: Call `addComment` to add a comment
* Call this method to add a comment to selected text in the DraftJS editor.
* Params: [`AddCommentRequest`](/docs/api-reference/sdk/models/data-models#addcommentrequest-7)
* `editor`: DraftJS editor wrapper object with `{ editorState, setEditorState }`.
* `editorId`: Id of the editor. Use this if you have multiple DraftJS editors on the same page. (optional)
* `context`: Add custom metadata to the Comment Annotation. [Learn more](/docs/async-collaboration/comments/customize-behavior#metadata). (optional)
> [tab] React / Next.js
>
> ```js theme={null}
> import { addComment } from '@veltdev/draftjs-velt-comments';
>
> const addCommentRequest = {
> editor,
> editorId: 'EDITOR_ID',
> context: {
> storyId: 'story-id',
> storyName: 'story-name',
> },
> };
>
> addComment(addCommentRequest);
> ```
#### Step 6: Render comments in DraftJS editor
* Get comment data from Velt SDK and render it in the DraftJS editor.
* Params: [`RenderCommentsRequest`](/docs/api-reference/sdk/models/data-models#rendercommentsrequest-7)
* `editor`: DraftJS editor wrapper object with `{ editorState, setEditorState }`.
* `editorId`: Id of the editor. Use this if you have multiple DraftJS editors on the same page. (optional)
* `commentAnnotations`: Array of Comment Annotation objects.
> [tab] React / Next.js
>
> ```js theme={null}
> import { useEffect, useRef, useState } from 'react';
> import { EditorState } from 'draft-js';
> import { useCommentAnnotations } from '@veltdev/react';
> import {
> DraftJSVeltEditor,
> renderComments,
> } from '@veltdev/draftjs-velt-comments';
>
> function DraftJSEditor() {
> const annotations = useCommentAnnotations();
> const [editorState, setEditorState] = useState(() =>
> EditorState.createEmpty()
> );
>
> const editorRef = useRef({ editorState, setEditorState });
>
> useEffect(() => {
> editorRef.current = { editorState, setEditorState };
> }, [editorState]);
>
> useEffect(() => {
> renderComments({
> editor: editorRef.current,
> editorId: 'EDITOR_ID',
> commentAnnotations: annotations ?? [],
> });
> }, [annotations]);
>
> return (
> editorState={editorState}
> onChange={setEditorState}
> />
> );
> }
> ```
#### Step 7: Persist DraftJS content without Velt comment entities (optional)
* When saving editor content to your backend, remove Velt comment entities to keep your stored content clean.
* Use `exportContentStateWithoutComments` before converting DraftJS content to raw JSON.
```js theme={null}
import { convertToRaw } from 'draft-js';
import { exportContentStateWithoutComments } from '@veltdev/draftjs-velt-comments';
const cleanContent = exportContentStateWithoutComments(
editorState.getCurrentContent()
);
const rawContent = convertToRaw(cleanContent);
```
#### Step 8: Style the commented text
* Style the commented text by adding CSS for the `velt-comment-text` element.
```css theme={null}
velt-comment-text {
background-color: rgba(255, 255, 0, 0.3);
border-bottom: 2px solid #ffcc00;
cursor: pointer;
}
velt-comment-text:hover {
background-color: rgba(255, 255, 0, 0.5);
}
velt-comment-text.velt-comment-selected {
background-color: rgba(255, 255, 0, 0.5);
}
```
## Complete Example
[https://sample-apps-draftjs-comments-demo.vercel.app/](https://sample-apps-draftjs-comments-demo.vercel.app/)
## APIs
#### [DraftJSVeltEditor](/docs/api-reference/sdk/api/api-methods#draftjsvelteditor)
A wrapper around the DraftJS `Editor` component that automatically handles decorator setup, content change detection, and Velt annotation context updates.
* Props: [`DraftJSVeltEditorProps`](/docs/api-reference/sdk/models/data-models#draftjsvelteditorprops)
* `editorState`: Current DraftJS editor state.
* `onChange`: Callback when the editor state changes.
* `editorId`: Optional editor ID for multi-editor scenarios.
* All other standard DraftJS `Editor` props are forwarded.
> [tab] React / Next.js
>
> ```jsx theme={null}
> import { DraftJSVeltEditor } from '@veltdev/draftjs-velt-comments';
>
> editorState={editorState}
> onChange={setEditorState}
> editorId="my-editor"
> placeholder="Start typing..."
> />
> ```
#### [addComment()](/docs/api-reference/sdk/api/api-methods#addcomment-8)
Creates a comment annotation for the currently selected text in the editor.
* Signature: `async (request:` [AddCommentRequest](/docs/api-reference/sdk/models/data-models#addcommentrequest-7)`) => Promise`
* Params: `request:` [AddCommentRequest](/docs/api-reference/sdk/models/data-models#addcommentrequest-7)
* Returns: `Promise`
> [tab] React / Next.js
>
> ```jsx theme={null}
> import { addComment } from '@veltdev/draftjs-velt-comments';
>
> const handleAddComment = () => {
> addComment({ editor, editorId: 'my-editor' });
> };
>
> onMouseDown={(event) => event.preventDefault()}
> onClick={handleAddComment}
> >
> Comment
>
> ```
#### [renderComments()](/docs/api-reference/sdk/api/api-methods#rendercomments-8)
Renders and highlights comment annotations in the DraftJS editor.
* Signature: `(request:` [RenderCommentsRequest](/docs/api-reference/sdk/models/data-models#rendercommentsrequest-7)`) => void`
* Params: `request:` [RenderCommentsRequest](/docs/api-reference/sdk/models/data-models#rendercommentsrequest-7)
* Returns: `void`
> [tab] React / Next.js
>
> ```jsx theme={null}
> import { renderComments } from '@veltdev/draftjs-velt-comments';
>
> useEffect(() => {
> renderComments({
> editor: editorRef.current,
> editorId: 'my-editor',
> commentAnnotations,
> });
> }, [commentAnnotations]);
> ```
#### [exportContentStateWithoutComments()](/docs/api-reference/sdk/api/api-methods#exportcontentstatewithoutcomments)
Returns a DraftJS `ContentState` without Velt comment entities. Use it before saving content outside Velt.
> [tab] React / Next.js
>
> ```jsx theme={null}
> import { convertToRaw } from 'draft-js';
> import { exportContentStateWithoutComments } from '@veltdev/draftjs-velt-comments';
>
> const cleanContent = exportContentStateWithoutComments(
> editorState.getCurrentContent()
> );
> const rawContent = convertToRaw(cleanContent);
> ```
# Freestyle Setup
Source: https://velt.dev/docs/async-collaboration/comments/setup/freestyle

> [tab] React / Next.js
>
> ## 1. Import Comment components
>
> Import the `VeltComments` component and the `VeltCommentTool` component.
>
> ```js theme={null}
> import {
> VeltProvider,
> VeltComments,
> VeltCommentTool
> } from '@veltdev/react';
> ```
>
> ## 2. Add Comments component
>
> Add the `VeltComments` component to the root of your app.
>
> This component is required to render comments in your app.
>
> ```js theme={null}
>
>
>
> ```
>
> ## 3. Add Comment Tool component
>
> Add the `VeltCommentTool` component wherever you want to show the comment tool button.
>
> 
>
> Clicking on it initiates comment mode & changes your mouse cursor to a comment pin. Now you can click anywhere on the document to attach comments to any elements.
>
> ```js theme={null}
>
>
>
> ```
>
> ## 4. Test Integration
>
> Test it out by opening the page with Velt components in your browser.
>
> Click on the `Comment Tool` and click anywhere on the page to add a comment.
>
> 
> [tab] Other Frameworks
>
> ## 1. Add Comment component
>
> Add the comment component to your template. Try to put it as close to the root level of your ``.
>
> This component is required to render comments in your app.
>
> ```html theme={null}
>
>
>
> ```
>
> ## 2. Add Comment Tool component
>
> Add the `` component wherever you want to show the comment tool button.
>
> 
>
> Clicking on it initiates comment mode & changes your mouse cursor to a comment pin. Now you can click anywhere on the document to attach comments to any elements.
>
> ```js theme={null}
>
>
>
> ```
>
> ## 3. Test Integration
>
> Test it out by adding a comment.
>
> You should be able to leave comments using the `Comment Tool`.
>
> 
```jsx React / Next.js theme={null}
import {
VeltProvider,
VeltComments,
VeltCommentTool
} from '@veltdev/react';
export default function App() {
return (
);
}
```
```html HTML theme={null}
Comment documentation
```
# Inline Comments Setup
Source: https://velt.dev/docs/async-collaboration/comments/setup/inline-comments

> [tab] React / Next.js
>
> ## 1. Import Comment components
>
> Import the `VeltProvider`, `VeltComments`, and `VeltInlineCommentsSection` component.
>
> ```js theme={null}
> import { VeltProvider, VeltComments, VeltInlineCommentsSection } from '@veltdev/react';
> ```
>
> ## 2. Add VeltComments component
>
> * Add the `VeltComments` component to the root of your app where your `VeltProvider` is.
> * This component is required to render comments in your app.
>
> ```js theme={null}
>
>
>
> ```
>
> ## 3. Add container to hold Inline Comments component
>
> * Create an element to hold your Inline Comments component, such as a `div` or `section`.
> * Add a unique element `id` to it.
>
> ```jsx theme={null}
>
> ```
>
> ## 4. Add VeltInlineCommentsSection component
>
> * Add `VeltInlineCommentsSection` component inside your container.
> * Add `targetElementId` property to the Velt Inline Comments component. This needs to match the id you set to the container. This binds the Inline Comments component with the desired container.
>
> ```jsx theme={null}
> targetElementId="container-id"
> />
> ```
>
> ## 5. (Optional) Make it single threaded or multithreaded
>
> * Default: `true`
> * By default inline comment section is multithreaded.
> * You can make it single threaded by setting `multiThread` attribute to `false`.
>
> ```jsx theme={null}
>
> ```
>
> ## 6. (Optional) Customize placeholder text
>
> Customize the placeholder text for comment, reply, and composer input fields.
>
> ```jsx theme={null}
> commentPlaceholder="Add a comment..."
> replyPlaceholder="Write a reply..."
> composerPlaceholder="Start typing..."
> />
> ```
>
> To customize placeholder text shown when **editing** an existing comment or reply, use `editPlaceholder`, `editCommentPlaceholder`, and `editReplyPlaceholder`. See [`VeltInlineCommentsSectionProps`](/docs/api-reference/sdk/models/data-models#veltinlinecommentssectionprops) for details.
>
> ## 7. (Optional) Enable message truncation
>
> * Default: `false`
> * Truncate long messages in the list, showing a **Show more** toggle after the specified number of lines.
> * Use `messageTruncationLines` to control the cutoff (default: `4`).
>
> ```jsx theme={null}
> targetElementId="article0"
> messageTruncation={true}
> messageTruncationLines={3}
> />
> ```
> [tab] Other Frameworks
>
> ## 1. Add velt-comments component
>
> * Add the Velt Comments component to the root of your app.
> * This component is required to render comments in your app.
>
> ```html theme={null}
>
>
>
> ```
>
> ## 2. Add container to hold Inline Comments component
>
> * Create an element to hold your Inline Comments component, such as a `div` or `section`.
> * Add a unique element `id` to it.
>
> ```html theme={null}
>
> ```
>
> ## 3. Add velt-inline-comments-section component
>
> * Add `velt-inline-comments-section` component inside your container.
> * Add `target-element-id` property to the Velt Inline Comments component. This needs to match the id you set to the container. This binds the Inline Comments component with the desired container.
>
> ```jsx theme={null}
> target-element-id="container-id"
> shadow-dom="false"
> dialog-variant="dialog-variant"
> variant="inline-section-variant"
> dark-mode="true"
> >
>
> ```
>
> ## 4. (Optional) Make it single threaded or multithreaded
>
> * Default: `true`
> * By default inline comments are multithreaded.
> * You can make it single threaded by setting `multi-thread` attribute to `false`.
>
> ```html theme={null}
>
>
> ```
>
> ## 5. (Optional) Customize placeholder text
>
> Customize the placeholder text for comment, reply, and composer input fields.
>
> ```html theme={null}
> comment-placeholder="Add a comment..."
> reply-placeholder="Write a reply..."
> composer-placeholder="Start typing..."
> >
>
> ```
>
> To customize placeholder text shown when **editing** an existing comment or reply, use `edit-placeholder`, `edit-comment-placeholder`, and `edit-reply-placeholder`. See [`VeltInlineCommentsSectionProps`](/docs/api-reference/sdk/models/data-models#veltinlinecommentssectionprops) for details.
>
> ## 6. (Optional) Enable message truncation
>
> * Default: `false`
> * Truncate long messages in the list, showing a **Show more** toggle after the specified number of lines.
> * Use `message-truncation-lines` to control the cutoff (default: `4`).
>
> ```html theme={null}
> target-element-id="article0"
> message-truncation="true"
> message-truncation-lines="3">
>
> ```
```jsx React / Next.js theme={null}
import { VeltProvider, VeltComments } from '@veltdev/react';
export default function App() {
return (
);
}
```
```html HTML theme={null}
Comment documentation
```
# Lexical Setup
Source: https://velt.dev/docs/async-collaboration/comments/setup/lexical

## Setup
#### Step 1: Add Comment components
* Add the `Velt Comments` component to the root of your app.
* This component is required to render comments in your app.
* Set the `text mode` prop to `false` to hide the default text comment tool.
> [tab] React / Next.js
>
> ```js theme={null}
>
>
>
> ```
> [tab] Other Frameworks
>
> ```html theme={null}
>
>
>
> ```
#### Step 2: Install the Velt Lexical extension
```bash theme={null}
npm install @veltdev/lexical-velt-comments @veltdev/client lexical
```
#### Step 3: Configure the Lexical editor with the Velt Comments extension
* Register the `CommentNode` and configure your Lexical editor.
> [tab] React / Next.js
>
> ```js theme={null}
> import { LexicalComposer } from '@lexical/react/LexicalComposer';
> import { CommentNode } from '@veltdev/lexical-velt-comments';
>
> const initialConfig = {
> namespace: 'MyEditor',
> nodes: [CommentNode],
> onError: (error) => console.error(error),
> };
>
> function App() {
> return (
>
> {/* Editor plugins */}
>
> );
> }
> ```
> [tab] Other Frameworks
>
> ```js theme={null}
> import { createEditor } from 'lexical';
> import { registerRichText } from '@lexical/rich-text';
> import { CommentNode, addComment, renderComments } from '@veltdev/lexical-velt-comments';
>
> const editor = createEditor({
> namespace: 'MyEditor',
> nodes: [CommentNode],
> onError: (error) => {
> throw error;
> },
> });
>
> // Set the root element
> editor.setRootElement(document.querySelector('#editor'));
>
> // Register rich text support
> registerRichText(editor);
> ```
#### Step 4: Add a comment button
* Add a button that users can click to add comments after selecting text.
> [tab] React / Next.js
>
> ```js theme={null}
> import { useCallback } from 'react';
> import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext';
> import { addComment } from '@veltdev/lexical-velt-comments';
>
> function AddCommentPlugin() {
> const [editor] = useLexicalComposerContext();
>
> const handleAddComment = useCallback(() => {
> addComment({ editor });
> }, [editor]);
>
> return (
>
> Add Comment
>
> );
> }
> ```
> [tab] Other Frameworks
>
> ```html theme={null}
>
>
> ```
>
> ```js theme={null}
> import { addComment } from '@veltdev/lexical-velt-comments';
>
> const addCommentBtn = document.getElementById('add-comment-btn');
> addCommentBtn.addEventListener('click', () => {
> addComment({ editor });
> });
> ```
#### Step 5: Call `addComment` to add a comment
* Call this method to add a comment to selected text in the Lexical editor. You can use this when the user clicks on a comment button or presses a keyboard shortcut.
* Params: [`AddCommentRequest`](/docs/api-reference/sdk/models/data-models#addcommentrequest-3). It has the following properties:
* `editor`: Instance of the Lexical Editor.
* `editorId`: Id of the editor. Use this if you have multiple Lexical editors on the same page. (optional)
* `context`: Add any custom metadata to the Comment Annotation. [Learn more](/docs/async-collaboration/comments/customize-behavior#metadata). (optional)
> [tab] React / Next.js
>
> ```js theme={null}
> import { addComment } from '@veltdev/lexical-velt-comments';
>
> const addCommentRequest = {
> editor,
> editorId: 'EDITOR_ID',
> context: {
> storyId: 'story-id',
> storyName: 'story-name',
> },
> };
>
> addComment(addCommentRequest);
> ```
> [tab] Other Frameworks
>
> ```js theme={null}
> import { addComment } from '@veltdev/lexical-velt-comments';
>
> const addCommentRequest = {
> editor,
> editorId: 'EDITOR_ID',
> context: {
> storyId: 'story-id',
> storyName: 'story-name',
> },
> };
>
> addComment(addCommentRequest);
> ```
#### Step 6: Render comments in Lexical editor
* Get the comment data from Velt SDK and render it in the Lexical Editor.
* Params: [`RenderCommentsRequest`](/docs/api-reference/sdk/models/data-models#rendercommentsrequest-3). It has the following properties:
* `editor`: Instance of the Lexical Editor.
* `editorId`: Id of the editor. Use this if you have multiple Lexical editors on the same page. (optional)
* `commentAnnotations`: Array of Comment Annotation objects.
> [tab] React / Next.js
>
> ```js theme={null}
> import { renderComments } from '@veltdev/lexical-velt-comments';
> import { useCommentAnnotations } from '@veltdev/react';
>
> const annotations = useCommentAnnotations();
>
> useEffect(() => {
> if (editor && annotations) {
> renderComments({
> editor,
> editorId: 'EDITOR_ID',
> commentAnnotations: annotations,
> });
> }
> }, [editor, annotations]);
> ```
> [tab] Other Frameworks
>
> ```js theme={null}
> import { renderComments } from '@veltdev/lexical-velt-comments';
>
> const commentElement = Velt.getCommentElement();
> commentElement.getAllCommentAnnotations().subscribe((annotations) => {
> if (editor && annotations?.length) {
> const renderCommentsRequest = {
> editor,
> editorId: 'EDITOR_ID',
> commentAnnotations: annotations,
> };
> renderComments(renderCommentsRequest);
> }
> });
> ```
#### Step 7: Persist editor content without Velt marks (optional)
* When saving editor content to your backend, you may want to exclude Velt comment marks to keep the content clean.
* Use `exportJSONWithoutComments` to export the editor state as JSON without Velt comment nodes.
```js theme={null}
import { exportJSONWithoutComments } from '@veltdev/lexical-velt-comments';
// Get clean editor state JSON without Velt comment marks
const cleanState = exportJSONWithoutComments(editor);
// Save to your backend
localStorage.setItem('editor-content', JSON.stringify(cleanState));
```
#### Step 8: Style the commented text
* Style the commented text by adding CSS for the `velt-comment-text` element.
```css theme={null}
velt-comment-text {
background-color: rgba(255, 255, 0, 0.3);
border-bottom: 2px solid #ffcc00;
cursor: pointer;
}
velt-comment-text:hover {
background-color: rgba(255, 255, 0, 0.5);
}
velt-comment-text.velt-comment-selected {
background-color: rgba(255, 255, 0, 0.5);
}
```
## Complete Example
[https://sample-apps-lexical-comments-demo.vercel.app/](https://sample-apps-lexical-comments-demo.vercel.app/)
## APIs
#### [CommentNode](/docs/api-reference/sdk/models/data-models#commentnode)
A custom Lexical node used to wrap commented text with comment annotation metadata.
* Usage: Register the node with your Lexical editor so comment elements render correctly.
> [tab] React / Next.js
>
> ```tsx theme={null}
> import { LexicalComposer } from '@lexical/react/LexicalComposer';
> import { CommentNode } from '@veltdev/lexical-velt-comments';
>
> const initialConfig = {
> namespace: 'MyEditor',
> nodes: [CommentNode],
> onError: console.error,
> };
>
> export default function Editor() {
> return {/* plugins */} ;
> }
> ```
> [tab] Other Frameworks
>
> ```tsx theme={null}
> import { createEditor } from 'lexical';
> import { CommentNode } from '@veltdev/lexical-velt-comments';
>
> const editor = createEditor({
> namespace: 'MyEditor',
> nodes: [CommentNode],
> onError: (error) => {
> throw error;
> },
> });
> ```
#### [addComment()](/docs/api-reference/sdk/api/api-methods#addcomment)
Creates a comment annotation for the currently selected text in the editor.
* Params:
* `request:` [`AddCommentRequest`](/docs/api-reference/sdk/models/data-models#addcommentrequest-3)
* `editor: LexicalEditor`
* `editorId?: string`
* `context?: object`
* Returns: `Promise`
> [tab] React / Next.js
>
> ```tsx theme={null}
> import { addComment } from '@veltdev/lexical-velt-comments';
>
> addComment({ editor, editorId: 'my-editor' })}>
> Comment
>
> ```
> [tab] Other Frameworks
>
> ```tsx theme={null}
> import { addComment } from '@veltdev/lexical-velt-comments';
>
> addComment({
> editor,
> editorId: 'my-editor',
> context: { customData: 'value' },
> });
> ```
#### [renderComments()](/docs/api-reference/sdk/api/api-methods#rendercomments)
Renders and highlights comment annotations in the editor.
* Params:
* `request:` [`RenderCommentsRequest`](/docs/api-reference/sdk/models/data-models#rendercommentsrequest-3)
* `editor: LexicalEditor`
* `editorId?: string`
* `commentAnnotations?:` [`CommentAnnotation[]`](/docs/api-reference/sdk/models/data-models#commentannotation)
* Returns: `void`
> [tab] React / Next.js
>
> ```tsx theme={null}
> import { useEffect } from 'react';
> import { renderComments } from '@veltdev/lexical-velt-comments';
> import { useCommentAnnotations } from '@veltdev/react';
>
> const annotations = useCommentAnnotations();
>
> useEffect(() => {
> if (editor && annotations) {
> renderComments({
> editor,
> editorId: 'my-editor',
> commentAnnotations: annotations,
> });
> }
> }, [editor, annotations]);
> ```
> [tab] Other Frameworks
>
> ```tsx theme={null}
> import { renderComments } from '@veltdev/lexical-velt-comments';
>
> const commentElement = Velt.getCommentElement();
> commentElement.getAllCommentAnnotations().subscribe((annotations) => {
> if (editor && annotations) {
> renderComments({
> editor,
> editorId: 'my-editor',
> commentAnnotations: annotations,
> });
> }
> });
> ```
#### [exportJSONWithoutComments()](/docs/api-reference/sdk/api/api-methods#exportjsonwithoutcomments)
Exports the editor state as serialized JSON while stripping out all comment nodes and normalizing adjacent text nodes.
* Params: `editor:` `LexicalEditor`
* Returns: `SerializedEditorState`
```tsx theme={null}
import { exportJSONWithoutComments } from '@veltdev/lexical-velt-comments';
const cleanState = exportJSONWithoutComments(editor);
```
# Lottie Player Setup
Source: https://velt.dev/docs/async-collaboration/comments/setup/lottie-player-setup

> [tab] React / Next.js
>
> > [!WARNING]
> >
> > Make sure you turn React strict mode off.
>
> **1. Add Velt Components in your app**
>
> ### a. Add the `VeltComments` component in the root of your app
>
> Add the `VeltComments` component to enable the Comment feature in your app.
>
> Enable the follow attributes to be `true`:
>
> * `priority`: allows user to P0, P1, or P2 as priority. You can customize this list.
> * `autoCategorize`: allows AI to categorize comment as Question, Feedback, Bug, Other. You can customize this list.
> * `commentIndex`: shows a small icon showing index of the comment in order of creation.
>
> ```jsx theme={null}
>
> ```
>
> ### b. Add the `VeltCommentTool` component wherever you want your render the comment tool.
>
> Note you can also provide your own button to this component.
>
> ```jsx theme={null}
>
>
> {/* your custom button (optional) */}
>
>
> ```
>
> ### c. Place the `VeltCommentPlayerTimeline` component as a sibling to your video player.
>
> To show comment bubbles on your player seek bar, add the `` component as a sibling to your video player component.
>
> It will auto adjust to the same width as your video player.
>
> ```jsx theme={null}
>
>
>
>
> ```
>
> > [!NOTE]
> >
> > Right now we assume you have a maximum of one `` component and one sibling video player component per `documentID`
>
> > [!WARNING]
> >
> > Ensure that the parent container of `` doesn't have CSS position value as 'static'.
>
> ### d. Add the `` component.
>
> (Optional) To embed the sidebar in your existing component, set `embedMode` prop as `true`.
>
> ```jsx theme={null}
>
> ```
>
> ### e. Add the `` component.
>
> This will open or close the Comment Sidebar.
> Note you can also provide your own button to this component.
>
> ```jsx theme={null}
>
>
> {/* your custom button (optional) */}
>
>
> ```
>
> **2. Set the `totalMediaLength` on the `VeltCommentPlayerTimeline`**
>
> You can pass an integer to `totalMediaLength` using props to represent the total number of frames or seconds in the video:
>
> ```jsx theme={null}
>
> ```
>
> Alternatively, you can set this using API method call. This is useful if you first need to grab the total frames from another method before setting it.
>
> ```jsx theme={null}
> const commentElement = client.getCommentElement();
> commentElement.setTotalMediaLength(120);
> ```
>
> **3. Subscribe to when the Comment Tool is activated by the User.**
>
> Add an event handler on where you originally placed `` to handle `onCommentModeChange` events.
>
> Use this whenever the user clicks on the comment tool, to pause your player and set a new `Location` in the Velt SDK.
>
> Setting a `Location` in the Velt SDK ensures that the comments are tied to that particular media frame or timestamp.
>
> ```jsx theme={null}
>
> onCommentModeChange(mode)} />
>
> const onCommentModeChange = (mode) => {
> // mode will be `true` if the user has activated the comment tool
> // If the comment tool is active, pause the player and set the "location".
> if (mode) {
> // pause player
> // See step 8 below for details
> setLocation()
> }
> });
>
> ```
>
> **4. Set Velt Location**
>
> You can pass in a key value pair object that represents the current state of your player. If you are using the `VeltCommentPlayerTimeline` component, ensure to set the current rounded frame or second in the special key `currentMediaPosition`.
>
> > [!NOTE]
> >
> > `currentMediaPosition` is a protected keyword that is used to arrange the comment bubbles on top of the video player timeline in the correct spot
>
> ```jsx theme={null}
> const setLocation = (client) => {
>
> // set currentMediaPosition property on a Location object to represent the current frame
> let location = {
> currentMediaPosition : 120
> }
> //set the Location using the client
> client.setLocation(location)
>
> }
> ```
>
> **5. When the player is played, remove Velt `Location` to remove comments from the media.**
>
> Call `removeLocation()` when your player starts playing:
>
> ```jsx theme={null}
> const removeLocation = () => {
> //remove the location, so the video player can play without comments appearing in frames
> client.removeLocation()
> }
> ```
>
> **6. Set your player's state when the user clicks on the comment.**
>
> Add the `onCommentClick` event handler on the `VeltCommentsSidebar` & `VeltCommentPlayerTimeline` components you added earlier.
> The event will give you back the `location` object that you had set earlier.
>
> You can use this object to update your player state and also update the SDK's `location` so that we can start rendering the comments associated with that `location`.
>
> ### a. Handle it on the `VeltCommentsSidebar`:
>
> ```jsx theme={null}
> onCommentClick(event)} />
>
> const onCommentClick = (event) => {
> if (event) {
> // Get the location object from the event.
> const { location } = event;
> if (location) {
> // Get the media position where the comment was added.
> const { currentMediaPosition } = location;
> if (currentMediaPosition) {
> // Pause the player.
>
> // Seek to the given comment media position.
>
> // Set the Velt Location to the clicked comment location.
> client.setLocation(location);
> }
> }
> }
> }
> ```
>
> ### b. Handle it on the `VeltCommentPlayerTimeline`:
>
> ```jsx theme={null}
> onTimelineCommentClick(event)} />
>
> const onTimelineCommentClick = (event) => {
> if (event) {
> // Get the location object from the event.
> const { location } = event;
> if (location) {
> // Get the media position where the comment was added.
> const { currentMediaPosition } = location;
> if (currentMediaPosition) {
> // Pause the player.
>
> // Seek to the given comment media position.
>
> // Set the Velt Location to the clicked comment location.
> client.setLocation(location);
> }
> }
> }
> }
> ```
>
> The clicked Comment data will be in the following format:
>
> | property | type | description |
> | - | - | - |
> | `documentId` | string | The document ID where the comment was added |
> | `location` | object | The location where the comment was added |
> | `targetElementId` | string | The DOM ID of the target element on which the comment was added |
> | `context` | Object | Any context data passed when the comment was added |
>
> # Additional Configurations
>
> ## Allow comments only on certain elements
>
> Provide a list of element DOM IDs where commenting should be allowed.
> Comments will be disabled for all other elements.
>
> ```jsx theme={null}
> const commentElement = client.getCommentElement();
> commentElement.allowedElementIds(['lottiePlayerContainer']);
> ```
> [tab] Other Frameworks
>
> **1. Add Velt Components in your app**
>
> ### a. Add the `VeltComments` component in the root of your app
>
> Add the `VeltComments` component to enable the Comment feature in your app.
>
> Enable the follow attributes to be `true`:
>
> * `priority`: allows user to P0, P1, or P2 as priority. You can customize this list.
> * `auto-categorize`: allows AI to categorize comment as Question, Feedback, Bug, Other. You can customize this list.
> * `comment-index`: shows a small icon showing index of the comment in order of creation.
>
> ```jsx theme={null}
>
> ```
>
> ### b. Add the `velt-comment-tool` component wherever you want your render the comment tool.
>
> Note you can also provide your own button to this component.
>
> ```jsx theme={null}
>
>
>
>
>
> ```
>
> ### c. Place the `velt-commen-player-timeline` component as a sibling to your video player.
>
> To show comment bubbles on your player seek bar, add the `` component as a sibling to your video player component.
>
> It will auto adjust to the same width as your video player.
>
> ```jsx theme={null}
>
>
>
>
> ```
>
> > [!NOTE]
> >
> > Right now we assume you have a maximum of one `` component and one sibling video player component per `documentID`
>
> > [!WARNING]
> >
> > Ensure that the parent container of `` doesn't have CSS position value as 'static'.
>
> ### d. Add the `` component.
>
> (Optional) To embed the sidebar in your existing component, set `embed-mode` prop as `true`.
>
> ```jsx theme={null}
>
> ```
>
> ### e. Add the `` component.
>
> This will open or close the Comment Sidebar.
> Note you can also provide your own button to this component.
>
> ```jsx theme={null}
>
>
>
> ```
>
> **2. Set the `total-media-length` on the `velt-comment-player-timeline`**
>
> You can pass an integer to `total-media-length` using props to represent the total number of frames or seconds in the video:
>
> ```jsx theme={null}
>
> ```
>
> Alternatively, you can set this using API method call. This is useful if you first need to grab the total frames from another method before setting it.
>
> ```jsx theme={null}
> const commentElement = Velt.getCommentElement();
> commentElement.setTotalMediaLength(120);
> ```
>
> **3. Subscribe to when the Comment Tool is activated by the User.**
>
> Add an event handler to handle `onCommentModeChange` events.
>
> Use this whenever the user clicks on the comment tool, to pause your player and set a new `Location` in the Velt SDK.
>
> Setting a `Location` in the Velt SDK ensures that the comments are tied to that particular media frame or timestamp.
>
> ```jsx theme={null}
> const commentElement = Velt.getCommentElement();
> let subscription = commentElement.onCommentModeChange().subscribe((mode) => {
> // mode will be `true` if the user has activated the comment tool
> // If the comment tool is active, pause the player and set the "location".
> if (mode) {
> // pause player
> // See step 8 below for details
> setLocation()
> }
> });
> ```
>
> To unsubscribe from the subscription:
>
> ```jsx theme={null}
> subscription?.unsubscribe()
> ```
>
> **4. Set Velt Location**
>
> You can pass in a key value pair object that represents the current state of your player. If you are using the `velt-comment-player-timeline` component, ensure to set the current rounded frame or second in the special key `current-media-position`.
>
> > [!NOTE]
> >
> > `current-media-position` is a protected keyword that is used to arrange the comment bubbles on top of the video player timeline in the correct spot
>
> ```jsx theme={null}
> const setLocation = (client) => {
>
> // set currentMediaPosition property on a Location object to represent the current frame
> let location = {
> currentMediaPosition : 120
> }
> //set the Location using the client
> Velt.setLocation(location)
>
> }
> ```
>
> **5. When the player is played, remove Velt `Location` to remove comments from the media.**
>
> Call `removeLocation()` when your player starts playing:
>
> ```jsx theme={null}
> const removeLocation = () => {
> //remove the location, so the video player can play without comments appearing in frames
> Velt.removeLocation()
> }
> ```
>
> **6. Set your player's state when the user clicks on the comment.**
>
> Add the `onCommentClick` event handler on the `VeltCommentsSidebar` & `VeltCommentPlayerTimeline` components you added earlier.
> The event will give you back the `location` object that you had set earlier.
> You can use this object to update your player state and also update the SDK's `location` so that we can start rendering the comments associated with that `location`.
>
> ### a. Handle it on the `velt-comments-sidebar`:
>
> ```jsx theme={null}
>
>
> const onCommentClick = (event) => {
> if (event) {
> // Get the location object from the event.
> const { location } = event;
> if (location) {
> // Get the media position where the comment was added.
> const { currentMediaPosition } = location;
> if (currentMediaPosition) {
> // Pause the player.
>
> // Seek to the given comment media position.
>
> // Set the Velt Location to the clicked comment location.
> client.setLocation(location);
> }
> }
> }
> }
>
> const commentElement = Velt.getCommentElement();
> let subscription = commentElement.onSidebarButtonOnCommentDialogClick().subscribe((event) => onCommentClick(event));
> ```
>
> To unsubscribe from the subscription:
>
> ```jsx theme={null}
> subscription?.unsubscribe()
> ```
>
> ### b. Handle it on the ``:
>
> ```html theme={null}
>
>
> ```
>
> The clicked Comment data will be in the following format:
>
> | property | type | description |
> | - | - | - |
> | `documentId` | string | The document ID where the comment was added |
> | `location` | object | The location where the comment was added |
> | `targetElementId` | string | The DOM ID of the target element on which the comment was added |
> | `context` | Object | Any context data passed when the comment was added |
>
> # Additional Configurations
>
> ## Allow comments only on certain elements
>
> Provide a list of element DOM IDs where commenting should be allowed.
> Comments will be disabled for all other elements.
>
> ```jsx theme={null}
> const commentElement = Velt.getCommentElement();
> commentElement.allowedElementIds(['lottiePlayerContainer']);
> ```
# Monaco Setup
Source: https://velt.dev/docs/async-collaboration/comments/setup/monaco
Add Velt text comments to a Monaco editor with the Velt Monaco comments package.

The Monaco integration renders comment highlights as view-only overlay elements positioned over the commented text. It does not modify your Monaco model, undo history, or saved source code.
## Setup
#### Step 1: Add Comment components
* Add the `Velt Comments` component to the root of your app. This component is required to create and render comments in your app.
* Authenticate the user with `authProvider` and set the Velt document before users add comments.
* Set the `textMode` prop to `false` to hide the default Velt text comment tool. Monaco selections are handled by `@veltdev/monaco-velt-comments`.
* Add `VeltCommentsSidebar` if you want a Google Docs-style comment sidebar.
> [tab] React / Next.js
>
> ```tsx theme={null}
> import { VeltComments, VeltCommentsSidebar, VeltProvider, useSetDocument } from '@veltdev/react';
>
> const user = {
> userId: 'user-1',
> organizationId: 'org-1',
> name: 'User One',
> email: 'user@example.com',
> };
>
> function VeltSetup() {
> useSetDocument('document-id', { documentName: 'Document name' });
> return null;
> }
>
> function App() {
> return (
>
>
>
>
> {/* Your app content */}
>
> );
> }
> ```
> [tab] Other Frameworks
>
> ```html theme={null}
>
>
>
> ```
#### Step 2: Install the Velt Monaco extension
> [tab] React / Next.js
>
> ```bash theme={null}
> npm i @veltdev/monaco-velt-comments monaco-editor @monaco-editor/react
> ```
> [tab] Other Frameworks
>
> ```bash theme={null}
> npm i @veltdev/monaco-velt-comments monaco-editor @veltdev/client
> ```
`monaco-editor` is a peer dependency and must be provided by your Monaco app. The package uses the Monaco editor instance your app creates and does not bundle Monaco at runtime.
#### Step 3: Register the Monaco editor with Velt Comments
Register the integration on the Monaco editor instance returned by `monaco.editor.create` or by `@monaco-editor/react`'s `onMount`. Keep the returned handle so you can dispose it on teardown.
> [tab] React / Next.js
>
> ```tsx theme={null}
> import { useEffect, useRef, useState } from 'react';
> import { Editor as MonacoReact, loader } from '@monaco-editor/react';
> import { useCommentAnnotations } from '@veltdev/react';
> import * as monaco from 'monaco-editor';
> import {
> registerVeltComments,
> renderComments,
> type MonacoEditor,
> type VeltCommentsHandle,
> } from '@veltdev/monaco-velt-comments';
>
> loader.config({ monaco });
>
> const EDITOR_ID = 'my-editor';
>
> function MonacoTextEditor() {
> const [editor, setEditor] = useState(null);
> const handleRef = useRef(null);
> const commentAnnotations = useCommentAnnotations();
>
> useEffect(() => {
> if (!editor) return;
>
> renderComments({
> editor,
> editorId: EDITOR_ID,
> commentAnnotations: commentAnnotations ?? [],
> });
> }, [editor, commentAnnotations]);
>
> useEffect(() => {
> return () => handleRef.current?.dispose();
> }, []);
>
> return (
> height="480px"
> defaultLanguage="typescript"
> defaultValue={'const greeting = "hello world";\n'}
> options={{ automaticLayout: true, wordWrap: 'on' }}
> onMount={(mountedEditor) => {
> setEditor(mountedEditor);
> handleRef.current = registerVeltComments(mountedEditor, {
> editorId: EDITOR_ID,
> });
> }}
> />
> );
> }
> ```
> [tab] Other Frameworks
>
> ```ts theme={null}
> import * as monaco from 'monaco-editor';
> import { registerVeltComments } from '@veltdev/monaco-velt-comments';
>
> const editor = monaco.editor.create(document.querySelector('#editor'), {
> value: 'const greeting = "hello world";\n',
> language: 'typescript',
> automaticLayout: true,
> wordWrap: 'on',
> });
>
> const handle = registerVeltComments(editor, {
> editorId: 'my-editor',
> });
>
> // Later, for example during teardown:
> handle.dispose();
> ```
#### Step 4: Add a comment button to your Monaco editor
Add a button that users can click to add comments after selecting text in the Monaco editor.
**Important:** Use `onMouseDown` with `preventDefault()` so the browser does not move focus away from Monaco before `addComment` reads the current selection. Keep the actual `addComment` call in `onClick`.
> [tab] React / Next.js
>
> ```tsx theme={null}
> import { addComment } from '@veltdev/monaco-velt-comments';
>
> const handleAddComment = () => {
> if (!editor) return;
>
> void addComment({
> editor,
> editorId: EDITOR_ID,
> });
> };
>
> onMouseDown={(event) => event.preventDefault()}
> onClick={handleAddComment}
> >
> Add Comment
>
> ```
> [tab] Other Frameworks
>
> ```html theme={null}
>
>
> ```
>
> ```ts theme={null}
> import { addComment } from '@veltdev/monaco-velt-comments';
>
> const addCommentButton = document.querySelector('#add-comment');
>
> addCommentButton.addEventListener('mousedown', (event) => {
> event.preventDefault();
> });
>
> addCommentButton.addEventListener('click', () => {
> void addComment({ editor, editorId: 'my-editor' });
> });
> ```
Registering the integration also adds an **Add Comment** Monaco editor action in the command palette and right-click menu. The action is enabled only when there is a non-empty editor selection.
#### Step 5: Call `addComment` to add a comment
* Call this method to add a comment to selected text in the Monaco editor.
* Params: [`AddCommentRequest`](/docs/api-reference/sdk/models/data-models#addcommentrequest-10). It has the following properties:
* `editor`: Monaco `IStandaloneCodeEditor` instance.
* `editorId`: Id of the editor. Use this if you have multiple Monaco editors on the same page. (optional)
* `context`: Add custom metadata to the Comment Annotation. [Learn more](/docs/async-collaboration/comments/customize-behavior#metadata). (optional)
> [tab] React / Next.js
>
> ```tsx theme={null}
> import { addComment } from '@veltdev/monaco-velt-comments';
>
> const addCommentRequest = {
> editor,
> editorId: 'EDITOR_ID',
> context: {
> fileId: 'file-123',
> language: 'typescript',
> },
> };
>
> void addComment(addCommentRequest);
> ```
> [tab] Other Frameworks
>
> ```ts theme={null}
> import { addComment } from '@veltdev/monaco-velt-comments';
>
> const addCommentRequest = {
> editor,
> editorId: 'EDITOR_ID',
> context: {
> fileId: 'file-123',
> language: 'typescript',
> },
> };
>
> void addComment(addCommentRequest);
> ```
The library automatically writes `context.textEditorConfig` with the selected text, its 1-based occurrence index in the document, and the editor ID when one is provided.
#### Step 6: Render comments in Monaco editor
* Get the comment data from Velt SDK and render it in the Monaco editor.
* Params: [`RenderCommentsRequest`](/docs/api-reference/sdk/models/data-models#rendercommentsrequest-10). It has the following properties:
* `editor`: Monaco `IStandaloneCodeEditor` instance.
* `editorId`: Id of the editor. Use this if you have multiple Monaco editors on the same page. (optional)
* `commentAnnotations`: Array of Comment Annotation objects.
> [tab] React / Next.js
>
> ```tsx theme={null}
> import { useEffect } from 'react';
> import { useCommentAnnotations } from '@veltdev/react';
> import { renderComments } from '@veltdev/monaco-velt-comments';
>
> const commentAnnotations = useCommentAnnotations();
>
> useEffect(() => {
> if (!editor) return;
>
> renderComments({
> editor,
> editorId: 'EDITOR_ID',
> commentAnnotations: commentAnnotations ?? [],
> });
> }, [editor, commentAnnotations]);
> ```
> [tab] Other Frameworks
>
> ```ts theme={null}
> import { renderComments } from '@veltdev/monaco-velt-comments';
>
> const commentElement = Velt.getCommentElement();
> commentElement.getAllCommentAnnotations().subscribe((annotations) => {
> renderComments({
> editor,
> editorId: 'EDITOR_ID',
> commentAnnotations: annotations,
> });
> });
> ```
#### Step 7: Re-apply Monaco comment highlights (optional)
* Monaco renders comment highlights as view-only overlay elements.
* The integration does not write Velt comment marks into your Monaco model or saved source code.
* Save your Monaco model value normally. After you call `model.setValue(...)`, `editor.setModel(...)`, or load saved content, call `renderComments` again.
```ts theme={null}
const value = editor.getValue();
// Save value to your backend.
renderComments({
editor,
editorId: 'EDITOR_ID',
commentAnnotations,
});
```
#### Step 8: Style the commented text
* You can style the commented text by adding CSS for the `velt-comment-text` element.
* Monaco highlights are rendered as overlay elements in the outer document, so broad `velt-comment-text` styles are appropriate for this integration.
```css theme={null}
velt-comment-text {
background-color: rgba(255, 212, 0, 0.4);
border-bottom: 2px solid #ffd400;
cursor: pointer;
}
velt-comment-text:hover,
velt-comment-text[comment-selected="true"],
velt-comment-text.velt-comment-selected {
background-color: rgba(255, 212, 0, 0.7);
}
```
### Multiple Monaco editors
When using multiple Monaco editors on the same page, provide unique `editorId` values. The library stores `editorId` in `context.textEditorConfig.editorId` and filters annotations by that value when rendering.
```tsx theme={null}
const editor1Handle = registerVeltComments(editor1, { editorId: 'editor-1' });
const editor2Handle = registerVeltComments(editor2, { editorId: 'editor-2' });
await addComment({
editor: editor1,
editorId: 'editor-1',
});
renderComments({
editor: editor2,
editorId: 'editor-2',
commentAnnotations,
});
editor1Handle.dispose();
editor2Handle.dispose();
```
### TypeScript support
The package includes full TypeScript definitions.
```ts theme={null}
import type {
AddCommentRequest,
AnchorEntry,
CommentAnnotation,
CommentAnnotationContext,
MonacoEditor,
MonacoVeltCommentsConfig,
RenderCommentsRequest,
SelectionContext,
SyncAnchor,
VeltCommentsHandle,
} from '@veltdev/monaco-velt-comments';
```
## Complete Example
> [tab] React / Next.js
>
> ```tsx theme={null}
> import { useCallback, useEffect, useRef, useState } from 'react';
> import { Editor as MonacoReact, loader } from '@monaco-editor/react';
> import {
> VeltComments,
> VeltCommentsSidebar,
> VeltCommentsSidebarButton,
> VeltPresence,
> VeltProvider,
> useCommentAnnotations,
> useSetDocument,
> } from '@veltdev/react';
> import * as monaco from 'monaco-editor';
> import {
> addComment,
> registerVeltComments,
> renderComments,
> type MonacoEditor,
> type VeltCommentsHandle,
> } from '@veltdev/monaco-velt-comments';
>
> loader.config({ monaco });
>
> const EDITOR_ID = 'main-editor';
>
> function InitializeDocument() {
> useSetDocument('monaco-comments-doc', {
> documentName: 'Monaco Comments Document',
> });
>
> return null;
> }
>
> function MyEditor() {
> const [editor, setEditor] = useState(null);
> const handleRef = useRef(null);
> const commentAnnotations = useCommentAnnotations();
>
> useEffect(() => {
> if (!editor) return;
>
> renderComments({
> editor,
> editorId: EDITOR_ID,
> commentAnnotations: commentAnnotations ?? [],
> });
> }, [editor, commentAnnotations]);
>
> useEffect(() => {
> return () => handleRef.current?.dispose();
> }, []);
>
> const handleAddComment = useCallback(() => {
> if (!editor) return;
>
> void addComment({
> editor,
> editorId: EDITOR_ID,
> context: { source: 'monaco-editor' },
> });
> }, [editor]);
>
> return (
>
>
>
>
> onMouseDown={(event) => event.preventDefault()}
> onClick={handleAddComment}
> >
> Add Comment
>
>
>
>
height="480px"
> defaultLanguage="typescript"
> defaultValue={'const greeting = "hello world";\n'}
> options={{
> automaticLayout: true,
> wordWrap: 'on',
> scrollBeyondLastLine: false,
> }}
> onMount={(mountedEditor) => {
> setEditor(mountedEditor);
> handleRef.current = registerVeltComments(mountedEditor, {
> editorId: EDITOR_ID,
> });
> }}
> />
>
> );
> }
>
> const user = {
> userId: 'user-1',
> organizationId: 'org-1',
> name: 'User One',
> email: 'user@example.com',
> };
>
> export default function App() {
> return (
>
>
>
>
>
>
> );
> }
> ```
> [tab] Other Frameworks
>
> ```ts theme={null}
> import { initVelt } from '@veltdev/client';
> import * as monaco from 'monaco-editor';
> import {
> addComment,
> registerVeltComments,
> renderComments,
> } from '@veltdev/monaco-velt-comments';
>
> const client = await initVelt('API_KEY');
> await client.identify({
> userId: 'user-1',
> organizationId: 'org-1',
> name: 'User One',
> email: 'user@example.com',
> });
>
> client.setDocument('monaco-comments-doc', {
> documentName: 'Monaco Comments Document',
> });
>
> const editor = monaco.editor.create(document.querySelector('#editor'), {
> value: 'const greeting = "hello world";\n',
> language: 'typescript',
> automaticLayout: true,
> wordWrap: 'on',
> });
>
> const editorId = 'main-editor';
> const handle = registerVeltComments(editor, { editorId });
> const commentElement = Velt.getCommentElement();
>
> commentElement.getAllCommentAnnotations().subscribe((commentAnnotations) => {
> renderComments({
> editor,
> editorId,
> commentAnnotations,
> });
> });
>
> const addCommentButton = document.querySelector('#add-comment');
> addCommentButton.addEventListener('mousedown', (event) => {
> event.preventDefault();
> });
> addCommentButton.addEventListener('click', () => {
> void addComment({ editor, editorId });
> });
>
> window.addEventListener('beforeunload', () => {
> handle.dispose();
> editor.dispose();
> });
> ```
## APIs
#### [registerVeltComments()](/docs/api-reference/sdk/api/api-methods#registerveltcomments)
Registers the Velt comments integration on a Monaco editor instance. The call is idempotent per editor and returns a handle that tears down editor listeners, tracking decorations, overlay elements, renderer state, and local selected-comment subscriber cleanup.
* Params:
* `editor`: Monaco `IStandaloneCodeEditor` instance.
* `config`: [`MonacoVeltCommentsConfig`](/docs/api-reference/sdk/models/data-models#monacoveltcommentsconfig). (optional)
* Returns: [`VeltCommentsHandle`](/docs/api-reference/sdk/models/data-models#veltcommentshandle)
> [tab] React / Next.js
>
> ```tsx theme={null}
> import { registerVeltComments } from '@veltdev/monaco-velt-comments';
>
> const handle = registerVeltComments(editor, {
> editorId: 'my-editor',
> });
>
> handle.dispose();
> ```
> [tab] Other Frameworks
>
> ```ts theme={null}
> import { registerVeltComments } from '@veltdev/monaco-velt-comments';
>
> const handle = registerVeltComments(editor, {
> editorId: 'my-editor',
> });
>
> handle.dispose();
> ```
#### [addComment()](/docs/api-reference/sdk/api/api-methods#addcomment-11)
Creates a Velt comment annotation for the currently selected Monaco text. The selected text and its occurrence index are stored in `annotation.context.textEditorConfig`; the document content is not modified.
* Params: [`AddCommentRequest`](/docs/api-reference/sdk/models/data-models#addcommentrequest-10)
* Returns: `Promise`
> [tab] React / Next.js
>
> ```tsx theme={null}
> import { addComment } from '@veltdev/monaco-velt-comments';
>
> await addComment({
> editor,
> editorId: 'my-editor',
> context: {
> fileId: 'file-123',
> language: 'typescript',
> },
> });
> ```
> [tab] Other Frameworks
>
> ```ts theme={null}
> import { addComment } from '@veltdev/monaco-velt-comments';
>
> await addComment({
> editor,
> editorId: 'my-editor',
> context: {
> fileId: 'file-123',
> language: 'typescript',
> },
> });
> ```
#### [renderComments()](/docs/api-reference/sdk/api/api-methods#rendercomments-11)
Resolves Velt comment annotations to Monaco ranges and renders them as stable `` overlay elements positioned over the commented text.
* Params: [`RenderCommentsRequest`](/docs/api-reference/sdk/models/data-models#rendercommentsrequest-10)
* Returns: `void`
> [tab] React / Next.js
>
> ```tsx theme={null}
> import { renderComments } from '@veltdev/monaco-velt-comments';
>
> renderComments({
> editor,
> editorId: 'my-editor',
> commentAnnotations: commentAnnotations ?? [],
> });
> ```
> [tab] Other Frameworks
>
> ```ts theme={null}
> import { renderComments } from '@veltdev/monaco-velt-comments';
>
> renderComments({
> editor,
> editorId: 'my-editor',
> commentAnnotations,
> });
> ```
#### [isVeltAvailable()](/docs/api-reference/sdk/api/api-methods#isveltavailable)
Checks whether the Velt SDK is loaded on `window.Velt`.
* Params: none
* Returns: `boolean`
> [tab] React / Next.js
>
> ```tsx theme={null}
> import { isVeltAvailable, renderComments } from '@veltdev/monaco-velt-comments';
>
> if (isVeltAvailable()) {
> renderComments({ editor, editorId: 'my-editor', commentAnnotations });
> }
> ```
> [tab] Other Frameworks
>
> ```ts theme={null}
> import { isVeltAvailable, renderComments } from '@veltdev/monaco-velt-comments';
>
> if (isVeltAvailable()) {
> renderComments({ editor, editorId: 'my-editor', commentAnnotations });
> }
> ```
# Nutrient Setup
Source: https://velt.dev/docs/async-collaboration/comments/setup/nutrient
Add Velt text comments to a Nutrient Web SDK PDF viewer with the Velt Nutrient comments extension.

The Nutrient integration renders each Velt comment as a view-only overlay positioned over the commented PDF text with Nutrient `CustomOverlayItem`s. It does not modify your PDF. Comment anchors are stored as a durable `{ text, pageNumber, occurrence }` object and re-resolved against the page text whenever comments render.
## Setup
#### Step 1: Add Comment components
* Add the `Velt Comments` component to the root of your app. This component is required to create and render comments in your app.
* Authenticate the user with `authProvider` and set the Velt document before users add comments.
* Set the `textMode` prop to `false` to hide the default Velt text comment tool. Nutrient selections are handled by `@veltdev/nutrient-velt-comments`.
* Add `VeltCommentsSidebar` if you want a Google Docs-style comment sidebar.
> [tab] React / Next.js
>
> ```tsx theme={null}
> import { VeltComments, VeltCommentsSidebar, VeltProvider, useSetDocument } from '@veltdev/react';
>
> const user = {
> userId: 'user-1',
> organizationId: 'org-1',
> name: 'User One',
> email: 'user@example.com',
> };
>
> function VeltSetup() {
> useSetDocument('document-id', { documentName: 'Document name' });
> return null;
> }
>
> function App() {
> return (
>
>
>
>
> {/* Your app content */}
>
> );
> }
> ```
#### Step 2: Install the Velt Nutrient extension
```bash theme={null}
npm i @veltdev/nutrient-velt-comments @nutrient-sdk/viewer@1.15.1
```
`@nutrient-sdk/viewer` is a peer dependency used for types. Use the same Nutrient version that you load from the CDN script. Load the Nutrient Web SDK at runtime so your app does not bundle the browser-only PDF viewer and WebAssembly assets.
> [tab] React / Next.js
>
> ```tsx theme={null}
> import Script from 'next/script';
>
> const NUTRIENT_CDN_SCRIPT =
> 'https://cdn.cloud.nutrient.io/pspdfkit-web@1.15.1/nutrient-viewer.js';
>
> export default function RootLayout({ children }: { children: React.ReactNode }) {
> return (
>
>
>
> {children}
>
>
> );
> }
> ```
> [!TIP]
>
> If you self-host Nutrient assets, copy `node_modules/@nutrient-sdk/viewer/dist/` into your static folder and load the SDK script from that path. The Velt Nutrient package expects the runtime SDK namespace on `window.NutrientViewer`.
#### Step 3: Configure the Nutrient viewer with the Velt Comments extension
Load the Nutrient viewer, then attach `NutrientVeltComments` to the viewer instance after `NutrientViewer.load(...)` resolves. The same instance is used by `addComment`, `captureSelection`, and `renderComments`.
> [tab] React / Next.js
>
> ```tsx theme={null}
> import { useEffect, useRef, useState } from 'react';
> import { useCommentAnnotations } from '@veltdev/react';
> import {
> NutrientVeltComments,
> renderComments,
> type AttachedExtension,
> type NutrientInstance,
> } from '@veltdev/nutrient-velt-comments';
>
> type NutrientViewerApi = (typeof import('@nutrient-sdk/viewer'))['default'];
>
> declare global {
> interface Window {
> NutrientViewer?: NutrientViewerApi;
> }
> }
>
> const EDITOR_ID = 'my-pdf';
>
> function waitForNutrientViewer(timeoutMs = 30000): Promise {
> return new Promise((resolve, reject) => {
> const start = Date.now();
>
> const tick = () => {
> if (window.NutrientViewer) {
> resolve(window.NutrientViewer);
> return;
> }
>
> if (Date.now() - start > timeoutMs) {
> reject(new Error('Nutrient SDK did not load.'));
> return;
> }
>
> window.setTimeout(tick, 50);
> };
>
> tick();
> });
> }
>
> function NutrientViewerComponent() {
> const viewerRef = useRef(null);
> const instanceRef = useRef(null);
> const extensionRef = useRef(null);
> const [instance, setInstance] = useState(null);
> const annotations = useCommentAnnotations();
>
> useEffect(() => {
> if (!viewerRef.current || instanceRef.current) return;
>
> let cancelled = false;
> const container = viewerRef.current;
>
> waitForNutrientViewer().then((Nutrient) => {
> if (cancelled || instanceRef.current) return;
>
> Nutrient.unload(container);
>
> Nutrient.load({
> container,
> document: '/your-document.pdf',
> licenseKey: 'YOUR_NUTRIENT_LICENSE_KEY',
> }).then((nutrientInstance) => {
> if (cancelled) {
> Nutrient.unload(container);
> return;
> }
>
> instanceRef.current = nutrientInstance;
> extensionRef.current = NutrientVeltComments
> .configure({ editorId: EDITOR_ID })
> .attach(nutrientInstance);
> setInstance(nutrientInstance);
> });
> });
>
> return () => {
> cancelled = true;
> extensionRef.current?.detach();
> extensionRef.current = null;
> window.NutrientViewer?.unload(container);
> instanceRef.current = null;
> setInstance(null);
> };
> }, []);
>
> useEffect(() => {
> if (!instance) return;
>
> renderComments({
> instance,
> commentAnnotations: annotations ?? [],
> });
> }, [instance, annotations]);
>
> return
;
> }
> ```
#### Step 4: Add a comment button to your Nutrient viewer
Add a button that users can click after selecting text in the PDF. Call `captureSelection(instance)` before `addComment({ instance })` so the Velt Nutrient package records the current Nutrient selection before focus moves to your host UI.
> [tab] React / Next.js
>
> ```tsx theme={null}
> import { addComment, captureSelection } from '@veltdev/nutrient-velt-comments';
>
> const handleAddComment = async () => {
> if (!instance) return;
>
> await captureSelection(instance);
> const result = await addComment({ instance });
>
> if (!result) {
> console.warn('Select text in the PDF before adding a comment.');
> }
> };
>
> onMouseDown={(event) => event.preventDefault()}
> onClick={handleAddComment}
> >
> Add Comment
>
> ```
#### Step 5: Call `addComment` to add a comment
* Call this method to add a comment to selected text in the Nutrient viewer.
* Params: [`AddCommentArgs`](/docs/api-reference/sdk/models/data-models#nutrient-addcommentargs). It has the following properties:
* `instance`: Nutrient viewer instance returned by `NutrientViewer.load(...)`.
* Returns: [`Promise`](/docs/api-reference/sdk/models/data-models#nutrient-addcommentresult). It returns `null` if no text is selected or Velt is not loaded.
> [tab] React / Next.js
>
> ```tsx theme={null}
> import { addComment, captureSelection } from '@veltdev/nutrient-velt-comments';
>
> await captureSelection(instance);
> const result = await addComment({ instance });
> ```
To scope comments to a specific viewer on pages with multiple Nutrient instances, pass an editor id when attaching the extension:
```tsx theme={null}
NutrientVeltComments.configure({ editorId: 'EDITOR_ID' }).attach(instance);
```
#### Step 6: Render comments in Nutrient viewer
* Get comment data from the Velt SDK and render it in the Nutrient viewer.
* Params: [`RenderCommentsArgs`](/docs/api-reference/sdk/models/data-models#nutrient-rendercommentsargs). It has the following properties:
* `instance`: Nutrient viewer instance.
* `commentAnnotations`: Array of Comment Annotation objects.
> [tab] React / Next.js
>
> ```tsx theme={null}
> import { useEffect } from 'react';
> import { useCommentAnnotations } from '@veltdev/react';
> import { renderComments } from '@veltdev/nutrient-velt-comments';
>
> const commentAnnotations = useCommentAnnotations();
>
> useEffect(() => {
> if (!instance) return;
>
> renderComments({
> instance,
> commentAnnotations: commentAnnotations ?? [],
> });
> }, [instance, commentAnnotations]);
> ```
Highlights are view-only. The library re-derives each highlight from its [`TextEditorConfig`](/docs/api-reference/sdk/models/data-models#nutrient-texteditorconfig) anchor and Nutrient repositions the overlays across scroll, zoom, and page changes. Re-run `renderComments` when Velt's annotation list changes or when you unload and reload the document.
#### Step 7: Clean up the Velt Nutrient extension
`NutrientVeltComments.configure(...).attach(instance)` returns an [`AttachedExtension`](/docs/api-reference/sdk/models/data-models#nutrient-attachedextension). Call `detach()` in your effect cleanup to remove listeners, clear per-instance state, and remove overlay elements before unloading the viewer.
```tsx theme={null}
return () => {
extensionRef.current?.detach();
extensionRef.current = null;
window.NutrientViewer?.unload(container);
};
```
#### Step 8: Style the commented text
* Each highlight is a `div.velt-nutrient-highlight` inside a `velt-comment-text` overlay.
* Override the default inline highlight styles with `!important`.
```css theme={null}
velt-comment-text .velt-nutrient-highlight {
background-color: rgba(255, 212, 0, 0.4) !important;
border-bottom: 2px solid rgba(255, 170, 0, 0.95) !important;
}
velt-comment-text:hover .velt-nutrient-highlight,
velt-comment-text[comment-selected="true"] .velt-nutrient-highlight,
velt-comment-text.velt-comment-selected .velt-nutrient-highlight {
background-color: rgba(255, 212, 0, 0.7) !important;
}
```
## Complete Example
[https://sample-apps-nutrient-comments-demo.vercel.app/](https://sample-apps-nutrient-comments-demo.vercel.app/)
## APIs
#### [NutrientVeltComments](/docs/api-reference/sdk/api/api-methods#nutrient-nutrientveltcomments)
Creates the Velt Comments extension for a Nutrient viewer. Use `NutrientVeltComments.configure(...).attach(instance)` to attach it to a viewer instance.
* Config: [`NutrientVeltCommentsConfig`](/docs/api-reference/sdk/models/data-models#nutrient-nutrientveltcommentsconfig)
* Returns: `NutrientVeltComments`
> [tab] React / Next.js
>
> ```tsx theme={null}
> import { NutrientVeltComments } from '@veltdev/nutrient-velt-comments';
>
> const attached = NutrientVeltComments
> .configure({ editorId: 'my-pdf' })
> .attach(instance);
>
> attached.detach();
> ```
#### [captureSelection()](/docs/api-reference/sdk/api/api-methods#nutrient-captureselection)
Records the current Nutrient text selection for the next `addComment` call.
* Signature: `(instance: NutrientInstance) => Promise`
* Params: `instance: NutrientInstance`
* Returns: `Promise`
> [tab] React / Next.js
>
> ```tsx theme={null}
> import { captureSelection } from '@veltdev/nutrient-velt-comments';
>
> await captureSelection(instance);
> ```
#### [addComment()](/docs/api-reference/sdk/api/api-methods#nutrient-addcomment)
Creates a comment annotation for the currently captured Nutrient text selection.
* Signature: `async (args: AddCommentArgs) => Promise`
* Params: `args:` [`AddCommentArgs`](/docs/api-reference/sdk/models/data-models#nutrient-addcommentargs)
* Returns: `Promise`; see [`AddCommentResult`](/docs/api-reference/sdk/models/data-models#nutrient-addcommentresult).
> [tab] React / Next.js
>
> ```tsx theme={null}
> import { addComment } from '@veltdev/nutrient-velt-comments';
>
> const result = await addComment({ instance });
> ```
#### [renderComments()](/docs/api-reference/sdk/api/api-methods#nutrient-rendercomments)
Renders and updates Velt comment highlights in the Nutrient viewer.
* Signature: `(args:` [`RenderCommentsArgs`](/docs/api-reference/sdk/models/data-models#nutrient-rendercommentsargs)`) => void`
* Params: `args:` [`RenderCommentsArgs`](/docs/api-reference/sdk/models/data-models#nutrient-rendercommentsargs)
* Returns: `void`
> [tab] React / Next.js
>
> ```tsx theme={null}
> import { renderComments } from '@veltdev/nutrient-velt-comments';
>
> renderComments({
> instance,
> commentAnnotations: annotations ?? [],
> });
> ```
# Page Mode Setup
Source: https://velt.dev/docs/async-collaboration/comments/setup/page

> [tab] React / Next.js
>
> ## 1. Import CommentsSidebar Components
>
> Import the Comments Sidebar Components.
>
> ```jsx theme={null}
> import {
> VeltProvider,
> VeltCommentsSidebar,
> VeltSidebarButton,
> } from '@veltdev/react';
> ```
>
> ## 2. Add Comments and Sidebar components
>
> Add the `VeltComments` and `VeltCommentsSidebar` components to the root of your app.
>
> ```jsx theme={null}
>
>
>
>
> ```
>
> ## 3. Enable Page Mode
>
> Set the `pageMode` attribute to true on the `VeltCommentsSidebar` component.
>
> ```js App.js theme={null}
>
> ```
>
> ## 4. Add Sidebar button component
>
> Add the Sidebar button to toggle the sidebar.
>
> ```jsx theme={null}
>
>
>
> ```
>
> ## 5. Test Page Mode
>
> Test Page Mode out by opening the sidebar. You should be able to leave Page Mode comments at the bottom of the Comments Sidebar.
>
> 
> [tab] Other Frameworks
>
> ## 1. Place the `\` component
>
> Place the `` component at the root of your app.
>
> ```html theme={null}
>
> ```
>
> ## 2. Enable Page Mode
>
> Enable Page Mode by setting the `page-mode` attribute to `true` on the `` component.
>
> ```html theme={null}
>
> ```
>
> ## 3. Place the `\` component
>
> Place the `` component wherever you want the toggle button to appear.
>
> ```html theme={null}
>
> ```
>
> ## 4. Test Page Mode
>
> Test Page Mode out by opening the sidebar. You should be able to leave Page Mode comments at the bottom of the Comments Sidebar.
>
> 
```jsx React / Next.js theme={null}
import {
VeltProvider,
VeltCommentsSidebar,
VeltSidebarButton,
} from '@veltdev/react';
export default function App() {
return (
{/* Add VeltComments to the root of your app provider */}
{/* Add VeltCommentsSidebar to the root of your app provider */}
{/* Add VeltCommentSideBarButton wherever you want it to appear */}
);
}
```
```html HTML theme={null}
Collaboration App
```
# Plate Setup
Source: https://velt.dev/docs/async-collaboration/comments/setup/plate

> [!NOTE]
>
> Plate.js is a React-only framework. This guide covers the React integration only.
## Setup
#### Step 1: Add Comment components
* Add the `Velt Comments` component to the root of your app.
* This component is required to render comments in your app.
* Set the `text mode` prop to `false` to hide the default text comment tool.
> [tab] React / Next.js
>
> ```js theme={null}
>
>
>
> ```
#### Step 2: Install the Velt Plate extension
```bash theme={null}
npm i @veltdev/plate-comments-react
```
#### Step 3: Configure the Plate editor with the Velt Comments extension
* Import `VeltCommentsPlugin` and add it to your Plate editor's plugins array.
> [tab] React / Next.js
>
> ```js theme={null}
> import { Plate, PlateContent, usePlateEditor } from '@platejs/core/react';
> import { VeltCommentsPlugin } from '@veltdev/plate-comments-react';
>
> function PlateEditor() {
> const editor = usePlateEditor({
> plugins: [VeltCommentsPlugin],
> value: initialValue, // Your initial editor content
> });
>
> return (
>
>
>
> );
> }
> ```
#### Step 4: Add a comment button to your Plate editor
* Add a button that users can click to add comments after selecting text.
* Use `onMouseDown` with `preventDefault` to preserve the editor selection when clicking the button.
> [tab] React / Next.js
>
> ```js theme={null}
> import { Plate, PlateContent, usePlateEditor } from '@platejs/core/react';
> import { VeltCommentsPlugin, addComment } from '@veltdev/plate-comments-react';
>
> function PlateEditor() {
> const editor = usePlateEditor({
> plugins: [VeltCommentsPlugin],
> value: initialValue,
> });
>
> const handleAddComment = () => {
> if (editor) {
> addComment({ editor });
> }
> };
>
> return (
>
>
onMouseDown={(e) => {
> e.preventDefault();
> handleAddComment();
> }}
> >
> Add Comment
>
>
>
>
>
> );
> }
> ```
#### Step 5: Call `addComment` to add a comment
* Call this method to add a comment to selected text in the Plate editor. You can use this when the user clicks on the comment button or presses a keyboard shortcut.
* Params: [`AddCommentRequest`](/docs/api-reference/sdk/models/data-models#addcommentrequest-4). It has the following properties:
* `editor`: Instance of the Plate editor.
* `editorId`: Id of the Plate editor. Use this if you have multiple Plate editors on the same page in your app. (optional)
* `context`: Add any custom metadata to the Comment Annotation. [Learn more](/docs/async-collaboration/comments/customize-behavior#metadata). (optional)
> [tab] React / Next.js
>
> ```js theme={null}
> import { addComment } from '@veltdev/plate-comments-react';
>
> const addCommentRequest = {
> editor,
> editorId: 'EDITOR_ID',
> context: {
> storyId: 'story-id',
> storyName: 'story-name',
> },
> };
>
> addComment(addCommentRequest);
> ```
#### Step 6: Render comments in Plate editor
* Get the comment data from Velt SDK using the `useCommentAnnotations` hook and render it in the Plate editor.
* Params: [`RenderCommentsRequest`](/docs/api-reference/sdk/models/data-models#rendercommentsrequest-4). It has the following properties:
* `editor`: Instance of the Plate editor.
* `editorId`: Id of the Plate editor. Use this if you have multiple Plate editors on the same page in your app. (optional)
* `commentAnnotations`: Array of Comment Annotation objects.
> [tab] React / Next.js
>
> ```js theme={null}
> import { useEffect } from 'react';
> import { renderComments } from '@veltdev/plate-comments-react';
> import { useCommentAnnotations } from '@veltdev/react';
>
> function PlateEditor() {
> const annotations = useCommentAnnotations();
>
> useEffect(() => {
> if (editor && annotations) {
> renderComments({
> editor,
> editorId: 'EDITOR_ID',
> commentAnnotations: annotations,
> });
> }
> }, [editor, annotations]);
>
> // ... rest of component
> }
> ```
#### Step 7: Persist Velt Comment Marks (optional)
* By default, Velt comment marks are persisted by the Velt SDK. When the editor loads and the Velt SDK initializes, the marks will be automatically added to the editor.
* If you plan to store the contents of the Plate editor on your end with the comment marks already included, you can disable this feature.
* Default: `true`
```js theme={null}
const editor = usePlateEditor({
plugins: [
VeltCommentsPlugin.configure({
options: {
persistVeltMarks: false,
},
}),
],
});
```
#### Step 8: Style the commented text
* You can style the commented text by adding CSS for the `velt-comment-text` element.
```css theme={null}
velt-comment-text {
background-color: rgba(255, 255, 0, 0.3);
border-bottom: 2px solid #ffcc00;
cursor: pointer;
}
velt-comment-text:hover {
background-color: rgba(255, 255, 0, 0.5);
}
velt-comment-text.velt-comment-selected {
background-color: rgba(255, 255, 0, 0.5);
}
```
## APIs
#### [VeltCommentsPlugin.configure()](/docs/api-reference/sdk/api/api-methods#veltcommentsplugin-configure)
A Plate.js plugin for Velt Comments integration.
* Params: `options?:` [VeltCommentsPluginConfig](/docs/api-reference/sdk/models/data-models#veltcommentspluginconfig)
* `editorId?: string` - Unique identifier for this editor instance (for multi-editor scenarios).
* `persistVeltMarks?: boolean` - Whether to persist Velt marks. Default: `true`.
* Returns: Plate Plugin
> [tab] React / Next.js
>
> ```tsx theme={null}
> import { usePlateEditor } from '@platejs/core/react';
> import { VeltCommentsPlugin } from '@veltdev/plate-comments-react';
>
> // Basic usage
> const editor = usePlateEditor({
> plugins: [VeltCommentsPlugin],
> });
>
> // With configuration
> const editor = usePlateEditor({
> plugins: [
> VeltCommentsPlugin.configure({
> options: {
> editorId: 'my-editor',
> persistVeltMarks: true,
> },
> }),
> ],
> });
> ```
#### [addComment()](/docs/api-reference/sdk/api/api-methods#addcomment-4)
Creates a comment annotation for the currently selected text in the editor.
* Params:
* `request:` [AddCommentRequest](/docs/api-reference/sdk/models/data-models#addcommentrequest-4)
* `editor: PlateEditor`
* `editorId?: string`
* `context?: object`
* Returns: `Promise`
> [tab] React / Next.js
>
> ```tsx theme={null}
> import { addComment } from '@veltdev/plate-comments-react';
>
> onMouseDown={(e) => {
> e.preventDefault();
> addComment({
> editor,
> editorId: 'my-editor',
> context: { customData: 'value' },
> });
> }}
> >
> Comment
>
> ```
#### [renderComments()](/docs/api-reference/sdk/api/api-methods#rendercomments-4)
Renders and highlights comment annotations in the editor.
* Params:
* `request:` [RenderCommentsRequest](/docs/api-reference/sdk/models/data-models#rendercommentsrequest-4)
* `editor: PlateEditor`
* `editorId?: string`
* `commentAnnotations?:` [CommentAnnotation\[\]](/docs/api-reference/sdk/models/data-models#commentannotation)
* Returns: `void`
> [tab] React / Next.js
>
> ```tsx theme={null}
> import { useEffect } from 'react';
> import { renderComments } from '@veltdev/plate-comments-react';
> import { useCommentAnnotations } from '@veltdev/react';
>
> const annotations = useCommentAnnotations();
>
> useEffect(() => {
> if (editor && annotations) {
> renderComments({
> editor,
> editorId: 'my-editor',
> commentAnnotations: annotations,
> });
> }
> }, [editor, annotations]);
> ```
#### [exportJSONWithoutComments()](/docs/api-reference/sdk/api/api-methods#exportjsonwithoutcomments-2)
Exports the editor content as JSON with Velt comment elements removed. Useful when saving content to your backend without comment markup.
* Params: `content: Descendant[]` - The editor content (Slate nodes).
* Returns: `Descendant[]` - Content with comment elements removed.
> [tab] React / Next.js
>
> ```tsx theme={null}
> import { exportJSONWithoutComments } from '@veltdev/plate-comments-react';
>
> const saveContent = () => {
> const cleanContent = exportJSONWithoutComments(editor.children);
> // Save cleanContent to your backend
> };
> ```
#### PlateVeltComment
React component for rendering Velt comment elements in the editor. This is automatically used by the plugin, but can be referenced for custom render element implementations.
> [tab] React / Next.js
>
> ```tsx theme={null}
> import { PlateVeltComment, VeltCommentsElement } from '@veltdev/plate-comments-react';
>
> const renderElement = (props) => {
> if (props.element.type === 'veltComment') {
> return ;
> }
> // ... other elements
> };
> ```
# Popover Setup
Source: https://velt.dev/docs/async-collaboration/comments/setup/popover

## Step 1: Import Comment components
> [tab] React / Next.js
>
> Import the `VeltComments`, `VeltCommentTool`, and `VeltCommentBubble` components.
>
> ```js theme={null}
> import {
> VeltProvider,
> VeltComments,
> VeltCommentTool,
> VeltCommentBubble
> } from '@veltdev/react';
> ```
> [tab] HTML
>
> No imports needed. The Velt SDK is loaded via script tag.
## Step 2: Add Comments component with Popover mode
Add the Comments component to the root of your app and enable Popover mode.
This component is required to render comments in your app. Popover mode means comments can be attached to specific target elements (similar to Google Sheets).
> [tab] React / Next.js
>
> ```js theme={null}
>
>
>
> ```
> [tab] Other Frameworks
>
> Add the comment component to your template close to the root level of your ``.
>
> ```html theme={null}
>
>
>
> ```
## Step 3: Add the Comment Tool component
There are two patterns for adding the Comment Tool:
* Add a Comment Tool next to each element you want to comment on
* Have a single Comment Tool and use it to pin comments on elements
### a. Comment Tool next to each element
Add a Comment Tool near each cell or element you want to comment on. For example, in a table you could add this tool to each cell and show it on hover or right click context menu.
* Add unique DOM ID to each element
* Set the `targetElementId` to match the element's ID
* When users click on the Comment Tool, it attaches a Comment to that element
* If your app is more complex and cannot have unique IDs for each element (e.g., table cell), you could also use `context` to bind the element and comment with custom metadata, which can then be used to filter, group, and render comments that match specific criteria. [Learn more](/docs/async-collaboration/comments/customize-behavior#aggregation)

Once the Comment is added, you'll see a triangle on the top right corner of the element.

> [tab] React / Next.js
>
> ```jsx theme={null}
>
> ```
> [tab] HTML
>
> ```html theme={null}
>
> ```
### b. Single Comment Tool

Add a Comment Tool in a single location such as the navigation bar.
* Add unique DOM ID and `data-velt-target-comment-element-id` attribute to each element (both with the same value)
* When users click on the Comment Tool and then click on the target element, it attaches a Comment to it
* You can only add one Comment Annotation (thread) per element with this approach
* If your app is more complex and cannot have unique IDs for each element (e.g., table cell), you could also use `context` to bind the element and comment with custom metadata, which can then be used to filter, group, and render comments that match specific criteria. [Learn more](/docs/async-collaboration/comments/customize-behavior#aggregation)
> [!WARNING]
>
> If you don't add the `data-velt-target-comment-element-id` attribute, you will be adding multiple Comment Annotations on the same element.
> [tab] React / Next.js
>
> ```jsx theme={null}
>
> ```
> [tab] HTML
>
> ```html theme={null}
>
> ```
## Step 4: Add Metadata to the Comment
* Render additional data on comments UI
* Create custom UI components
* Enable comment filtering on custom data
* Use the metadata later when processing notifications
### a. Using Comment Tool
> [tab] React / Next.js
>
> ```jsx theme={null}
>
> ```
> [tab] HTML
>
> ```html theme={null}
>
> ```
### b. Using Comment Add Event Callback
Learn more about it [here](/docs/async-collaboration/comments/customize-behavior#addcontext).
## Step 5: Add the Comment Bubble component (optional)

> [!WARNING]
>
> Either use this or the default triangle component. Using both could cause visual UX issues. Turn off the triangle by setting `popoverTriangleComponent` to `false` in the Velt Comments component.
The Comment Bubble component:
* Displays a count of replies for a comment thread
* Must have the same `targetElementId` or `context` as its associated element and comment tool
* Can show either total replies or only unread replies
* Can be placed anywhere in your UI
**Props:**
* `commentCountType`: Which count to display
* `total`: Total number of replies (default)
* `unread`: Number of unread replies
> [tab] React / Next.js
>
> ```js theme={null}
>
>
>
> commentCountType="unread"
> targetElementId="cell-id-1"
> />
>
>
>
> commentCountType="unread"
> targetElementId="cell-id-2"
> />
>
>
> ```
> [tab] HTML
>
> ```html theme={null}
>
>
>
> comment-count-type="unread"
> target-element-id="cell-id-1"
> >
>
>
>
> comment-count-type="unread"
> target-element-id="cell-id-2"
> >
>
>
> ```
### Remove Popover Mode Triangle (optional)

You can remove the triangle that appears in Popover mode.
By default, the triangle is enabled.
> [tab] React / Next.js
>
> ```jsx theme={null}
>
> ```
>
> API Method:
>
> ```jsx theme={null}
> const commentElement = client.getCommentElement();
> commentElement.enablePopoverTriangleComponent();
> commentElement.disablePopoverTriangleComponent();
> ```
> [tab] HTML
>
> ```html theme={null}
>
> ```
>
> API Method:
>
> ```jsx theme={null}
> const commentElement = client.getCommentElement();
> commentElement.enablePopoverTriangleComponent();
> commentElement.disablePopoverTriangleComponent();
> ```
## Step 6: Test Integration
Test it out by opening the page with Velt components in your browser.
Click on the Comment Tool and leave a comment on the target element.

## Complete Example
> [tab] React / Next.js
>
> ```jsx theme={null}
> import {
> VeltProvider,
> VeltComments,
> VeltCommentTool,
> VeltCommentBubble
> } from '@veltdev/react';
>
> export default function App() {
> return (
>
>
>
> {/* Pattern a: Comment Tool next to each element */}
>
>
> {/* Pattern b: Single Comment Tool */}
>
>
>
>
> Content
>
>
> Content
>
>
>
>
> );
> }
> ```
> [tab] HTML
>
> ```html theme={null}
>
>
>
>
>
>
>
>
>
>
>
> Content
>
>
> Content
>
>
>
>
> ```
# ProseMirror Setup
Source: https://velt.dev/docs/async-collaboration/comments/setup/prosemirror

## Setup
#### Step 1: Add Comment components
* Add the `Velt Comments` component to the root of your app.
* This component is required to render comments in your app.
* Set the `text mode` prop to `false` to hide the default text comment tool.
> [tab] React / Next.js
>
> ```js theme={null}
>
>
>
> ```
> [tab] Other Frameworks
>
> ```html theme={null}
>
>
>
> ```
#### Step 2: Install the Velt ProseMirror extension
```bash theme={null}
npm i @veltdev/prosemirror-velt-comments prosemirror-model prosemirror-state prosemirror-view
```
For the examples below, also install the standard ProseMirror example packages:
```bash theme={null}
npm i prosemirror-schema-basic prosemirror-example-setup
```
#### Step 3: Configure the ProseMirror editor with the Velt Comments plugin
Add `VeltCommentsPlugin` to the `plugins` array when creating your `EditorState`.
> [tab] React / Next.js
>
> ```tsx theme={null}
> import { useEffect, useRef } from 'react';
> import { schema } from 'prosemirror-schema-basic';
> import { exampleSetup } from 'prosemirror-example-setup';
> import { EditorState } from 'prosemirror-state';
> import { EditorView } from 'prosemirror-view';
> import { VeltCommentsPlugin } from '@veltdev/prosemirror-velt-comments';
>
> const EDITOR_ID = 'my-editor';
>
> function ProseMirrorEditor() {
> const containerRef = useRef(null);
> const viewRef = useRef(null);
>
> useEffect(() => {
> if (!containerRef.current) return;
>
> const state = EditorState.create({
> schema,
> plugins: [
> ...exampleSetup({ schema }),
> VeltCommentsPlugin({ editorId: EDITOR_ID }),
> ],
> });
>
> const view = new EditorView(containerRef.current, { state });
> viewRef.current = view;
>
> return () => {
> view.destroy();
> viewRef.current = null;
> };
> }, []);
>
> return
;
> }
> ```
> [tab] Other Frameworks
>
> ```js theme={null}
> import { schema } from 'prosemirror-schema-basic';
> import { exampleSetup } from 'prosemirror-example-setup';
> import { EditorState } from 'prosemirror-state';
> import { EditorView } from 'prosemirror-view';
> import { VeltCommentsPlugin } from '@veltdev/prosemirror-velt-comments';
>
> const state = EditorState.create({
> schema,
> plugins: [
> ...exampleSetup({ schema }),
> VeltCommentsPlugin({ editorId: 'my-editor' }),
> ],
> });
>
> const view = new EditorView(document.querySelector('#editor'), { state });
> ```
#### Step 4: Add a comment button to your ProseMirror editor
Add a button that users can click to add comments after selecting text in the ProseMirror editor.
**Important:** Use `onMouseDown` with `preventDefault()` so the browser does not move focus away from the editor before `addComment` reads the current selection.
> [tab] React / Next.js
>
> ```tsx theme={null}
> import { addComment } from '@veltdev/prosemirror-velt-comments';
>
> const handleAddComment = () => {
> if (!viewRef.current) return;
>
> addComment({
> editor: viewRef.current,
> editorId: EDITOR_ID,
> });
> };
>
> onMouseDown={(event) => event.preventDefault()}
> onClick={handleAddComment}
> >
> Add Comment
>
> ```
> [tab] Other Frameworks
>
> ```js theme={null}
> import { addComment } from '@veltdev/prosemirror-velt-comments';
>
> const addCommentButton = document.querySelector('#add-comment');
>
> addCommentButton.addEventListener('mousedown', (event) => {
> event.preventDefault();
> });
>
> addCommentButton.addEventListener('click', () => {
> addComment({ editor: view, editorId: 'my-editor' });
> });
> ```
#### Step 5: Call `addComment` to add a comment
* Call this method to add a comment to selected text in the ProseMirror editor.
* Params: [`AddCommentRequest`](/docs/api-reference/sdk/models/data-models#addcommentrequest-8). It has the following properties:
* `editor`: ProseMirror `EditorView`.
* `editorId`: Id of the editor. Use this if you have multiple ProseMirror editors on the same page. (optional)
* `context`: Add custom metadata to the Comment Annotation. [Learn more](/docs/async-collaboration/comments/customize-behavior#metadata). (optional)
> [tab] React / Next.js
>
> ```tsx theme={null}
> import { addComment } from '@veltdev/prosemirror-velt-comments';
>
> const addCommentRequest = {
> editor: viewRef.current,
> editorId: 'EDITOR_ID',
> context: {
> storyId: 'story-id',
> storyName: 'story-name',
> },
> };
>
> addComment(addCommentRequest);
> ```
> [tab] Other Frameworks
>
> ```js theme={null}
> import { addComment } from '@veltdev/prosemirror-velt-comments';
>
> const addCommentRequest = {
> editor: view,
> editorId: 'EDITOR_ID',
> context: {
> storyId: 'story-id',
> storyName: 'story-name',
> },
> };
>
> addComment(addCommentRequest);
> ```
#### Step 6: Render comments in ProseMirror editor
* Get the comment data from Velt SDK and render it in the ProseMirror editor.
* Params: [`RenderCommentsRequest`](/docs/api-reference/sdk/models/data-models#rendercommentsrequest-8). It has the following properties:
* `editor`: ProseMirror `EditorView`.
* `editorId`: Id of the editor. Use this if you have multiple ProseMirror editors on the same page. (optional)
* `commentAnnotations`: Array of Comment Annotation objects.
> [tab] React / Next.js
>
> ```tsx theme={null}
> import { useEffect } from 'react';
> import { useCommentAnnotations } from '@veltdev/react';
> import { renderComments } from '@veltdev/prosemirror-velt-comments';
>
> const commentAnnotations = useCommentAnnotations();
>
> useEffect(() => {
> if (!viewRef.current) return;
>
> renderComments({
> editor: viewRef.current,
> editorId: 'EDITOR_ID',
> commentAnnotations: commentAnnotations ?? [],
> });
> }, [commentAnnotations]);
> ```
> [tab] Other Frameworks
>
> ```js theme={null}
> import { renderComments } from '@veltdev/prosemirror-velt-comments';
>
> const commentElement = Velt.getCommentElement();
> commentElement.getAllCommentAnnotations().subscribe((annotations) => {
> renderComments({
> editor: view,
> editorId: 'EDITOR_ID',
> commentAnnotations: annotations,
> });
> });
> ```
#### Step 7: Re-apply ProseMirror comment highlights (optional)
* ProseMirror renders comment highlights as view-only overlay elements.
* The integration does not write Velt comment marks into your ProseMirror schema or saved document.
* Save your ProseMirror document normally. After you recreate the `EditorView` or replace document content, call `renderComments` again.
```ts theme={null}
const json = view.state.doc.toJSON();
// Save json to your backend.
renderComments({
editor: view,
editorId: 'EDITOR_ID',
commentAnnotations,
});
```
#### Step 8: Style the commented text
* You can style the commented text by adding CSS for the `velt-comment-text` element.
* Use the `comment-available` attribute to apply styles only after comment data has loaded.
```css theme={null}
velt-comment-text[comment-available="true"] {
background-color: rgba(255, 255, 0, 0.3);
border-bottom: 2px solid #ffcc00;
cursor: pointer;
}
velt-comment-text[comment-available="true"]:hover {
background-color: rgba(255, 255, 0, 0.5);
}
velt-comment-text.velt-comment-selected {
background-color: rgba(255, 255, 0, 0.5);
}
```
## Complete Example
[https://sample-apps-prosemirror-comments-demo.vercel.app/](https://sample-apps-prosemirror-comments-demo.vercel.app/)
## APIs
#### [VeltCommentsPlugin()](/docs/api-reference/sdk/api/api-methods#veltcommentsplugin)
Creates the ProseMirror plugin that powers Velt comments. Add it to your editor state's `plugins` array.
* Params: `config?:` [`VeltCommentsPluginConfig`](/docs/api-reference/sdk/models/data-models#veltcommentspluginconfig-1)
* Returns: ProseMirror `Plugin`
> [tab] React / Next.js
>
> ```tsx theme={null}
> import { schema } from 'prosemirror-schema-basic';
> import { exampleSetup } from 'prosemirror-example-setup';
> import { EditorState } from 'prosemirror-state';
> import { VeltCommentsPlugin } from '@veltdev/prosemirror-velt-comments';
>
> const state = EditorState.create({
> schema,
> plugins: [
> ...exampleSetup({ schema }),
> VeltCommentsPlugin({ editorId: 'my-editor' }),
> ],
> });
> ```
> [tab] Other Frameworks
>
> ```js theme={null}
> import { VeltCommentsPlugin } from '@veltdev/prosemirror-velt-comments';
>
> VeltCommentsPlugin({ editorId: 'my-editor' });
> ```
#### [addComment()](/docs/api-reference/sdk/api/api-methods#addcomment-9)
Creates a comment annotation for the currently selected text in the editor.
* Signature: `async (request:` [`AddCommentRequest`](/docs/api-reference/sdk/models/data-models#addcommentrequest-8)`) => Promise`
* Params: `request:` [`AddCommentRequest`](/docs/api-reference/sdk/models/data-models#addcommentrequest-8)
* Returns: `Promise`
> [tab] React / Next.js
>
> ```tsx theme={null}
> import { addComment } from '@veltdev/prosemirror-velt-comments';
>
> const handleAddComment = () => {
> if (!viewRef.current) return;
> addComment({ editor: viewRef.current, editorId: 'my-editor' });
> };
>
> onMouseDown={(event) => event.preventDefault()}
> onClick={handleAddComment}
> >
> Comment
>
> ```
> [tab] Other Frameworks
>
> ```js theme={null}
> import { addComment } from '@veltdev/prosemirror-velt-comments';
>
> addComment({
> editor: view,
> editorId: 'my-editor',
> context: { customData: 'value' },
> });
> ```
#### [renderComments()](/docs/api-reference/sdk/api/api-methods#rendercomments-9)
Renders and highlights comment annotations in the ProseMirror editor.
* Signature: `(request:` [`RenderCommentsRequest`](/docs/api-reference/sdk/models/data-models#rendercommentsrequest-8)`) => void`
* Params: `request:` [`RenderCommentsRequest`](/docs/api-reference/sdk/models/data-models#rendercommentsrequest-8)
* Returns: `void`
> [tab] React / Next.js
>
> ```tsx theme={null}
> import { useEffect } from 'react';
> import { useCommentAnnotations } from '@veltdev/react';
> import { renderComments } from '@veltdev/prosemirror-velt-comments';
>
> const annotations = useCommentAnnotations();
>
> useEffect(() => {
> if (!viewRef.current) return;
>
> renderComments({
> editor: viewRef.current,
> editorId: 'my-editor',
> commentAnnotations: annotations ?? [],
> });
> }, [annotations]);
> ```
> [tab] Other Frameworks
>
> ```js theme={null}
> import { renderComments } from '@veltdev/prosemirror-velt-comments';
>
> const commentElement = Velt.getCommentElement();
> commentElement.getAllCommentAnnotations().subscribe((annotations) => {
> renderComments({
> editor: view,
> editorId: 'my-editor',
> commentAnnotations: annotations,
> });
> });
> ```
#### [veltCommentsPluginKey](/docs/api-reference/sdk/api/api-methods#veltcommentspluginkey)
The ProseMirror `PluginKey` used by the package. Use it only for advanced inspection of plugin state.
* Params: none
* Returns: `PluginKey`
```ts theme={null}
import { veltCommentsPluginKey } from '@veltdev/prosemirror-velt-comments';
const state = veltCommentsPluginKey.getState(view.state);
const anchors = state?.anchors;
```
# Quill Setup
Source: https://velt.dev/docs/async-collaboration/comments/setup/quill

## Setup
#### Step 1: Add Comment components
* Add the `Velt Comments` component to the root of your app.
* This component is required to render comments in your app.
* Set the `text mode` prop to `false` to hide the default text comment tool.
> [tab] React / Next.js
>
> ```js theme={null}
>
>
>
> ```
> [tab] Other Frameworks
>
> ```html theme={null}
>
>
>
> ```
#### Step 2: Install the Velt Quill extension
```bash theme={null}
npm i @veltdev/quill-velt-comments
```
#### Step 3: Configure the Quill editor with the Velt Comments module
> [tab] React / Next.js
>
> ```js theme={null}
> import { useEffect, useRef, useState } from 'react';
> import Quill from 'quill';
> import { QuillVeltComments } from '@veltdev/quill-velt-comments';
>
> // Register the module with Quill (once, outside component)
> Quill.register('modules/veltComments', QuillVeltComments);
>
> function QuillEditor() {
> const editorRef = useRef(null);
> const [quill, setQuill] = useState(null);
>
> useEffect(() => {
> if (!editorRef.current) return;
>
> const quillInstance = new Quill(editorRef.current, {
> theme: 'snow',
> modules: {
> veltComments: {
> persistVeltMarks: true,
> },
> },
> });
>
> setQuill(quillInstance);
> }, []);
>
> return
;
> }
> ```
> [tab] Other Frameworks
>
> ```js theme={null}
> import Quill from 'quill';
> import { QuillVeltComments } from '@veltdev/quill-velt-comments';
>
> // Register the module with Quill
> Quill.register('modules/veltComments', QuillVeltComments);
>
> // Create editor with the module enabled
> const quill = new Quill('#editor', {
> theme: 'snow',
> modules: {
> veltComments: {
> persistVeltMarks: true,
> },
> },
> });
> ```
#### Step 4: Add a comment button to your Quill editor
Add a button that users can click to add comments after selecting text.
> [!WARNING]
>
> When clicking a button, the browser moves focus to the button which clears the editor selection. You must save the selection on `mousedown` (before focus changes) and restore it before adding the comment.
> [tab] React / Next.js
>
> ```js theme={null}
> import { useCallback, useRef } from 'react';
> import { addComment } from '@veltdev/quill-velt-comments';
>
> // Inside your QuillEditor component from Step 3:
> const savedSelectionRef = useRef(null);
>
> const handleAddComment = useCallback(() => {
> if (quill) {
> if (savedSelectionRef.current) {
> quill.setSelection(savedSelectionRef.current.index, savedSelectionRef.current.length);
> }
> addComment({ editor: quill });
> savedSelectionRef.current = null;
> }
> }, [quill]);
>
> // In your JSX:
> onMouseDown={(e) => {
> e.preventDefault();
> const sel = quill?.getSelection();
> if (sel?.length > 0) savedSelectionRef.current = sel;
> }}
> onClick={handleAddComment}
> >
> Add Comment
>
> ```
> [tab] Other Frameworks
>
> ```html theme={null}
>
>
> ```
>
> ```js theme={null}
> import { addComment } from '@veltdev/quill-velt-comments';
>
> let savedSelection = null;
> const btn = document.getElementById('add-comment-btn');
>
> btn.addEventListener('mousedown', () => {
> const sel = quill.getSelection();
> if (sel && sel.length > 0) savedSelection = sel;
> });
>
> btn.addEventListener('click', () => {
> if (savedSelection) quill.setSelection(savedSelection.index, savedSelection.length);
> addComment({ editor: quill });
> savedSelection = null;
> });
> ```
> [!TIP]
>
> Unlike Tiptap, Quill does not have a built-in bubble menu. You will need to create your own comment button or toolbar item.
#### Step 5: Call `addComment` to add a comment
* Call this method to add a comment to selected text in the Quill editor. You can use this when the user clicks on the comment button or presses a keyboard shortcut.
* Params: [`AddCommentRequest`](/docs/api-reference/sdk/models/data-models#addcommentrequest-6). It has the following properties:
* `editor`: Instance of the Quill editor.
* `editorId`: Id of the Quill editor. Use this if you have multiple Quill editors on the same page. (optional)
* `context`: Add any custom metadata to the Comment Annotation. [Learn more](/docs/async-collaboration/comments/customize-behavior#metadata). (optional)
> [tab] React / Next.js
>
> ```js theme={null}
> import { addComment } from '@veltdev/quill-velt-comments';
>
> const addCommentRequest = {
> editor: quill,
> editorId: 'EDITOR_ID',
> context: {
> storyId: 'story-id',
> storyName: 'story-name',
> },
> };
>
> addComment(addCommentRequest);
> ```
> [tab] Other Frameworks
>
> ```js theme={null}
> import { addComment } from '@veltdev/quill-velt-comments';
>
> const addCommentRequest = {
> editor: quill,
> editorId: 'EDITOR_ID',
> context: {
> storyId: 'story-id',
> storyName: 'story-name',
> },
> };
>
> addComment(addCommentRequest);
> ```
#### Step 6: Render comments in Quill editor
* Get the comment data from Velt SDK and render it in the Quill editor.
* Params: [`RenderCommentsRequest`](/docs/api-reference/sdk/models/data-models#rendercommentsrequest-6). It has the following properties:
* `editor`: Instance of the Quill editor.
* `editorId`: Id of the Quill editor. Use this if you have multiple Quill editors on the same page. (optional)
* `commentAnnotations`: Array of Comment Annotation objects.
> [tab] React / Next.js
>
> ```js theme={null}
> import { renderComments } from '@veltdev/quill-velt-comments';
> import { useCommentAnnotations } from '@veltdev/react';
>
> const annotations = useCommentAnnotations();
>
> useEffect(() => {
> if (quill && annotations?.length) {
> const renderCommentsRequest = {
> editor: quill,
> editorId: 'EDITOR_ID',
> commentAnnotations: annotations,
> };
> renderComments(renderCommentsRequest);
> }
> }, [quill, annotations]);
> ```
> [tab] Other Frameworks
>
> ```js theme={null}
> import { renderComments } from '@veltdev/quill-velt-comments';
>
> const commentElement = Velt.getCommentElement();
> commentElement.getAllCommentAnnotations().subscribe((annotations) => {
> if (quill && annotations?.length) {
> const renderCommentsRequest = {
> editor: quill,
> editorId: 'EDITOR_ID',
> commentAnnotations: annotations,
> };
> renderComments(renderCommentsRequest);
> }
> });
> ```
#### Step 7: Persist Velt Comment Marks (optional)
* By default, Velt comment marks (``) are persisted by the Velt SDK. When the editor loads and the Velt SDK initializes, the marks will be automatically added to the editor.
* If you plan to store the contents of the Quill editor on your end with the comment marks already included, you can disable this feature.
* Default: `true`
```js theme={null}
const quill = new Quill(editorRef.current, {
theme: 'snow',
modules: {
veltComments: {
persistVeltMarks: false,
},
},
});
```
#### Step 8: Style the commented text
* You can style the commented text by adding CSS for the `velt-comment-text` element.
```css theme={null}
velt-comment-text {
background-color: rgba(255, 255, 0, 0.3);
border-bottom: 2px solid #ffcc00;
cursor: pointer;
}
velt-comment-text:hover {
background-color: rgba(255, 255, 0, 0.5);
}
velt-comment-text.velt-comment-selected {
background-color: rgba(255, 255, 0, 0.5);
}
```
## APIs
#### [QuillVeltComments](/docs/api-reference/sdk/api/api-methods#quillveltcomments)
The Velt Comments module for Quill. Register it with Quill before creating the editor.
* Params: `options?:` [QuillVeltCommentsConfig](/docs/api-reference/sdk/models/data-models#quillveltcommentsconfig)
* `editorId?: string` - Unique identifier for this editor instance (for multi-editor scenarios)
* `persistVeltMarks?: boolean` - Whether to persist Velt marks. Default: `true`
* Returns: `Quill Module`
> [tab] React / Next.js
>
> ```tsx theme={null}
> import Quill from 'quill';
> import { QuillVeltComments } from '@veltdev/quill-velt-comments';
>
> Quill.register('modules/veltComments', QuillVeltComments);
>
> const quillInstance = new Quill(editorRef.current, {
> theme: 'snow',
> modules: {
> veltComments: {
> editorId: 'my-editor',
> persistVeltMarks: true,
> },
> },
> });
> ```
> [tab] Other Frameworks
>
> ```tsx theme={null}
> import Quill from 'quill';
> import { QuillVeltComments } from '@veltdev/quill-velt-comments';
>
> Quill.register('modules/veltComments', QuillVeltComments);
>
> const quill = new Quill('#editor', {
> theme: 'snow',
> modules: {
> veltComments: {
> editorId: 'my-editor',
> persistVeltMarks: true,
> },
> },
> });
> ```
#### [addComment()](/docs/api-reference/sdk/api/api-methods#addcomment-6)
Creates a comment annotation for the currently selected text in the editor.
* Params:
* `request:` [AddCommentRequest](/docs/api-reference/sdk/models/data-models#addcommentrequest-6)
* `editor: Quill`
* `editorId?: string`
* `context?: object`
* Returns: `Promise`
> [tab] React / Next.js
>
> ```tsx theme={null}
> import { addComment } from '@veltdev/quill-velt-comments';
>
> onMouseDown={(e) => {
> e.preventDefault();
> addComment({
> editor: quill,
> editorId: 'my-editor',
> context: { customData: 'value' }
> });
> }}
> >
> Comment
>
> ```
> [tab] Other Frameworks
>
> ```tsx theme={null}
> import { addComment } from '@veltdev/quill-velt-comments';
>
> addComment({
> editor: quill,
> editorId: 'my-editor',
> context: { customData: 'value' },
> });
> ```
#### [renderComments()](/docs/api-reference/sdk/api/api-methods#rendercomments-6)
Renders and highlights comment annotations in the editor.
* Params:
* `request:` [RenderCommentsRequest](/docs/api-reference/sdk/models/data-models#rendercommentsrequest-6)
* `editor: Quill`
* `editorId?: string`
* `commentAnnotations?:` [CommentAnnotation\[\]](/docs/api-reference/sdk/models/data-models#commentannotation)
* Returns: `void`
> [tab] React / Next.js
>
> ```tsx theme={null}
> import { useEffect } from 'react';
> import { renderComments } from '@veltdev/quill-velt-comments';
> import { useCommentAnnotations } from '@veltdev/react';
>
> const annotations = useCommentAnnotations();
>
> useEffect(() => {
> if (quill && annotations) {
> renderComments({
> editor: quill,
> editorId: 'my-editor',
> commentAnnotations: annotations,
> });
> }
> }, [quill, annotations]);
> ```
> [tab] Other Frameworks
>
> ```tsx theme={null}
> import { renderComments } from '@veltdev/quill-velt-comments';
>
> const commentElement = Velt.getCommentElement();
> commentElement.getAllCommentAnnotations().subscribe((annotations) => {
> if (quill && annotations) {
> renderComments({
> editor: quill,
> editorId: 'my-editor',
> commentAnnotations: annotations,
> });
> }
> });
> ```
# SlateJS Setup
Source: https://velt.dev/docs/async-collaboration/comments/setup/slatejs

## Setup
#### Step 1: Add Comment components
* Add the `Velt Comments` component to the root of your app.
* This component is required to render comments in your app.
* Set the `text mode` prop to `false` to hide the default text comment tool.
> [tab] React / Next.js
>
> ```js theme={null}
>
>
>
> ```
#### Step 2: Install the Velt SlateJS extension
```bash theme={null}
npm i @veltdev/slate-velt-comments
```
#### Step 3: Configure the SlateJS editor with the Velt Comments extension
> [tab] React / Next.js
>
> ```js theme={null}
> import { withVeltComments } from '@veltdev/slate-velt-comments';
> import { withReact, withHistory } from 'slate-react';
>
> const editor = withVeltComments(
> withReact(withHistory(createEditor())),
> { HistoryEditor: SlateHistoryEditor }
> );
> ```
#### Step 4: Register Velt component type in SlateJS
* Register the Velt Comments Element type with your SlateJS editor's custom types.
* This ensures proper type checking for the comments functionality.
> [tab] React / Next.js
>
> ```ts theme={null}
> import type { VeltCommentsElement } from '@veltdev/slate-velt-comments';
>
> type CustomElement = VeltCommentsElement;
>
> declare module 'slate' {
> interface CustomTypes {
> Element: CustomElement;
> }
> }
> ```
#### Step 5: Add a comment button to your SlateJS editor
* Add a button that appears in the context menu of your SlateJS editor when the user selects text.
* This button will be used to add a comment to the selected text.
> [tab] React / Next.js
>
> ```js theme={null}
> import { addComment } from '@veltdev/slate-velt-comments';
> import { useSlate } from 'slate-react';
>
> const CommentButton = (props) => {
> const editor = useSlate();
>
> return (
> onMouseDown={(e) => {
> e.preventDefault();
> addComment({ editor });
> }}
> >
> Comment
>
> );
> };
> ```
#### Step 6: Call `addComment` to add a comment
* Call this method to add a comment to selected text in the SlateJS editor. You can use this when the user clicks on the comment button in context menu or presses a keyboard shortcut.
* Params: `AddCommentRequest`
* `editorId`: string, the id of the editor. Use this if you have multiple editors in your app.
* `editor`: instance of the SlateJS editor.
* `context`: optional object to set the Comment Annotation's [custom metadata](/docs/async-collaboration/comments/customize-behavior#metadata).
> [tab] React / Next.js
>
> ```js theme={null}
> import { addComment } from '@veltdev/slate-velt-comments';
> import { useSlate } from 'slate-react';
>
> const CommentButton = (props) => {
> const editor = useSlate();
>
> return (
> onMouseDown={(e) => {
> e.preventDefault();
> addComment({ editor });
> }}
> >
> Comment
>
> );
> };
> ```
#### Step 7: Render comments in SlateJS editor
* Get the comment data.
* Render the comments in the SlateJS editor.
* Params: `RenderCommentsRequest`
* `editorId`: string, the id of the editor. Use this if you have multiple editors in your app.
* `editor`: instance of the SlateJS editor.
* `commentAnnotations`: CommentAnnotation\[]
> [tab] React / Next.js
>
> ```js theme={null}
> import { renderComments } from '@veltdev/slate-velt-comments';
>
> const commentAnnotations = useCommentAnnotations();
>
> useEffect(() => {
> if (editor && commentAnnotations) {
> renderComments({ editor, commentAnnotations });
> }
> }, [commentAnnotations, editor]);
> ```
#### Step 8: Style the commented text
* You can style the commented text by adding a CSS class to the `velt-comment-text` element.
* By using the `comment-available` attribute, you can apply styles only when the comment data has loaded.
```css theme={null}
velt-comment-text[comment-available="true"] {
background-color: #ffff00;
}
```
## Complete Example
[https://slatejs-app-demo.vercel.app/](https://slatejs-app-demo.vercel.app/)
## APIs
#### [withVeltComments()](/docs/api-reference/sdk/api/api-methods#withveltcomments)
Augment a Slate editor with Velt Comments support (adds schema/commands/normalizers).
* Params:
* `editor: Editor`
* `options?: VeltCommentsEditorOptions`
* Returns: `VeltCommentsEditor`
> [tab] React / Next.js
>
> ```jsx theme={null}
> import { withVeltComments } from '@veltdev/slate-velt-comments';
> import { withReact, withHistory } from 'slate-react';
>
> const editor = withVeltComments(
> withReact(withHistory(createEditor())),
> { HistoryEditor: SlateHistoryEditor }
> );
> ```
#### [addComment()](/docs/api-reference/sdk/api/api-methods#addcomment)
Creates a comment annotation for the currently selected text in the editor.
* Signature: `async (request:` [AddCommentRequest](/docs/api-reference/sdk/models/data-models#addcommentrequest)`) => Promise`
* Params: `request:` [AddCommentRequest](/docs/api-reference/sdk/models/data-models#addcommentrequest)
* Returns: `Promise`
> [tab] React / Next.js
>
> ```jsx theme={null}
> import { addComment } from '@veltdev/slate-velt-comments';
>
> { e.preventDefault(); addComment({ editor }); }}>
> Comment
>
> ```
#### [renderComments()](/docs/api-reference/sdk/api/api-methods#rendercomments)
Renders and highlights comment annotations in the editor.
* Signature: `(request:` [RenderCommentsRequest](/docs/api-reference/sdk/models/data-models#rendercommentsrequest)`) => void`
* Params: `request:` [RenderCommentsRequest](/docs/api-reference/sdk/models/data-models#rendercommentsrequest)
* Returns: `void`
> [tab] React / Next.js
>
> ```jsx theme={null}
> import { renderComments } from '@veltdev/slate-velt-comments';
> import type { CommentAnnotation } from '@veltdev/types';
>
> useEffect(() => {
> if (editor && commentAnnotations) {
> renderComments({ editor, commentAnnotations });
> }
> }, [editor, commentAnnotations]);
> ```
#### [SlateVeltComment](/docs/api-reference/sdk/api/api-methods#slateveltcomment)
React component that renders a Velt comment text element with annotation ID.
* Params:
* `props: RenderElementProps`
* `element:` [VeltCommentsElement](/docs/api-reference/sdk/models/data-models#veltcommentselement)
* Returns: `N/A`
```tsx theme={null}
import { SlateVeltComment } from '@veltdev/slate-velt-comments';
import type { RenderElementProps } from 'slate-react';
import type { VeltCommentsElement } from '@veltdev/slate-velt-comments';
const RenderElement = (props: RenderElementProps) => {
if (props.element.type === 'veltComment') {
return ;
}
return {props.children}
;
};
```
# SpreadJS Setup
Source: https://velt.dev/docs/async-collaboration/comments/setup/spreadjs
Add Velt comments to a SpreadJS workbook with the Velt SpreadJS comments extension.

The SpreadJS integration renders each Velt comment as a view-only overlay positioned over the commented cell or range. It does not modify your workbook. Comment anchors are stored as durable `{ sheetName, row, col, rowCount, colCount }` data and re-resolved to pixels with SpreadJS cell geometry whenever comments render.
## Setup
#### Step 1: Add Comment components
* Add the `Velt Comments` component to the root of your app. This component is required to create and render comments in your app.
* Authenticate the user with `authProvider` and set the Velt document before users add comments.
* Set the `textMode` prop to `false` to hide the default Velt text comment tool. SpreadJS selections are handled by `@veltdev/spreadjs-velt-comments`.
* Add `VeltCommentsSidebar` if you want a Google Docs-style comment sidebar.
> [tab] React / Next.js
>
> ```tsx theme={null}
> import { VeltComments, VeltCommentsSidebar, VeltProvider, useSetDocument } from '@veltdev/react';
>
> const user = {
> userId: 'user-1',
> organizationId: 'org-1',
> name: 'User One',
> email: 'user@example.com',
> };
>
> function VeltSetup() {
> useSetDocument('spreadsheet-id', { documentName: 'Spreadsheet name' });
> return null;
> }
>
> function App() {
> return (
>
>
>
>
> {/* Your app content */}
>
> );
> }
> ```
#### Step 2: Install the Velt SpreadJS extension
```bash theme={null}
npm i @veltdev/spreadjs-velt-comments @mescius/spread-sheets @mescius/spread-sheets-io
```
`@mescius/spread-sheets` is a peer dependency of the Velt SpreadJS package. `@mescius/spread-sheets-io` is required when you import XLSX files into a workbook.
> [tab] React / Next.js
>
> ```tsx theme={null}
> import '@mescius/spread-sheets/styles/gc.spread.sheets.excel2013white.css';
> ```
#### Step 3: Configure the SpreadJS workbook with the Velt Comments extension
Create the workbook, import your spreadsheet, then attach `SpreadJSVeltComments` after the import completes. The same workbook instance is used by `addComment` and `renderComments`.
> [tab] React / Next.js
>
> ```tsx theme={null}
> import { useEffect, useRef, useState } from 'react';
> import { useCommentAnnotations } from '@veltdev/react';
> import {
> SpreadJSVeltComments,
> renderComments,
> type AttachedExtension,
> type SpreadInstance,
> } from '@veltdev/spreadjs-velt-comments';
>
> const EDITOR_ID = 'my-workbook';
>
> function SpreadsheetEditor() {
> const hostRef = useRef(null);
> const workbookRef = useRef(null);
> const extensionRef = useRef(null);
> const [instance, setInstance] = useState(null);
> const annotations = useCommentAnnotations();
>
> useEffect(() => {
> if (!hostRef.current || workbookRef.current) return;
>
> let cancelled = false;
> const host = hostRef.current;
>
> import('@mescius/spread-sheets').then(async (spreadModule) => {
> const GC = 'default' in spreadModule ? spreadModule.default : spreadModule;
> await import('@mescius/spread-sheets-io');
> if (cancelled || workbookRef.current) return;
>
> const workbook = new GC.Spread.Sheets.Workbook(host);
> workbookRef.current = workbook;
>
> const response = await fetch('/your-workbook.xlsx');
> const file = new File([await response.blob()], 'your-workbook.xlsx');
>
> workbook.import(
> file,
> () => {
> if (cancelled) return;
>
> extensionRef.current = SpreadJSVeltComments
> .configure({ editorId: EDITOR_ID })
> .attach(workbook);
> setInstance(workbook);
> },
> (error: unknown) => console.error('XLSX import failed', error),
> { fileType: GC.Spread.Sheets.FileType.excel },
> );
> });
>
> return () => {
> cancelled = true;
> extensionRef.current?.detach();
> workbookRef.current?.destroy();
> workbookRef.current = null;
> setInstance(null);
> };
> }, []);
>
> useEffect(() => {
> if (!instance) return;
>
> renderComments({
> instance,
> commentAnnotations: annotations ?? [],
> });
> }, [instance, annotations]);
>
> return
;
> }
> ```
#### Step 4: Add a comment button to your SpreadJS workbook
SpreadJS renders the grid to a canvas, so there is no DOM text selection for a default text bubble menu. Add a toolbar button or contextual selection bubble that uses the workbook's selected cell/range state, then call `addComment({ instance })`.
> [tab] React / Next.js
>
> ```tsx theme={null}
> import { addComment } from '@veltdev/spreadjs-velt-comments';
>
> const handleAddComment = async () => {
> if (!instance) return;
>
> const result = await addComment({ instance });
> if (!result) {
> console.warn('Select a cell or range before adding a comment.');
> }
> };
>
> Add Comment
> ```
#### Step 5: Call `addComment` to add a comment
* Call this method to add a comment to the currently selected cell or range.
* Params: [`AddCommentArgs`](/docs/api-reference/sdk/models/data-models#spreadjs-addcommentargs). It has the following properties:
* `instance`: SpreadJS workbook instance created with `new GC.Spread.Sheets.Workbook(host)`.
* Returns: [`Promise`](/docs/api-reference/sdk/models/data-models#spreadjs-addcommentresult). It returns `null` if no cell/range is selected or Velt is not loaded.
> [tab] React / Next.js
>
> ```tsx theme={null}
> import { addComment } from '@veltdev/spreadjs-velt-comments';
>
> const result = await addComment({ instance });
> ```
To scope comments to a specific workbook on pages with multiple SpreadJS instances, pass an editor id when attaching the extension:
```tsx theme={null}
SpreadJSVeltComments.configure({ editorId: 'EDITOR_ID' }).attach(workbook);
```
#### Step 6: Render comments in SpreadJS workbook
* Get comment data from the Velt SDK and render it in the SpreadJS workbook.
* Params: [`RenderCommentsArgs`](/docs/api-reference/sdk/models/data-models#spreadjs-rendercommentsargs). It has the following properties:
* `instance`: SpreadJS workbook instance.
* `commentAnnotations`: Array of Comment Annotation objects.
> [tab] React / Next.js
>
> ```tsx theme={null}
> import { useEffect } from 'react';
> import { useCommentAnnotations } from '@veltdev/react';
> import { renderComments } from '@veltdev/spreadjs-velt-comments';
>
> const commentAnnotations = useCommentAnnotations();
>
> useEffect(() => {
> if (!instance) return;
>
> renderComments({
> instance,
> commentAnnotations: commentAnnotations ?? [],
> });
> }, [instance, commentAnnotations]);
> ```
Highlights are view-only. The library re-derives each highlight from its [`TextEditorConfig`](/docs/api-reference/sdk/models/data-models#spreadjs-texteditorconfig) anchor and SpreadJS repositions the overlays across scroll, zoom, row/column resize, and sheet changes. Re-run `renderComments` when Velt's annotation list changes or when you import a new workbook.
#### Step 7: Clean up the Velt SpreadJS extension
`SpreadJSVeltComments.configure(...).attach(instance)` returns an [`AttachedExtension`](/docs/api-reference/sdk/models/data-models#spreadjs-attachedextension). Call `detach()` in your effect cleanup to remove listeners, clear per-instance state, and remove overlay elements before destroying the workbook.
```tsx theme={null}
return () => {
extensionRef.current?.detach();
extensionRef.current = null;
workbookRef.current?.destroy();
};
```
#### Step 8: Style the commented text
* Each comment is rendered through a `.velt-spreadjs-overlay` layer with a `.velt-spreadjs-highlight` range fill and a `velt-comment-text` marker.
* Override the default inline highlight styles with `!important`.
```css theme={null}
.velt-spreadjs-highlight {
background-color: rgba(255, 212, 0, 0.36) !important;
border: 1.5px solid rgba(255, 170, 0, 0.95) !important;
}
velt-comment-text:hover .velt-spreadjs-highlight,
velt-comment-text[comment-selected="true"] .velt-spreadjs-highlight,
velt-comment-text.velt-comment-selected .velt-spreadjs-highlight {
background-color: rgba(255, 212, 0, 0.62) !important;
}
```
## Complete Example
[https://sample-apps-spreadjs-comments-demo.vercel.app/](https://sample-apps-spreadjs-comments-demo.vercel.app/)
## APIs
#### [SpreadJSVeltComments](/docs/api-reference/sdk/api/api-methods#spreadjs-spreadjsveltcomments)
Creates the Velt Comments extension for a SpreadJS workbook. Use `SpreadJSVeltComments.configure(...).attach(instance)` to attach it to a workbook instance.
* Config: [`SpreadJSVeltCommentsConfig`](/docs/api-reference/sdk/models/data-models#spreadjs-spreadjsveltcommentsconfig)
* Returns: `SpreadJSVeltComments`
> [tab] React / Next.js
>
> ```tsx theme={null}
> import { SpreadJSVeltComments } from '@veltdev/spreadjs-velt-comments';
>
> const attached = SpreadJSVeltComments
> .configure({ editorId: 'my-workbook' })
> .attach(instance);
>
> attached.detach();
> ```
#### [addComment()](/docs/api-reference/sdk/api/api-methods#spreadjs-addcomment)
Creates a comment annotation for the currently selected SpreadJS cell or range.
* Signature: `async (args: AddCommentArgs) => Promise`
* Params: `args:` [`AddCommentArgs`](/docs/api-reference/sdk/models/data-models#spreadjs-addcommentargs)
* Returns: `Promise`; see [`AddCommentResult`](/docs/api-reference/sdk/models/data-models#spreadjs-addcommentresult).
> [tab] React / Next.js
>
> ```tsx theme={null}
> import { addComment } from '@veltdev/spreadjs-velt-comments';
>
> const result = await addComment({ instance });
> ```
#### [renderComments()](/docs/api-reference/sdk/api/api-methods#spreadjs-rendercomments)
Renders and updates Velt comment highlights in the SpreadJS workbook.
* Signature: `(args:` [`RenderCommentsArgs`](/docs/api-reference/sdk/models/data-models#spreadjs-rendercommentsargs)`) => void`
* Params: `args:` [`RenderCommentsArgs`](/docs/api-reference/sdk/models/data-models#spreadjs-rendercommentsargs)
* Returns: `void`
> [tab] React / Next.js
>
> ```tsx theme={null}
> import { renderComments } from '@veltdev/spreadjs-velt-comments';
>
> renderComments({
> instance,
> commentAnnotations: annotations ?? [],
> });
> ```
# Stream Setup
Source: https://velt.dev/docs/async-collaboration/comments/setup/stream

> [tab] React / Next.js
>
> ## 1. Import Comment components
>
> Import the `VeltComments` component.
>
> ```js theme={null}
> import {
> VeltProvider,
> VeltComments,
> } from '@veltdev/react';
> ```
>
> ## 2. Add `VeltComments` component with Stream mode
>
> Add the `VeltComments` component inside a scrolling container. Make it a sibling to the element that contains the content you want to be commented.
>
> In the `VeltComments` component, mark the `streamMode` attribute as `true`.
>
> Also set the `streamViewContainerId` attribute to the id of the scrolling container.
>
> Stream mode renders all comment dialog boxes in a column on the right side similar to Google Docs. It works well with Text mode, which is enabled by default.
>
> Setting a reference to the container ID helps us position & scroll the comment stream as the user scrolls more robustly.
>
> ```js theme={null}
>
>
>
>
> ```
>
> ## 3. Test Integration
>
> Test it out by adding a comment.
>
> Select any text, a `Comment Tool` button will appear near the highlighted text.
>
> Click on it to add a comment and see the comment appear in the comment stream.
> [tab] Other Frameworks
>
> ## 1. Add the velt-comments component with Stream mode
>
> Add the `` component inside a scrolling container. Make it a sibling to the element that contains the content you want to be commented.
>
> In the `` component, mark the `stream-mode` attribute as `true`.
>
> Also set the `stream-view-container-id` attribute to the id of the scrolling container.
>
> Stream mode renders all comment dialog boxes in a column on the right side similar to Google Docs. It works well with Text mode, which is enabled by default.
>
> Setting a reference to the container ID helps us position & scroll the comment stream as the user scrolls more robustly.
>
> ```html theme={null}
>
>
>
> ```
>
> ## 2. Test Integration
>
> Test it out by adding a comment.
>
> Select any text, a `Comment Tool` button will appear near the highlighted text.
>
> Click on it to add a comment and see the comment appear in the comment stream.
```jsx React / Next.js theme={null}
import { VeltProvider, VeltComments, VeltCommentTool } from '@veltdev/react';
export default function App() {
return (
);
}
```
```html HTML theme={null}
Comment documentation
```
# SuperDoc Setup
Source: https://velt.dev/docs/async-collaboration/comments/setup/superdoc

The SuperDoc integration renders Velt comment highlights as view-only overlay elements positioned over the commented text. It does not write Velt comment marks into your DOCX content. Comment anchors are stored as a durable text and occurrence pair, then resolved against the live SuperDoc document whenever comments render.
## Setup
#### Step 1: Add Comment components
* Add the `Velt Comments` component to the root of your app.
* This component is required to render comments in your app.
* Set the `textMode` prop to `false` to hide the default text comment tool.
> [tab] React / Next.js
>
> ```tsx theme={null}
> import { VeltComments, VeltProvider } from '@veltdev/react';
>
>
>
>
> ```
#### Step 2: Install the Velt SuperDoc extension
```bash theme={null}
npm i @veltdev/superdoc-velt-comments @harbour-enterprises/superdoc
```
SuperDoc is browser-only because it touches `window` and the DOM. Import its stylesheet globally, then dynamically import the SuperDoc SDK and Velt extension inside a client-side effect.
```tsx theme={null}
import '@harbour-enterprises/superdoc/style.css';
```
#### Step 3: Configure the SuperDoc editor with the Velt Comments extension
Create the SuperDoc editor, disable SuperDoc's built-in comments, then attach `SuperDocVeltComments` from the editor's `onReady` callback.
> [tab] React / Next.js
>
> ```tsx theme={null}
> import { useEffect, useRef, useState } from 'react';
> import { useCommentAnnotations } from '@veltdev/react';
> import type {
> AttachedExtension,
> SuperDocInstance,
> } from '@veltdev/superdoc-velt-comments';
>
> const EDITOR_ID = 'my-doc';
>
> function SuperDocEditor() {
> const hostRef = useRef(null);
> const superdocRef = useRef(null);
> const extensionRef = useRef(null);
> const [instance, setInstance] = useState(null);
> const annotations = useCommentAnnotations();
>
> useEffect(() => {
> if (!hostRef.current || superdocRef.current) return;
>
> let cancelled = false;
> const host = hostRef.current;
>
> Promise.all([
> import('@harbour-enterprises/superdoc'),
> import('@veltdev/superdoc-velt-comments'),
> ]).then(([{ SuperDoc }, wrapper]) => {
> if (cancelled) return;
>
> superdocRef.current = new SuperDoc({
> selector: host,
> toolbar: '#superdoc-toolbar',
> document: '/sample.docx',
> documentMode: 'editing',
> modules: { comments: false },
> onReady: () => {
> if (cancelled || !superdocRef.current) return;
>
> extensionRef.current = wrapper.SuperDocVeltComments
> .configure({ editorId: EDITOR_ID })
> .attach(superdocRef.current);
> setInstance(superdocRef.current);
> },
> });
> });
>
> return () => {
> cancelled = true;
> extensionRef.current?.detach();
> extensionRef.current = null;
> superdocRef.current?.destroy();
> superdocRef.current = null;
> setInstance(null);
> };
> }, []);
>
> useEffect(() => {
> if (!instance) return;
>
> import('@veltdev/superdoc-velt-comments').then(({ renderComments }) => {
> renderComments({
> instance,
> commentAnnotations: annotations ?? [],
> });
> });
> }, [instance, annotations]);
>
> return (
> <>
>
>
> >
> );
> }
> ```
#### Step 4: Add a comment button to your SuperDoc editor
Add a button users can click after selecting text in the SuperDoc editor. Use `onMouseDown` with `preventDefault()` so clicking the button does not clear the current editor selection before `addComment` reads it. Keep the actual `addComment` call in `onClick`.
> [tab] React / Next.js
>
> ```tsx theme={null}
> const handleAddComment = async () => {
> if (!instance) return;
>
> const { addComment } = await import('@veltdev/superdoc-velt-comments');
> const result = await addComment({ instance });
>
> if (!result) {
> console.warn('Select text in the document before adding a comment.');
> }
> };
>
> onMouseDown={(event) => event.preventDefault()}
> onClick={handleAddComment}
> >
> Add Comment
>
> ```
#### Step 5: Call `addComment` to add a comment
* Call this method to add a comment to selected text in the SuperDoc editor.
* Params: [`AddCommentArgs`](/docs/api-reference/sdk/models/data-models#addcommentargs-1). It has the following properties:
* `instance`: SuperDoc editor instance returned by `new SuperDoc(...)`.
* Returns: [`Promise`](/docs/api-reference/sdk/models/data-models#addcommentresult-1). It returns `null` if no text is selected or Velt is not loaded.
> [tab] React / Next.js
>
> ```tsx theme={null}
> import { addComment } from '@veltdev/superdoc-velt-comments';
>
> const result = await addComment({ instance });
> ```
To scope comments to a specific editor on pages with multiple SuperDoc instances, pass an editor id when attaching the extension:
```tsx theme={null}
SuperDocVeltComments.configure({ editorId: 'EDITOR_ID' }).attach(superdoc);
```
#### Step 6: Render comments in the SuperDoc editor
* Get the comment data from Velt SDK and render it in the SuperDoc editor.
* Params: [`RenderCommentsArgs`](/docs/api-reference/sdk/models/data-models#rendercommentsargs-1). It has the following properties:
* `instance`: SuperDoc editor instance.
* `commentAnnotations`: Array of Comment Annotation objects.
> [tab] React / Next.js
>
> ```tsx theme={null}
> import { useEffect } from 'react';
> import { useCommentAnnotations } from '@veltdev/react';
> import { renderComments } from '@veltdev/superdoc-velt-comments';
>
> const commentAnnotations = useCommentAnnotations();
>
> useEffect(() => {
> if (!instance) return;
>
> renderComments({
> instance,
> commentAnnotations: commentAnnotations ?? [],
> });
> }, [instance, commentAnnotations]);
> ```
Highlights are view-only. The library re-derives each highlight from its [`TextEditorConfig`](/docs/api-reference/sdk/models/data-models#texteditorconfig-5) anchor and remaps live ranges as the document changes. You do not need to call `renderComments` on every edit, scroll, zoom, or resize. Re-run it when Velt's annotation list changes.
#### Step 7: Clean up the SuperDoc extension
`SuperDocVeltComments.configure(...).attach(instance)` returns an [`AttachedExtension`](/docs/api-reference/sdk/models/data-models#attachedextension-1). Call `detach()` in your effect cleanup to remove listeners, clear per-instance state, and remove overlay elements before destroying the editor.
```tsx theme={null}
return () => {
extensionRef.current?.detach();
extensionRef.current = null;
superdocRef.current?.destroy();
};
```
#### Step 8: Style the commented text
* You can style commented text by adding CSS for the `velt-comment-text` element.
* SuperDoc highlights are light-DOM overlay elements inside `div.velt-superdoc-overlay-root`, so a global stylesheet can reach them.
* The default highlight rules use inline `!important` styles, so overrides should use `!important`.
```css theme={null}
velt-comment-text {
background-color: rgba(255, 212, 0, 0.4) !important;
border-bottom: 2px solid #ffd400 !important;
cursor: pointer;
}
velt-comment-text:hover {
background-color: rgba(255, 212, 0, 0.6) !important;
}
velt-comment-text[comment-selected="true"],
velt-comment-text.velt-comment-selected {
background-color: rgba(255, 212, 0, 0.7) !important;
}
```
## Complete Example
[https://sample-apps-superdoc-comments-demo.vercel.app/](https://sample-apps-superdoc-comments-demo.vercel.app/)
## APIs
#### [SuperDocVeltComments](/docs/api-reference/sdk/api/api-methods#superdocveltcomments)
Creates the Velt Comments extension for a SuperDoc editor. Use `SuperDocVeltComments.configure(...).attach(instance)` to attach it to an editor instance.
* Config: [`SuperDocVeltCommentsConfig`](/docs/api-reference/sdk/models/data-models#superdocveltcommentsconfig)
* Returns: `SuperDocVeltComments`
> [tab] React / Next.js
>
> ```tsx theme={null}
> import { SuperDocVeltComments } from '@veltdev/superdoc-velt-comments';
>
> const attached = SuperDocVeltComments
> .configure({ editorId: 'my-doc' })
> .attach(superdoc);
>
> attached.detach();
> ```
#### [addComment()](/docs/api-reference/sdk/api/api-methods#addcomment-12)
Creates a comment annotation for the currently selected text in the SuperDoc editor.
* Signature: `async (args: AddCommentArgs) => Promise`
* Params: `args:` [`AddCommentArgs`](/docs/api-reference/sdk/models/data-models#addcommentargs-1)
* Returns: `Promise`; see [`AddCommentResult`](/docs/api-reference/sdk/models/data-models#addcommentresult-1).
> [tab] React / Next.js
>
> ```tsx theme={null}
> import { addComment } from '@veltdev/superdoc-velt-comments';
>
> const result = await addComment({ instance });
> ```
#### [renderComments()](/docs/api-reference/sdk/api/api-methods#rendercomments-12)
Renders and updates Velt comment highlights in the SuperDoc editor.
* Signature: `(args:` [`RenderCommentsArgs`](/docs/api-reference/sdk/models/data-models#rendercommentsargs-1)`) => void`
* Params: `args:` [`RenderCommentsArgs`](/docs/api-reference/sdk/models/data-models#rendercommentsargs-1)
* Returns: `void`
> [tab] React / Next.js
>
> ```tsx theme={null}
> import { renderComments } from '@veltdev/superdoc-velt-comments';
>
> renderComments({
> instance,
> commentAnnotations: annotations ?? [],
> });
> ```
# Text Setup
Source: https://velt.dev/docs/async-collaboration/comments/setup/text

> [tab] React / Next.js
>
> ## 1. Import Comment components
>
> Import the `VeltComments` component.
>
> ```js theme={null}
> import { VeltProvider, VeltComments } from '@veltdev/react';
> ```
>
> ## 2. Add Comment component with Text mode
>
> Add the `VeltComments` component to the root of your app.
>
> This component is required to render comments in your app.
>
> Text mode is enabled by default. To disable it, set the `textMode` attribute to `false`.
>
> Text mode allows users to select any text and attach comments to it similar to Google Docs.
>
> ```js theme={null}
>
>
>
> ```
>
> ## 3. Test Integration
>
> Test it out by opening the page with Velt components in your browser.
>
> Select any text, a `Comment Tool` button will appear near the highlighted text. Click on it to add a comment.
>
> 
> [tab] Other Frameworks
>
> ## 1. Add Comment component with Text mode
>
> Add the comment component to your template. Try to put it as close to the root level of your ``.
>
> This component is required to render comments in your app. Text mode allows users to attach comments to highlighted text.
>
> ```html theme={null}
>
>
>
> ```
>
> ## 2. Test Integration
>
> Test it out by opening the page with Velt components in your browser.
>
> Select any text, a `Comment Tool` button will appear near the highlighted text. Click on it to add a comment.
>
> 
```jsx React / Next.js theme={null}
import { VeltProvider, VeltComments } from '@veltdev/react';
export default function App() {
return (
);
}
```
```html HTML theme={null}
Comment documentation
```
# TinyMCE Setup
Source: https://velt.dev/docs/async-collaboration/comments/setup/tinymce
Add Velt text comments to a TinyMCE editor with the Velt TinyMCE comments plugin.

The TinyMCE integration renders comment highlights as view-only overlay elements positioned over the commented text. It does not modify your TinyMCE content, schema, undo history, or saved HTML.
## Setup
#### Step 1: Add Comment components
* Add the `Velt Comments` component to the root of your app. This component is required to create and render comments in your app.
* Authenticate the user with `authProvider` and set the Velt document before users add comments.
* Set the `textMode` prop to `false` to hide the default Velt text comment tool. TinyMCE selections are handled by `@veltdev/tinymce-velt-comments`.
* Add `VeltCommentsSidebar` if you want a Google Docs-style comment sidebar.
> [tab] React / Next.js
>
> ```tsx theme={null}
> import { VeltComments, VeltCommentsSidebar, VeltProvider, useSetDocument } from '@veltdev/react';
>
> const user = {
> userId: 'user-1',
> organizationId: 'org-1',
> name: 'User One',
> email: 'user@example.com',
> };
>
> function VeltSetup() {
> useSetDocument('document-id', { documentName: 'Document name' });
> return null;
> }
>
> function App() {
> return (
>
>
>
>
> {/* Your app content */}
>
> );
> }
> ```
> [tab] Other Frameworks
>
> ```html theme={null}
>
>
>
> ```
#### Step 2: Install the Velt TinyMCE extension
> [tab] React / Next.js
>
> ```bash theme={null}
> npm i @veltdev/tinymce-velt-comments @tinymce/tinymce-react tinymce
> ```
> [tab] Other Frameworks
>
> ```bash theme={null}
> npm i @veltdev/tinymce-velt-comments @veltdev/client tinymce
> ```
`tinymce` is a peer dependency and must be provided by your TinyMCE app. Import the self-hosted TinyMCE assets used by your editor so `@tinymce/tinymce-react` and the Velt plugin use the same TinyMCE instance.
#### Step 3: Configure the TinyMCE editor with the Velt Comments plugin
Add `VeltCommentsPlugin` to the TinyMCE `plugins` list and set `velt_comments_editor_id` in the editor init options. Capture the TinyMCE editor instance from `onInit` or the `init` event, then render Velt comment annotations into the editor with `renderComments`.
> [tab] React / Next.js
>
> ```tsx theme={null}
> import { useEffect, useState } from 'react';
> import { Editor as TinyMCEReact } from '@tinymce/tinymce-react';
> import { useCommentAnnotations } from '@veltdev/react';
> import type { Editor as TinyMCEEditor } from 'tinymce';
> import { VeltCommentsPlugin, renderComments } from '@veltdev/tinymce-velt-comments';
>
> import 'tinymce';
> import 'tinymce/icons/default';
> import 'tinymce/themes/silver';
> import 'tinymce/models/dom';
> import 'tinymce/plugins/lists';
> import 'tinymce/plugins/link';
> import 'tinymce/skins/ui/oxide/skin.min.css';
> import contentUiCss from 'tinymce/skins/ui/oxide/content.min.css?raw';
> import contentCss from 'tinymce/skins/content/default/content.min.css?raw';
>
> const EDITOR_ID = 'my-editor';
>
> function TinyMCEEditor() {
> const [editor, setEditor] = useState(null);
> const annotations = useCommentAnnotations();
>
> useEffect(() => {
> if (!editor) return;
>
> renderComments({
> editor,
> editorId: EDITOR_ID,
> commentAnnotations: annotations ?? [],
> });
> }, [editor, annotations]);
>
> return (
> licenseKey="gpl"
> initialValue="Select text, then add a comment.
"
> init={{
> license_key: 'gpl',
> skin: false,
> content_css: false,
> content_style: `${contentUiCss}\n${contentCss}`,
> plugins: ['lists', 'link', VeltCommentsPlugin],
> toolbar: 'undo redo | bold italic | bullist numlist | link | addveltcomment',
> velt_comments_editor_id: EDITOR_ID,
> }}
> onInit={(_event, nextEditor) => setEditor(nextEditor)}
> />
> );
> }
> ```
> [tab] Other Frameworks
>
> ```js theme={null}
> import tinymce from 'tinymce';
> import { VeltCommentsPlugin } from '@veltdev/tinymce-velt-comments';
>
> let editor;
>
> tinymce.init({
> selector: '#editor',
> license_key: 'gpl',
> plugins: [VeltCommentsPlugin],
> toolbar: 'undo redo | bold italic | addveltcomment',
> velt_comments_editor_id: 'my-editor',
> setup: (nextEditor) => {
> nextEditor.on('init', () => {
> editor = nextEditor;
> });
> },
> });
> ```
> [!TIP]
>
> The package registers a TinyMCE plugin named `veltcomments`. You can pass the exported `VeltCommentsPlugin` constant in `plugins`, or use the string `'veltcomments'` after the package has been imported. It also registers a TinyMCE toolbar button named `addveltcomment`.
#### Step 4: Add a comment button to your TinyMCE editor
Add a button that users can click to add comments after selecting text in the TinyMCE editor.
**Important:** Use `onMouseDown` with `preventDefault()` so the browser does not move focus away from the editor before `addComment` reads the current selection. Keep the actual `addComment` call in `onClick`.
> [tab] React / Next.js
>
> ```tsx theme={null}
> import { addComment } from '@veltdev/tinymce-velt-comments';
>
> const handleAddComment = () => {
> if (!editor) return;
>
> void addComment({
> editor,
> editorId: EDITOR_ID,
> });
> };
>
> onMouseDown={(event) => event.preventDefault()}
> onClick={handleAddComment}
> >
> Add Comment
>
> ```
> [tab] Other Frameworks
>
> ```html theme={null}
>
>
> ```
>
> ```js theme={null}
> import { addComment } from '@veltdev/tinymce-velt-comments';
>
> const addCommentButton = document.querySelector('#add-comment');
>
> addCommentButton.addEventListener('mousedown', (event) => {
> event.preventDefault();
> });
>
> addCommentButton.addEventListener('click', () => {
> void addComment({ editor, editorId: 'my-editor' });
> });
> ```
#### Step 5: Call `addComment` to add a comment
* Call this method to add a comment to selected text in the TinyMCE editor.
* Params: [`AddCommentRequest`](/docs/api-reference/sdk/models/data-models#addcommentrequest-9). It has the following properties:
* `editor`: TinyMCE `Editor` instance.
* `editorId`: Id of the editor. Use this if you have multiple TinyMCE editors on the same page. (optional)
* `context`: Add custom metadata to the Comment Annotation. [Learn more](/docs/async-collaboration/comments/customize-behavior#metadata). (optional)
> [tab] React / Next.js
>
> ```tsx theme={null}
> import { addComment } from '@veltdev/tinymce-velt-comments';
>
> const addCommentRequest = {
> editor,
> editorId: 'EDITOR_ID',
> context: {
> storyId: 'story-id',
> storyName: 'story-name',
> },
> };
>
> void addComment(addCommentRequest);
> ```
> [tab] Other Frameworks
>
> ```js theme={null}
> import { addComment } from '@veltdev/tinymce-velt-comments';
>
> const addCommentRequest = {
> editor,
> editorId: 'EDITOR_ID',
> context: {
> storyId: 'story-id',
> storyName: 'story-name',
> },
> };
>
> void addComment(addCommentRequest);
> ```
The library automatically writes `context.textEditorConfig` with the selected text, its 1-based occurrence index in the document, and the editor ID when one is provided. If the editor is inside an element with `data-velt-location-id`, that value is sent to Velt as the annotation location.
#### Step 6: Render comments in TinyMCE editor
* Get the comment data from Velt SDK and render it in the TinyMCE editor.
* Params: [`RenderCommentsRequest`](/docs/api-reference/sdk/models/data-models#rendercommentsrequest-9). It has the following properties:
* `editor`: TinyMCE `Editor` instance.
* `editorId`: Id of the editor. Use this if you have multiple TinyMCE editors on the same page. (optional)
* `commentAnnotations`: Array of Comment Annotation objects.
> [tab] React / Next.js
>
> ```tsx theme={null}
> import { useEffect } from 'react';
> import { useCommentAnnotations } from '@veltdev/react';
> import { renderComments } from '@veltdev/tinymce-velt-comments';
>
> const commentAnnotations = useCommentAnnotations();
>
> useEffect(() => {
> if (!editor) return;
>
> renderComments({
> editor,
> editorId: 'EDITOR_ID',
> commentAnnotations: commentAnnotations ?? [],
> });
> }, [editor, commentAnnotations]);
> ```
> [tab] Other Frameworks
>
> ```js theme={null}
> import { renderComments } from '@veltdev/tinymce-velt-comments';
>
> const commentElement = Velt.getCommentElement();
> commentElement.getAllCommentAnnotations().subscribe((annotations) => {
> renderComments({
> editor,
> editorId: 'EDITOR_ID',
> commentAnnotations: annotations,
> });
> });
> ```
`renderComments` filters annotations by `context.textEditorConfig.editorId`. Resolved comments with `status.type === 'terminal'` are hidden unless they are currently selected in Velt.
#### Step 7: Re-apply TinyMCE comment highlights (optional)
* TinyMCE renders comment highlights as view-only overlay elements in the outer document.
* The integration does not write Velt comment marks into your TinyMCE content or undo history.
* Save your TinyMCE content normally. After you recreate the editor or replace content with `editor.setContent(...)`, call `renderComments` again.
```ts theme={null}
const html = editor.getContent();
// Save html to your backend.
renderComments({
editor,
editorId: 'EDITOR_ID',
commentAnnotations,
});
```
#### Step 8: Style the commented text
* You can style the commented text by adding CSS for the `velt-comment-text` element.
* TinyMCE highlights are overlay elements in the outer document, not inside the editor iframe, so add this CSS to your page stylesheet instead of `content_style`.
```css theme={null}
velt-comment-text {
background-color: rgba(255, 212, 0, 0.4);
border-bottom: 2px solid #ffd400;
cursor: pointer;
}
velt-comment-text:hover {
background-color: rgba(255, 212, 0, 0.6);
}
velt-comment-text[comment-selected="true"],
velt-comment-text.velt-comment-selected {
background-color: rgba(255, 212, 0, 0.7);
}
```
#### Using TinyMCE without React
For a vanilla TinyMCE app, initialize Velt with `@veltdev/client`, add the Velt comments web component to the page, and subscribe to annotations through the Velt comment element.
```bash theme={null}
npm install @veltdev/client
```
```html theme={null}
```
```ts theme={null}
import { initVelt } from '@veltdev/client';
import tinymce from 'tinymce';
import {
VeltCommentsPlugin,
addComment,
renderComments,
} from '@veltdev/tinymce-velt-comments';
const EDITOR_ID = 'my-editor';
const velt = await initVelt('YOUR_API_KEY');
await velt.identify({
userId: 'user-1',
organizationId: 'org-1',
name: 'User One',
email: 'user@example.com',
});
velt.setDocument('document-id', { documentName: 'Document name' });
const [editor] = await tinymce.init({
selector: '#editor',
license_key: 'gpl',
plugins: [VeltCommentsPlugin],
toolbar: 'bold italic | addveltcomment',
velt_comments_editor_id: EDITOR_ID,
});
document.getElementById('add-comment-btn')?.addEventListener('mousedown', (event) => {
event.preventDefault();
});
document.getElementById('add-comment-btn')?.addEventListener('click', () => {
void addComment({ editor, editorId: EDITOR_ID });
});
velt.getCommentElement()?.getAllCommentAnnotations().subscribe((annotations) => {
renderComments({ editor, editorId: EDITOR_ID, commentAnnotations: annotations });
});
```
#### Multiple TinyMCE editors
When using multiple editors on the same page, provide a unique `editorId` to TinyMCE's `velt_comments_editor_id` init option, `addComment`, and `renderComments`.
```ts theme={null}
const [editor1] = await tinymce.init({
target: document.querySelector('#editor-1') as HTMLElement,
license_key: 'gpl',
plugins: [VeltCommentsPlugin],
toolbar: 'addveltcomment',
velt_comments_editor_id: 'editor-1',
});
const [editor2] = await tinymce.init({
target: document.querySelector('#editor-2') as HTMLElement,
license_key: 'gpl',
plugins: [VeltCommentsPlugin],
toolbar: 'addveltcomment',
velt_comments_editor_id: 'editor-2',
});
await addComment({ editor: editor1, editorId: 'editor-1' });
await addComment({ editor: editor2, editorId: 'editor-2' });
renderComments({
editor: editor1,
editorId: 'editor-1',
commentAnnotations,
});
renderComments({
editor: editor2,
editorId: 'editor-2',
commentAnnotations,
});
```
#### TypeScript support
The package includes TypeScript definitions. Key type exports:
```ts theme={null}
import type {
AddCommentRequest,
RenderCommentsRequest,
TinymceVeltCommentsConfig,
CommentAnnotationContext,
} from '@veltdev/tinymce-velt-comments';
import type { CommentAnnotation } from '@veltdev/types';
```
Runtime exports:
```ts theme={null}
import {
VeltCommentsPlugin,
registerVeltCommentsPlugin,
addComment,
renderComments,
} from '@veltdev/tinymce-velt-comments';
```
## Complete Example
[https://sample-apps-tinymce-comments-demo.vercel.app/](https://sample-apps-tinymce-comments-demo.vercel.app/)
## APIs
#### [VeltCommentsPlugin](/docs/api-reference/sdk/api/api-methods#veltcommentsplugin-1)
The registered TinyMCE plugin name (`'veltcomments'`) that powers Velt comments. Importing the library registers it; add it to the TinyMCE editor's `plugins` list.
**Init options:**
* `velt_comments_editor_id?: string` - Unique identifier for this editor instance.
* `velt_comments_persist_marks?: boolean` - Reserved for API parity; highlights are always rendered as view-only overlays.
> [tab] React / Next.js
>
> ```tsx theme={null}
> import { VeltCommentsPlugin } from '@veltdev/tinymce-velt-comments';
>
> licenseKey="gpl"
> init={{
> license_key: 'gpl',
> plugins: ['lists', 'link', VeltCommentsPlugin],
> toolbar: 'bold italic | addveltcomment',
> velt_comments_editor_id: 'my-editor',
> }}
> />
> ```
> [tab] Other Frameworks
>
> ```js theme={null}
> import { VeltCommentsPlugin } from '@veltdev/tinymce-velt-comments';
>
> tinymce.init({
> selector: '#editor',
> license_key: 'gpl',
> plugins: [VeltCommentsPlugin],
> toolbar: 'bold italic | addveltcomment',
> velt_comments_editor_id: 'my-editor',
> });
> ```
#### [registerVeltCommentsPlugin()](/docs/api-reference/sdk/api/api-methods#registerveltcommentsplugin)
Explicitly registers the `veltcomments` plugin with a TinyMCE instance. Importing the package auto-registers the plugin when a TinyMCE instance is available; use this method when TinyMCE is loaded or provided later.
**Parameters:**
* `instance?: TinyMCE` - TinyMCE instance to register against.
**Returns:** `void`
```ts theme={null}
import tinymce from 'tinymce';
import { registerVeltCommentsPlugin } from '@veltdev/tinymce-velt-comments';
registerVeltCommentsPlugin(tinymce);
```
#### [addComment()](/docs/api-reference/sdk/api/api-methods#addcomment-10)
Creates a Velt comment annotation for the currently selected TinyMCE text.
* Signature: `async (request:` [`AddCommentRequest`](/docs/api-reference/sdk/models/data-models#addcommentrequest-9)`) => Promise`
* Params: `request:` [`AddCommentRequest`](/docs/api-reference/sdk/models/data-models#addcommentrequest-9)
* Returns: `Promise`
> [tab] React / Next.js
>
> ```tsx theme={null}
> import { addComment } from '@veltdev/tinymce-velt-comments';
>
> const handleAddComment = () => {
> if (!editor) return;
> void addComment({ editor, editorId: 'my-editor' });
> };
>
> onMouseDown={(event) => event.preventDefault()}
> onClick={handleAddComment}
> >
> Comment
>
> ```
> [tab] Other Frameworks
>
> ```js theme={null}
> import { addComment } from '@veltdev/tinymce-velt-comments';
>
> void addComment({
> editor,
> editorId: 'my-editor',
> context: { customData: 'value' },
> });
> ```
#### [renderComments()](/docs/api-reference/sdk/api/api-methods#rendercomments-10)
Resolves Velt comment annotations back to TinyMCE DOM ranges and renders stable `` overlay elements for the visible comments.
* Signature: `(request:` [`RenderCommentsRequest`](/docs/api-reference/sdk/models/data-models#rendercommentsrequest-9)`) => void`
* Params: `request:` [`RenderCommentsRequest`](/docs/api-reference/sdk/models/data-models#rendercommentsrequest-9)
* Returns: `void`
> [tab] React / Next.js
>
> ```tsx theme={null}
> import { useEffect } from 'react';
> import { useCommentAnnotations } from '@veltdev/react';
> import { renderComments } from '@veltdev/tinymce-velt-comments';
>
> const annotations = useCommentAnnotations();
>
> useEffect(() => {
> if (!editor) return;
>
> renderComments({
> editor,
> editorId: 'my-editor',
> commentAnnotations: annotations ?? [],
> });
> }, [editor, annotations]);
> ```
> [tab] Other Frameworks
>
> ```js theme={null}
> import { renderComments } from '@veltdev/tinymce-velt-comments';
>
> const commentElement = Velt.getCommentElement();
> commentElement.getAllCommentAnnotations().subscribe((annotations) => {
> renderComments({
> editor,
> editorId: 'my-editor',
> commentAnnotations: annotations,
> });
> });
> ```
# Tiptap Setup
Source: https://velt.dev/docs/async-collaboration/comments/setup/tiptap

## Setup
#### Step 1: Add Comment components
* Add the `Velt Comments` component to the root of your app.
* This component is required to render comments in your app.
* Set the `text mode` prop to `false` to hide the default text comment tool.
> [tab] React / Next.js
>
> ```js theme={null}
>
>
>
> ```
> [tab] Other Frameworks
>
> ```html theme={null}
>
>
>
> ```
#### Step 2: Install the Velt Tiptap extension
```bash theme={null}
npm i @veltdev/tiptap-velt-comments
```
#### Step 3: Configure the Tiptap editor with the Velt Comments extension
> [tab] React / Next.js
>
> ```js theme={null}
> import { TiptapVeltComments } from '@veltdev/tiptap-velt-comments';
>
> const editor = new Editor({
> extensions: [
> TiptapVeltComments,
> // ... other extensions
> ],
> });
> ```
> [tab] Other Frameworks
>
> ```js theme={null}
> import { TiptapVeltComments } from '@veltdev/tiptap-velt-comments';
>
> const editor = new Editor({
> extensions: [
> TiptapVeltComments,
> // ... other extensions
> ],
> });
> ```
#### Step 4: Add a comment button to your Tiptap editor
Add a button in your existing bubble menu or create a new bubble menu that appears when users select text in the editor.
> [tab] React / Next.js
>
> ```js theme={null}
> import { BubbleMenu, EditorContent, useEditor } from '@tiptap/react';
> import { addComment } from '@veltdev/tiptap-velt-comments';
>
> export default function TipTapComponent() {
> const editor = useEditor({
> // ... your editor configuration
> });
>
> const addTiptapVeltComment = () => {
> if (editor) {
> addComment({ editor });
> }
> };
>
> return (
>
>
>
> {/* Bubble Menu for Comments */}
> {editor && (
>
>
>
className="comment-button"
> onClick={(e) => {
> e.preventDefault();
> e.stopPropagation();
> addTiptapVeltComment();
> }}
> title="Add comment"
> >
>
> d="M10 17.25H4C3.30964 17.25 2.75 16.6904 2.75 16V10C2.75 5.99594 5.99594 2.75 10 2.75C14.0041 2.75 17.25 5.99594 17.25 10C17.25 14.0041 14.0041 17.25 10 17.25Z"
> strokeWidth="1.5"
> />
>
>
>
>
> )}
>
> );
> }
> ```
> [tab] Other Frameworks
>
> ```html theme={null}
>
>
>
> ```
>
> ```js theme={null}
> import { BubbleMenu, Editor } from '@tiptap/core';
> import { addComment } from '@veltdev/tiptap-velt-comments';
>
> const editor = new Editor({
> element: document.querySelector('#editor'),
> // ... your editor configuration
> });
>
> const addTiptapVeltComment = () => {
> if (editor) {
> addComment({ editor });
> }
> };
>
> // Create bubble menu
> const bubbleMenu = new BubbleMenu({
> editor,
> element: document.querySelector('.bubble-menu'),
> tippyOptions: { duration: 100 },
> });
>
> // Add click handler to comment button
> document.querySelector('.comment-button').addEventListener('click', (e) => {
> e.preventDefault();
> e.stopPropagation();
> addTiptapVeltComment();
> });
> ```
> [!TIP]
>
> Refer to the [Tiptap BubbleMenu documentation](https://tiptap.dev/docs/editor/extensions/functionality/bubble-menu) to learn more about customizing the bubble menu behavior.
#### Step 5: Call `addComment` to add a comment
* Call this method to add a comment to selected text in the Tiptap editor. You can use this when the user clicks on the comment button in context menu or presses a keyboard shortcut.
* Params: [`AddCommentRequest`](/docs/api-reference/sdk/models/data-models#addcommentrequest-1). It has the following properties:
* `editor`: instance of the Tiptap editor.
* `editorId`: Id of the tiptap editor. Use this if you have multiple tiptap editors on the same page in your app. (optional)
* `context`: Add any custom metadata to the Comment Annotation. [Learn more](/docs/async-collaboration/comments/customize-behavior#metadata). (optional)
> [tab] React / Next.js
>
> ```js theme={null}
> import { addComment } from '@veltdev/tiptap-velt-comments';
>
> const addCommentRequest = {
> editor,
> editorId: 'EDITOR_ID',
> context: {
> storyId: 'story-id',
> storyName: 'story-name',
> },
> };
>
> addComment(addCommentRequest);
> ```
> [tab] Other Frameworks
>
> ```js theme={null}
> import { addComment } from '@veltdev/tiptap-velt-comments';
>
> const addCommentRequest = {
> editor,
> editorId: 'EDITOR_ID',
> context: {
> storyId: 'story-id',
> storyName: 'story-name',
> },
> };
>
> addComment(addCommentRequest);
> ```
#### Step 6: Render comments in Tiptap editor
* Get the comment data from Velt SDK and render it in the Tiptap Editor.
* Params: [`RenderCommentsRequest`](/docs/api-reference/sdk/models/data-models#rendercommentsrequest-1). It has the following properties:
* `editor`: Instance of the Tiptap editor.
* `editorId`: Id of the tiptap editor. Use this if you have multiple tiptap editors on the same page in your app. (optional)
* `commentAnnotations`: Array of Comment Annotation objects.
> [tab] React / Next.js
>
> ```js theme={null}
> import { renderComments } from '@veltdev/tiptap-velt-comments';
>
> const annotations = useCommentAnnotations();
>
> useEffect(() => {
> if (editor && annotations?.length) {
> const renderCommentsRequest = {
> editor,
> editorId: 'EDITOR_ID',
> annotations,
> };
> renderComments(renderCommentsRequest);
> }
> }, [editor, annotations]);
> ```
> [tab] Other Frameworks
>
> ```js theme={null}
> import { renderComments } from '@veltdev/tiptap-velt-comments';
>
> const commentElement = Velt.getCommentElement();
> commentElement.getAllCommentAnnotations().subscribe((annotations) => {
> if (editor && annotations?.length) {
> const renderCommentsRequest = {
> editor,
> editorId: 'EDITOR_ID',
> commentAnnotations: annotations,
> };
> renderComments(renderCommentsRequest);
> }
> });
> ```
#### Step 7: Persist Velt Comment Marks (optional)
* By default, Velt comment marks (``) are persisted in the Tiptap editor by Velt SDK. When the editor loads and the velt sdk initializes, the marks will be automatically added to the editor by us.
* If you plan to store the contents of the tiptap editor as raw html on your end then you should turn off this feature since you will already be storing the Velt comment marks.
* Default: `true`
```js theme={null}
const editor = new Editor({
extensions: [
TiptapVeltComments.configure({
persistVeltMarks: false
}),
// ... other extensions
],
});
```
#### Step 8: Style the commented text
* You can style the commented text by adding a CSS class to the `velt-comment-text` element.
* By using the `comment-available` attribute, you can apply styles only when the comment data has loaded.
```css theme={null}
velt-comment-text[comment-available="true"] {
background-color: #ffff00;
}
```
## Complete Example
[https://documentation-app-demo.vercel.app/](https://documentation-app-demo.vercel.app/)
## APIs
#### [TiptapVeltComments.configure()](/docs/api-reference/sdk/api/api-methods#tiptapveltcomments-configure)
A custom Tiptap extension for Velt comments.
* Params: `options?:` [TiptapVeltCommentsOptions](/docs/api-reference/sdk/models/data-models#tiptapveltcommentsoptions)
* Returns: `TiptapVeltComments`
> [tab] React / Next.js
>
> ```tsx theme={null}
> import { useEditor } from '@tiptap/react';
> import StarterKit from '@tiptap/starter-kit';
> import { TiptapVeltComments } from '@veltdev/tiptap-velt-comments';
>
> const editor = useEditor({
> extensions: [
> StarterKit,
> TiptapVeltComments.configure({
> editorId: 'my-editor',
> persistVeltMarks: true,
> }),
> ],
> content: 'Your content
',
> });
> ```
> [tab] Other Frameworks
>
> ```tsx theme={null}
> import { Editor } from '@tiptap/core';
> import StarterKit from '@tiptap/starter-kit';
> import { TiptapVeltComments } from '@veltdev/tiptap-velt-comments';
>
> const editor = new Editor({
> element: document.querySelector('#editor'),
> extensions: [
> StarterKit,
> TiptapVeltComments.configure({
> editorId: 'my-editor',
> persistVeltMarks: true,
> }),
> ],
> content: 'Your content
',
> });
> ```
#### [addComment()](/docs/api-reference/sdk/api/api-methods#addcomment-2)
Creates a comment annotation for the currently selected text in the editor.
* Params:
* `request:` [AddCommentRequest](/docs/api-reference/sdk/models/data-models#addcommentrequest)
* `editor: Editor`
* `editorId?: string`
* `context?: object`
* Returns: `Promise`
> [tab] React / Next.js
>
> ```tsx theme={null}
> import { addComment } from '@veltdev/tiptap-velt-comments';
>
> onMouseDown={(e) => {
> e.preventDefault();
> addComment({
> editor,
> editorId: 'my-editor',
> context: { customData: 'value' }
> });
> }}
> >
> Comment
>
> ```
> [tab] Other Frameworks
>
> ```tsx theme={null}
> import { addComment } from '@veltdev/tiptap-velt-comments';
>
> addComment({
> editor,
> editorId: 'my-editor',
> context: { customData: 'value' },
> });
> ```
#### [renderComments()](/docs/api-reference/sdk/api/api-methods#rendercomments-2)
Renders and highlights comment annotations in the editor.
* Params:
* `request:` [RenderCommentsRequest](/docs/api-reference/sdk/models/data-models#rendercommentsrequest)
* `editor: Editor`
* `editorId?: string`
* `commentAnnotations?:` [CommentAnnotation\[\]](/docs/api-reference/sdk/models/data-models#commentannotation)
* Returns: `void`
> [tab] React / Next.js
>
> ```tsx theme={null}
> import { useEffect } from 'react';
> import { renderComments } from '@veltdev/tiptap-velt-comments';
> import { useCommentAnnotations } from '@veltdev/react';
>
> const annotations = useCommentAnnotations();
>
> useEffect(() => {
> if (editor && annotations) {
> renderComments({
> editor,
> editorId: 'my-editor',
> commentAnnotations: annotations,
> });
> }
> }, [editor, annotations]);
> ```
> [tab] Other Frameworks
>
> ```tsx theme={null}
> import { renderComments } from '@veltdev/tiptap-velt-comments';
>
> const commentElement = Velt.getCommentElement();
> commentElement.getAllCommentAnnotations().subscribe((annotations) => {
> if (editor && annotations) {
> renderComments({
> editor,
> editorId: 'my-editor',
> commentAnnotations: annotations,
> });
> }
> });
> ```
# Custom Video Player Setup
Source: https://velt.dev/docs/async-collaboration/comments/setup/video-player-setup/custom-video-player-setup
Use this guide to add collaboration into your own custom video player.

## Setup
### Step 1: Set up Velt Components in your app
You will be using the following components:
* `Velt Comments`: Renders comments on the DOM.
* `Velt Comment Tool`: Enables or disables adding comments.
* `Velt Reaction Tool`: Enables or disables adding reactions.
* `Velt Comment Player Timeline`: Adds comments bubble over your player seek bar.
* `Velt Comments Sidebar`: Adds a sidebar that shows all comments. Users can also search, filter & navigate to the comments from here.
* `Velt Sidebar Button`: Toggles the sidebar on/off.
#### A) Add the `Velt Comments` component in the root of your app
Add the `Velt Comments` component to the root of your app.
> [tab] React / Next.js
>
> ```jsx theme={null}
>
> ```
> [tab] Other Frameworks
>
> ```html theme={null}
>
> ```
#### B) Add the `Velt Comment Tool` component wherever you want your render the comment tool.
Note you can also provide your own button to this component.
> [tab] React / Next.js
>
> ```jsx theme={null}
>
>
> {/* your custom button (optional) */}
>
>
> ```
> [tab] Other Frameworks
>
> ```jsx theme={null}
>
>
>
>
>
> ```
> [!NOTE]
>
> **Disable Comment Tool**
> You can disable the comment tool to temporarily or conditionally restrict comment creation while still allowing users to view existing comments.
>
> > [accordion] See Example
> >
> > > [tab] React / Next.js
> > >
> > > ```jsx theme={null}
> > >
> > >
> > > {/* your custom button (optional) */}
> > >
> > >
> > > ```
> >
> > > [tab] Other Frameworks
> > >
> > > ```html theme={null}
> > >
> > >
> > >
> > >
> > >
> > > ```
#### C) Add the `Velt Reaction Tool` component wherever you want your render the reaction tool.
* Provide the video player ID on which you want the reactions to be added.
* Add an event handler to handle `onReactionToolClick` events.
> [tab] React / Next.js
>
> ```jsx theme={null}
> onReactionToolClick={() => onReactionToolClick()}>
>
> ```
> [tab] Other Frameworks
>
> ```html theme={null}
>
>
>
> ```
>
> ```js theme={null}
> const reactionToolTag = document.querySelector('velt-reaction-tool');
> reactionToolTag.addEventListener('onReactionToolClick', (event) => {
> console.log('reaction tool clicked', event.detail);
> });
> ```
#### D) Place the `Velt Comment Player Timeline` component as a sibling to your video player.
* To show comment bubbles on your player seek bar, add the `Velt Comment Player Timeline` component as a sibling to your video player component.
* It will auto adjust to the same width as your video player.
> [!NOTE]
>
> Right now we assume you have a maximum of one `velt comment player timeline` component and one sibling video player component per `documentID`
> [!WARNING]
>
> Ensure that the parent container of `velt comment player timeline` doesn't have CSS position value as 'static'.
> [!NOTE]
>
> `videoPlayerId` is optional and helps support multiple players/timelines on the same page.
>
> * If omitted, the timeline shows all comments for the current document (for the active version).
> * If provided, the timeline shows only comments whose `location.videoPlayerId` matches the given `videoPlayerId`.
>
> Tip: Use the same id on your player element and when setting `location.videoPlayerId` so the timeline can correctly associate comments with the player.
> [tab] React / Next.js
>
> ```jsx theme={null}
>
>
>
>
> ```
> [tab] Other Frameworks
>
> ```jsx theme={null}
>
>
>
>
> ```
#### E) Add `id` to the video player or its parent element.
* If you don't have access to the raw `` player, you can add an `id` to the parent element of the video player.
> [tab] React / Next.js
>
> ```jsx theme={null}
>
>
>
>
> ```
> [tab] Other Frameworks
>
> ```jsx theme={null}
>
>
>
>
> ```
#### F) Add the `Velt Comments Sidebar` component.
The Comments Sidebar displays all comments with search, filter, and navigation capabilities.
> [tab] React / Next.js
>
> ```jsx theme={null}
>
> ```
> [tab] Other Frameworks
>
> ```jsx theme={null}
>
> ```
> [!NOTE]
>
> **Optional Properties:**
>
> * **`embedMode`**: Embed the sidebar in your existing component instead of floating mode
>
> > [accordion] See Example
> >
> > > [tab] React / Next.js
> > >
> > > ```jsx theme={null}
> > > {/* With optional properties */}
> > > > > embedMode={true}
> > > />
> > > ```
> >
> > > [tab] Other Frameworks
> > >
> > > ```html theme={null}
> > >
> > > > > embed-mode="true"
> > > full-screen="true">
> > >
> > > ```
#### G) Add the `Velt Sidebar Button` component.
This will open or close the Comment Sidebar.
> [tab] React / Next.js
>
> ```jsx theme={null}
>
>
> ```
> [tab] Other Frameworks
>
> ```jsx theme={null}
>
>
> ```
### Step 2: Set the total media length on the Velt Comment Player Timeline
You can pass an integer to `total media length` using props to represent the total number of frames or seconds in the video:
> [tab] React / Next.js
>
> ```jsx theme={null}
>
> ```
> [tab] Other Frameworks
>
> ```jsx theme={null}
>
> ```
Alternatively, you can set this using API method call.
This is useful if you first need to grab the total frames from another method before setting it.
> [tab] React / Next.js
>
> ```jsx theme={null}
> const commentElement = client.getCommentElement();
> commentElement.setTotalMediaLength(120);
> ```
> [tab] Other Frameworks
>
> ```jsx theme={null}
> const commentElement = Velt.getCommentElement();
> commentElement.setTotalMediaLength(120);
> ```
### Step 3: Detect Comment Tool Activation and Set Media Location
* Detect when the user activates the comment tool by adding an event handler to the `onCommentModeChange` event.
* Pause your player and set a new `Location` in the Velt SDK.
* This ensures that the comments are tied to that particular media frame or timestamp.
* You can pass in a key value pair object that represents the current state of your player.
* If you are using the `Velt Comment Player Timeline` component, ensure to set the current media `frame` or `second` in the special key `currentMediaPosition`.
* Use the same id in `location.videoPlayerId` that you used in `VeltCommentPlayerTimeline`.
\[!NOTE] `currentMediaPosition` is a protected keyword that is used to arrange the comment bubbles on top of the video player timeline in the correct spot
> [tab] React / Next.js
>
> ```jsx theme={null}
> onCommentModeChange(mode)} />
>
> const onCommentModeChange = (mode) => {
> // mode will be `true` if the user has activated the comment tool
> // If the comment tool is active, pause the player and set the "location".
> if (mode) {
> // pause player
> setLocation()
> }
> });
>
> const setLocation = async (client) => {
>
> // set currentMediaPosition property on a Location object to represent the current frame
> let location = {
> currentMediaPosition : 120,
> videoPlayerId : "videoPlayerId"
> }
> //set the Location using the client
> await client.setLocations([location])
>
> }
> ```
> [tab] Other Frameworks
>
> ```jsx theme={null}
> const commentElement = Velt.getCommentElement();
> let subscription = commentElement.onCommentModeChange().subscribe((mode) => {
> // mode will be `true` if the user has activated the comment tool
> // If the comment tool is active, pause the player and set the "location".
> if (mode) {
> // pause player
> setLocation()
> }
> });
>
> const setLocation = async (client) => {
> // set currentMediaPosition property on a Location object to represent the current frame
> let location = {
> currentMediaPosition : 120,
> videoPlayerId : "videoPlayerId"
> }
> //set the Location using the client
> await Velt.setLocations([location])
> }
> ```
>
> To unsubscribe from the subscription:
>
> ```jsx theme={null}
> subscription?.unsubscribe()
> ```
### Step 4: Detect Reaction Tool Activation and Set Media Location
* Detect when the user activates the reaction tool by adding an event handler to the `onReactionToolClick` event.
* Pause your player and set a new `Location` in the Velt SDK.
* This ensures that the reactions are tied to that particular media frame or timestamp.
* You can pass in a key value pair object that represents the current state of your player.
If you are using the `Velt Comment Player Timeline` component, ensure to set the current rounded frame or second in the special key `currentMediaPosition`.
\[!NOTE] `currentMediaPosition` is a protected keyword that is used to arrange the comment bubbles on top of the video player timeline in the correct spot
> [tab] React / Next.js
>
> ```jsx theme={null}
>
> onReactionToolClick={() => onReactionToolClick()}>
>
>
> const onReactionToolClick = () => {
> // pause player
> setLocation()
> });
>
> const setLocation = async () => {
> // set currentMediaPosition property on a Location object to represent the current frame
> let location = {
> currentMediaPosition : 120,
> videoPlayerId : "videoPlayerId"
> }
> //set the Location using the client
> await client.setLocations([location])
>
> }
> ```
> [tab] Other Frameworks
>
> ```jsx theme={null}
>
>
> const reactionToolTag = document.querySelector('velt-reaction-tool');
> reactionToolTag.addEventListener('onReactionToolClick', (event) => {
> console.log('reaction tool clicked', event.detail);
> });
> ```
### Step 5: Remove Velt Location when the player is played
Call `unsetLocationsIds()` so the video player can play without comments appearing in frames.
> [tab] React / Next.js
>
> ```jsx theme={null}
> const clearLocation = async () => {
> // Unset all locations, so the video player can play without comments appearing in frames
> await client.unsetLocationsIds()
> }
> ```
> [tab] Other Frameworks
>
> ```jsx theme={null}
> const clearLocation = async () => {
> // Unset all locations, so the video player can play without comments appearing in frames
> await Velt.unsetLocationsIds()
> }
> ```
### Step 6: Navigate to the comment's location in the player from the Sidebar or Timeline
Add the `onCommentClick` event handler on the `Velt Comments Sidebar` & `Velt Comment Player Timeline` components you added earlier.
The event will give you back the `location` object that you had set on the comment.
Use this object to:
* update your player state
* update the SDK's `location` so the comments associated with that `location` are rendered.
#### A) Handle click on the `Velt Comments Sidebar`
> [tab] React / Next.js
>
> ```jsx theme={null}
> onCommentClick(event)} />
>
> const onCommentClick = async (event) => {
> if (event) {
> // Get the location object from the event.
> const { location } = event;
> if (location) {
> // Get the media position where the comment was added.
> const { currentMediaPosition } = location;
> if (currentMediaPosition) {
> // Pause the player.
>
> // Seek to the given comment media position.
>
> // Set the Velt Location to the clicked comment location.
> await client.setLocations([location]);
> }
> }
> }
> }
> ```
> [tab] Other Frameworks
>
> ```jsx theme={null}
> const commentElement = document.querySelector('velt-comments-sidebar');
> commentElement.addEventListener('onCommentClick', onCommentClick);
>
> // event handler for when a comment is clicked on
> const onCommentClick = (event) => {
> if (event) {
> // Get the location object from the event.
> const { location } = event;
> if (location) {
> // Get the media position where the comment was added.
> const { currentMediaPosition } = location;
> if (currentMediaPosition) {
> // Pause the player.
>
> // Seek to the given comment media position.
>
> // Set the Velt Location to the clicked comment location.
> await client.setLocations([location]);
> }
> }
> }
> };
>
> ```
#### B) Handle click on the `Velt Comment Player Timeline`
> [tab] React / Next.js
>
> ```jsx theme={null}
> onTimelineCommentClick(event)} />
>
> const onTimelineCommentClick = async (event) => {
> if (event) {
> // Get the location object from the event.
> const { location } = event;
> if (location) {
> // Get the media position where the comment was added.
> const { currentMediaPosition } = location;
> if (currentMediaPosition) {
> // Pause the player.
>
> // Seek to the given comment media position.
>
> // Set the Velt Location to the clicked comment location.
> await client.setLocations([location]);
> }
> }
> }
> }
> ```
> [tab] Other Frameworks
>
> ```js theme={null}
> const playerTimelineElement = document.querySelector('velt-comment-player-timeline');
> if (playerTimelineElement) {
> playerTimelineElement.addEventListener('onCommentClick', (event) => {
> console.log("onCommentClick: ", event.detail);
> });
> }
> ```
The clicked Comment data will be in the following format:
| property | type | description |
| - | - | - |
| `documentId` | string | The document ID where the comment was added |
| `location` | object | The location where the comment was added |
| `targetElementId` | string | The DOM ID of the target element on which the comment was added |
| `context` | Object | Any context data passed when the comment was added |
# Prebuilt Video Player Setup
Source: https://velt.dev/docs/async-collaboration/comments/setup/video-player-setup/video-player-setup
Use this guide if you want to set up a prebuilt video player from our SDK with collaborative features built in.

> [tab] React / Next.js
>
> **1. Import VeltVideoPlayer component**
>
> Import the `VeltVideoPlayer` component.
>
> ```jsx theme={null}
> import { VeltVideoPlayer} from '@veltdev/react'
> ```
>
> **2. Add src to VeltVideoPlayer**
>
> Add your video src URL to the `src` attribute of the `VeltVideoPlayer` component.
>
> There are a few other properties:
>
> * `darkMode` - boolean to enable dark mode
> * `sync` - boolean to enable sync mode
>
> ```jsx theme={null}
> src={"https://firebasestorage.googleapis.com/v0/b/snippyly.appspot.com/o/external%2Fvelt.mp4?alt=media&token=d8af2697-c797-4610-b886-ca510b231097"}
> darkMode={false}
> sync={true}
> />
> ```
> [tab] Other Frameworks
>
> Add your video src URL to the `src` attribute of the `` component.
>
> There are a few other properties:
>
> * `dark-mode` - boolean to enable dark mode
> * `sync` - boolean to enable sync mode
>
> ```html theme={null}
>
>
> src="http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/Sintel.mp4"
> dark-mode="false"
> sync="true"
> >
>
>
> ```
```jsx React / Next.js theme={null}
import {
VeltVideoPlayer
} from '@veltdev/react';
export default function App() {
return (
);
}
```
```html HTML theme={null}
Video Player documentation
```
# Customize Behavior
Source: https://velt.dev/docs/async-collaboration/comments/standalone-components/comment-composer/customize-behavior
For type definitions, see [`VeltCommentComposerProps`](/docs/api-reference/sdk/models/data-models#veltcommentcomposerprops).
## context
Pass custom context data to comments created via the Comment Composer. The provided context object will be added to the comment annotation, allowing you to associate additional metadata with comments.
> [tab] React / Next.js
>
> ```jsx theme={null}
>
> ```
> [tab] Other Frameworks
>
> ```html theme={null}
>
> ```
## documentId
Set a specific document ID for comments created via the Comment Composer. This allows you to associate comments with a particular document.
> [tab] React / Next.js
>
> ```jsx theme={null}
>
> ```
> [tab] Other Frameworks
>
> ```html theme={null}
>
> ```
## folderId
Set a specific folder ID for comments created via the Comment Composer. This allows you to associate comments with a particular folder.
> [tab] React / Next.js
>
> ```jsx theme={null}
>
> ```
> [tab] Other Frameworks
>
> ```html theme={null}
>
> ```
## locationId
Set a specific location ID for comments created via the Comment Composer. This allows you to associate comments with a particular location.
> [tab] React / Next.js
>
> ```jsx theme={null}
>
> ```
> [tab] Other Frameworks
>
> ```html theme={null}
>
> ```
## placeholder
Customize the input placeholder text in the comment composer. Overrides default placeholders.
> [tab] React / Next.js
>
> ```jsx theme={null}
>
> ```
> [tab] Other Frameworks
>
> ```html theme={null}
>
> ```
## targetComposerElementId
Set a unique identifier for the composer to enable programmatic submission via the submitComment() method.
> [tab] React / Next.js
>
> ```jsx theme={null}
>
> ```
> [tab] Other Frameworks
>
> ```html theme={null}
>
> ```
## clearComposer
Reset composer state including text, attachments, recordings, tagged users, assignments, and custom lists. Refer to [`clearComposer()`](/docs/async-collaboration/comments/customize-behavior#clearcomposer) for more details.
## submitComment
Programmatically submit a comment from a composer. Refer to [`submitComment()`](/docs/async-collaboration/comments/customize-behavior#submitcomment) for more details.
## getComposerData
Get the current state of the composer including text, attachments, recordings, tagged users, assignments, and custom lists. Refer to [`getComposerData()`](/docs/async-collaboration/comments/customize-behavior#getcomposerdata) for more details.
## readOnly
Disable comment input at the component level. When set to `true`, the composer will be in read-only mode.
The component-level `readOnly` prop takes precedence over the global read-only setting when explicitly set.
> [tab] React / Next.js
>
> ```jsx theme={null}
>
> ```
> [tab] Other Frameworks
>
> ```html theme={null}
>
> ```
# Comment Standalone Composer
Source: https://velt.dev/docs/async-collaboration/comments/standalone-components/comment-composer/overview
The Comment Standalone Composer enables you to add comments anywhere in your application. It's designed to work seamlessly with other Velt components and APIs:
* [Comment Data APIs](/docs/async-collaboration/comments/customize-behavior#getcommentannotations): Fetch and submit comment data.
* [Comment Thread](/docs/async-collaboration/comments/standalone-components/comment-thread/overview): Render comment threads using fetched data.
* [Comment Pin](/docs/async-collaboration/comments/standalone-components/comment-pin/overview): Display and position comment pins based on fetched data.
* [Primitive components](/docs/ui-customization/reference/primitives): Use granular components for maximum customization flexibility.
By combining these components, you can create custom comment interfaces such as sidebars, overlays, popovers, or inline comments. This approach offers greater flexibility and control over your comment system's design and functionality.
# Setup
Source: https://velt.dev/docs/async-collaboration/comments/standalone-components/comment-composer/setup
## Add Comment Composer Component
The Comment Composer component allows you to add a comment composer anywhere in your app. You can:
* Display it on a hotkey press
* Embed it in your custom sidebar
* Place it below an article
* Overlay it on an image
* and more...
> [tab] React / Next.js
>
> ```jsx theme={null}
>
> ```
> [tab] Other Frameworks
>
> ```html theme={null}
>
> ```
# Customize Behavior
Source: https://velt.dev/docs/async-collaboration/comments/standalone-components/comment-pin/customize-behavior
## `commentPinClicked` Event
* Listen to when a comment pin is clicked.
* Use this to get information about which pin was clicked and implement custom actions like navigation, analytics tracking, or opening a custom comment dialog.
> [tab] React / Next.js
>
> ```jsx theme={null}
> // Using Hook
> const commentPinClickedEvent = useCommentEventCallback('commentPinClicked');
> useEffect(() => {
> if (commentPinClickedEvent) {
> console.log('Comment pin clicked:', commentPinClickedEvent);
> }
> }, [commentPinClickedEvent]);
>
> // Using API
> const commentElement = client.getCommentElement();
> commentElement.on('commentPinClicked').subscribe((eventData) => {
> console.log('Comment pin clicked:', eventData);
> });
> ```
> [tab] Other Frameworks
>
> ```js theme={null}
> const commentElement = Velt.getCommentElement();
> commentElement.on('commentPinClicked').subscribe((eventData) => {
> console.log('Comment pin clicked:', eventData);
> });
> ```
**Event Data:** [CommentPinClickedEvent](/docs/api-reference/sdk/models/data-models#commentpinclickedevent)
# Comment Pin
Source: https://velt.dev/docs/async-collaboration/comments/standalone-components/comment-pin/overview
The Comment Pin component allows you to manually set the position of Comment Annotations.
This feature is particularly useful for complex UIs where you need precise control over the placement of Comment Pins.
Implementing this feature involves:
**1. Adding comment:** You have two options for adding comments with custom positioning:
* **a. Velt-Managed Click Events:** Use the `onCommentAdd` method to incorporate custom metadata into the comment object. This metadata will be used later to position the Comment Pin. [Learn more](/docs/async-collaboration/comments/customize-behavior#event-subscription#oncommentadd-event-data-schema)
* **b. Custom Click Event Handling:** Handle click events on your canvas and use the `addManualComment` method to create a comment with custom metadata. [Learn more](/docs/async-collaboration/comments/customize-behavior#addmanualcomment)
**2. Retrieving comments data:** Use the `getAllCommentAnnotations` method to fetch all Comment Annotations with their associated custom metadata.
For React developers, we provide hooks for easier integration. [Learn more](/docs/async-collaboration/comments/customize-behavior#getcommentannotations)
**3. Rendering comments Pins:**
Iterate through the retrieved annotations and render the Comment Pin component, using the custom metadata to set each pin's position.
# Setup
Source: https://velt.dev/docs/async-collaboration/comments/standalone-components/comment-pin/setup
## 1. Add custom metadata when comment is added
You have two options for adding comments with custom positioning metadata:
**Option A: Velt-Managed Click Events**
* Use the `onCommentAdd` prop of the VeltComments component to add custom metadata when a comment is added.
* You need to set the mandatory `commentType: 'manual'` property to the metadata object.
> [tab] React / Next.js
>
> ```jsx theme={null}
> yourMethod(event)} />
>
> const yourMethod = (event) => {
> event?.addContext({ position: {x: 200, y: 100}, commentType: 'manual'});
> }
> ```
> [tab] Other Frameworks
>
> ```js theme={null}
> const veltCommentsTag = document.querySelector('velt-comments');
>
> veltCommentsTag?.addEventListener('onCommentAdd', (event) => {
> console.log('*** onCommentAdd ***');
> console.log(event.detail);
> event.detail?.addContext({ position: {x: 200, y: 100}, commentType: 'manual'});
> });
>
> ```
**Option B: Custom Click Event Handling**
* Handle click events on your canvas and use the `addManualComment` method to create a comment with custom metadata.
> [tab] React / Next.js
>
> ```jsx theme={null}
> const context = {
> position: {x: 200, y: 100},
> };
> const commentElement = useCommentUtils();
> commentElement.addManualComment({ context });
> ```
> [tab] Other Frameworks
>
> ```js theme={null}
> const context = {
> position: {x: 200, y: 100},
> };
> const commentElement = Velt.getCommentElement();
> commentElement.addManualComment({ context: context});
> ```
## 2. Retrieve all Comment Annotations
Retrieve all `Comment Annotations` using the `useCommentAnnotations()` hook.
To learn more about the `useCommentAnnotations()` hook, [read here](/docs/api-reference/sdk/api/react-hooks#usegetcommentannotations).
> [tab] React / Next.js
>
> ```jsx theme={null}
> let commentAnnotations = useCommentAnnotations()
> ```
> [tab] Other Frameworks
>
> ```js theme={null}
> const commentElement = Velt.getCommentElement();
> let subscription = commentElement.getAllCommentAnnotations().subscribe((commentAnnotations) => {
> // console.log(commentAnnotations);
> });
> ```
>
> To unsubscribe from the subscription:
>
> ```jsx theme={null}
> subscription?.unsubscribe()
> ```
## 3. Render the Velt Comment Pin component and set the position
Add the `Velt Comment Pin` component and pass in the `Comment Annotation Id`.
Now retrieve the `context` to retrieve the custom metadata you set earlier and use it to set the position of the `Comment Pin`.
> [tab] React / Next.js
>
> ```jsx theme={null}
>
> let commentAnnotations = useCommentAnnotations()
>
> return (
>
> {
> commentAnnotations.map((commentAnnotation) => {
> return (
>
position: 'absolute',
> left: commentAnnotation.context.position.x + dragPosition.x,
> top: commentAnnotation.context.position.y + dragPosition.y,
> transform: 'translate(0%, -100%)'
> }}>
>
>
> )
> })
> }
>
> )
> ```
> [tab] Other Frameworks
>
> ```js theme={null}
> const commentElement = Velt.getCommentElement();
>
> let subscription = commentElement.getAllCommentAnnotations().subscribe((commentAnnotations) => {
> renderCommentAnnotations(commentAnnotations);
> });
>
> const commentsContainer = document.getElementById('comments-container');
>
> function renderCommentAnnotations(commentAnnotations) {
> commentAnnotations.forEach((commentAnnotation) => {
> if (!document.getElementById(`comment-pin-container-${commentAnnotation.annotationId}`)) {
> // Add Comment Pin if it doesn't exist
> const { x, y } = commentAnnotation.context.position;
> var commentPinContainer = document.createElement('div');
> commentPinContainer.className = 'comment-pin-container';
> commentPinContainer.id = `comment-pin-container-${commentAnnotation.annotationId}`;
> commentPinContainer.style.left = x + 'px';
> commentPinContainer.style.top = y + 'px';
> commentPinContainer.innerHTML = ` `;
> commentsContainer?.appendChild(commentPinContainer);
> }
> });
> }
>
> ```
```jsx React / Next.js theme={null}
import { VeltCommentPin, useCommentAnnotations } from '@veltdev/react';
export default function YourDocument() {
const yourMethod = (event) => {
event?.addContext({ position: {x: 200, y: 100}, commentType: 'manual'});
}
let commentAnnotations = useCommentAnnotations()
return (
yourMethod(event)} />
{
commentAnnotations.map((commentAnnotation) => {
return (
)
})
}
)
}
```
```html HTML theme={null}
```
# Comment Text
Source: https://velt.dev/docs/async-collaboration/comments/standalone-components/comment-text/overview
Attach a comment to a specific piece of text by wrapping it in the standalone Comment Text component.
The Comment Text component attaches an existing comment to a specific piece of text in your own markup. Put any text inside it and give it an annotation id: it highlights that text and attaches the comment to it.
Use it when the text you want to comment on lives in your own components and you already know which annotation belongs to it, for example when rendering comments in a rich-text editor. For selection-driven commenting where the user picks the text, use [text comments](/docs/async-collaboration/comments/setup/text) instead.
## Setup
Wrap the text and pass either `annotationId` or `multiThreadAnnotationId`.
> [tab] React / Next.js
>
> ```jsx theme={null}
> import { VeltCommentText } from '@veltdev/react';
>
>
> {/* your content here */}
>
>
>
> {/* your content here */}
>
> ```
> [tab] Other Frameworks
>
> ```html theme={null}
>
>
>
>
>
>
>
> ```
## Props
| Prop | HTML attribute | Type | Required | Description |
| - | - | - | - | - |
| `annotationId` | `annotation-id` | `string` | No | The comment annotation to attach to the wrapped text. |
| `multiThreadAnnotationId` | `multi-thread-annotation-id` | `string` | No | The multi-thread annotation to attach to the wrapped text. |
> [!NOTE]
>
> This component renders the `velt-comment-text` element. It is distinct from `VeltTextComment`, which is the selection toolbar used by [text comments](/docs/async-collaboration/comments/setup/text).
# Customize Behavior
Source: https://velt.dev/docs/async-collaboration/comments/standalone-components/comment-thread/customize-behavior
## 1. `onCommentClick` Callback
* When the user clicks on the comment thread, you can listen to it using this method.
* Example: Use this to fetch the context and make the necessary app state changes to navigate to the comment.
> [tab] React / Next.js
>
> ```jsx theme={null}
> annotationId="COMMENT_ANNOTATION_ID"
> onCommentClick={(data) => handleOnCommentClick(data)}
> />
> ```
> [tab] Other Frameworks
>
> ```jsx theme={null}
>
>
> ```
## 2. Pass Comment Annotation Object
* You can pass a Comment Annotation object directly to render the comment thread
* When using annotations from other documents:
* Comments will be read-only
* Reactions and recordings will not be rendered
* This enables creating Kanban boards by fetching comment annotations from multiple documents using our REST APIs
> [tab] React / Next.js
>
> ```jsx theme={null}
>
> ```
> [tab] Other Frameworks
>
> ```html theme={null}
>
> ```
# Standalone Comment Thread
Source: https://velt.dev/docs/async-collaboration/comments/standalone-components/comment-thread/overview
* You can use the Standalone Comment Thread component to build things such as:
* a kanban board
* your own version of the `Comments Sidebar` component
* This component does not add any additional functionality. It is just used to render existing comment data.
* This is a thin wrapper around the Comment Dialog component. See the [`Component catalog`](/docs/ui-customization/reference/component-catalog#veltcommentdialogwireframe-slot-tree) and [`Wireframe components`](/docs/ui-customization/reference/wireframe-components) for customization guidance.
* Get the Comment Annotations data using the APIs.
* Use this component to render the Comment Annotations data.
[https://landing-page-demo-velt.vercel.app/?feature=comment-thread](https://landing-page-demo-velt.vercel.app/?feature=comment-thread)
[Open in larger window](https://landing-page-demo-velt.vercel.app/?feature=comment-thread)
# Setup
Source: https://velt.dev/docs/async-collaboration/comments/standalone-components/comment-thread/setup
## 1. Retrieve Comment Annotations
* Retrieve all comment annotations data.
* [Learn more](/docs/async-collaboration/comments/customize-behavior#getcommentannotations).
> [tab] React / Next.js
>
> Using Hooks:
>
> ```jsx theme={null}
> let commentAnnotations = useCommentAnnotations()
> ```
>
> Using API:
>
> ```js theme={null}
> const commentElement = client.getCommentElement();
> let subscription = commentElement.getAllCommentAnnotations().subscribe((commentAnnotations) => {
> // console.log(commentAnnotations);
> });
> ```
>
> To unsubscribe from the subscription:
>
> ```jsx theme={null}
> subscription?.unsubscribe()
> ```
> [tab] Other Frameworks
>
> ```js theme={null}
> const commentElement = Velt.getCommentElement();
> let subscription = commentElement.getAllCommentAnnotations().subscribe((commentAnnotations) => {
> // console.log(commentAnnotations);
> });
> ```
>
> To unsubscribe from the subscription:
>
> ```jsx theme={null}
> subscription?.unsubscribe()
> ```
## 2. Add the Velt Comment Thread component
* Iterate over the `Comment Annotations` array and add the `Velt Comment Thread` component.
* Pass the `annotation Id` prop to set the specific Comment Thread data.
Here's an improved example:
> [tab] React / Next.js
>
> ```jsx theme={null}
>
> let commentAnnotations = useCommentAnnotations()
>
> return (
>
> {commentAnnotations.map((x,i) => )}
>
> )
> ```
> [tab] Other Frameworks
>
> ```html theme={null}
>
>
> ```
```jsx React / Next.js theme={null}
import { VeltCommentThread, useCommentAnnotations } from '@veltdev/react';
export default function YourDocument() {
let commentAnnotations = useCommentAnnotations()
return (
{commentAnnotations.map((x,i) => )}
)
}
```
```js Other Frameworks theme={null}
const commentElement = client.getCommentElement();
let subscription = commentElement.getAllCommentAnnotations().subscribe((comments) => {
// If you are using pure html, inject
// In other frameworks, you can loop over the comments inside the template itself
});
//To unsubscribe from the subscription:
subscription?.unsubscribe()
```
# Customize Behavior
Source: https://velt.dev/docs/async-collaboration/notifications/customize-behavior
# Configuration
#### setTabConfig
* Using this config, you can customize the name of the tabs or disable them altogether.
* By default, all the three tabs are enabled.
> [tab] React / Next.js with Hooks
>
> You can set it on Notifications Tool:
>
> ```jsx theme={null}
> "forYou": {
> name: 'Custom For You',
> enable: true,
> },
> "documents": {
> name: 'Custom Document',
> enable: false,
> },
> "all": {
> name: 'Custom All',
> enable: true,
> },
> }
> } />
> ```
>
> You can alternatively set it on Notifications Panel if you have directly embedded it:
>
> ```jsx theme={null}
> "forYou": {
> name: 'Custom For You',
> enable: true,
> },
> "documents": {
> name: 'Custom Document',
> enable: false,
> },
> "all": {
> name: 'Custom All',
> enable: true,
> },
> }
> } />
> ```
>
> **Using APIs:**
>
> ```jsx theme={null}
> const notificationElement = useNotificationUtils();
>
> const tabConfig = {
> "forYou": {
> name: 'Custom For You',
> enable: true,
> },
> "documents": {
> name: 'Custom Document',
> enable: false,
> },
> "all": {
> name: 'Custom All',
> enable: true,
> },
> };
>
> notificationElement.setTabConfig(tabConfig);
> ```
> [tab] React / Next.js
>
> You can set it on Notifications Tool:
>
> ```jsx theme={null}
> "forYou": {
> name: 'Custom For You',
> enable: true,
> },
> "documents": {
> name: 'Custom Document',
> enable: false,
> },
> "all": {
> name: 'Custom All',
> enable: true,
> },
> }
> } />
> ```
>
> You can alternatively set it on Notifications Panel if you have directly embedded it:
>
> ```jsx theme={null}
> "forYou": {
> name: 'Custom For You',
> enable: true,
> },
> "documents": {
> name: 'Custom Document',
> enable: false,
> },
> "all": {
> name: 'Custom All',
> enable: true,
> },
> }
> } />
> ```
>
> **Using APIs:**
>
> ```jsx theme={null}
> const notificationElement = client.getNotificationElement();
>
> const tabConfig = {
> "forYou": {
> name: 'Custom For You',
> enable: true,
> },
> "documents": {
> name: 'Custom Document',
> enable: false,
> },
> "all": {
> name: 'Custom All',
> enable: true,
> },
> };
>
> notificationElement.setTabConfig(tabConfig);
> ```
> [tab] Other Frameworks
>
> ```js theme={null}
> const tabConfig = {
> "forYou": {
> name: 'Custom For You',
> enable: true,
> },
> "documents": {
> name: 'Custom Document',
> enable: false,
> },
> "all": {
> name: 'Custom All',
> enable: true,
> },
> };
>
> // Set it using Notifications Tool
> const notificationsTool = document.querySelector('velt-notifications-tool');
> notificationsTool?.setAttribute("tab-config", JSON.stringify(tabConfig));
>
> // Or, set it using Notifications Panel
> const notificationsPanel = document.querySelector('velt-notifications-panel');
> notificationsPanel?.setAttribute("tab-config", JSON.stringify(tabConfig));
> ```
>
> **Using APIs:**
>
> ```jsx theme={null}
> const notificationElement = Velt.getNotificationElement();
>
> const tabConfig = {
> "forYou": {
> name: 'Custom For You',
> enable: true,
> },
> "documents": {
> name: 'Custom Document',
> enable: false,
> },
> "all": {
> name: 'Custom All',
> enable: true,
> },
> };
>
> notificationElement.setTabConfig(tabConfig);
> ```
#### considerAllNotifications
Controls the notification count and unread indicator for the notification panel. When enabled, the notification count and unread badge include items from all tabs; when disabled (default), they only include items from the “For You” tab.
Default: `false`
> [tab] React / Next.js
>
> **Using Props:**
>
> ```jsx theme={null}
>
> ```
> [tab] Other Frameworks
>
> **Using Props:**
>
> ```html theme={null}
>
> ```
#### enableCurrentDocumentOnly
Programmatically filters notifications to show only those from the current document. By default it shows notifications for the 15 most recently active documents accessible to the current user in the current organization.
> [tab] React / Next.js
>
> **Hooks:**
>
> ```jsx theme={null}
> const notificationElement = useNotificationUtils();
>
> useEffect(() => {
> notificationElement.enableCurrentDocumentOnly();
> notificationElement.disableCurrentDocumentOnly();
> }, [notificationElement]);
> ```
>
> **API:**
>
> ```jsx theme={null}
> const notificationElement = client.getNotificationElement();
> notificationElement.enableCurrentDocumentOnly();
> notificationElement.disableCurrentDocumentOnly();
> ```
> [tab] Other Frameworks
>
> ```jsx theme={null}
> const notificationElement = Velt.getNotificationElement();
> notificationElement.enableCurrentDocumentOnly();
> notificationElement.disableCurrentDocumentOnly();
> ```
#### setMaxDays
Notifications older than the specified number of days will not be displayed.
Default: 15 days.
> [tab] React / Next.js with Hooks
>
> ```jsx theme={null}
>
> ```
>
> **Using API:**
>
> ```jsx theme={null}
> const notificationElement = useNotificationUtils();
> notificationElement.setMaxDays(15);
> ```
> [tab] React / Next.js
>
> ```jsx theme={null}
>
> ```
>
> **Using API:**
>
> ```jsx theme={null}
> const notificationElement = client.getNotificationElement();
> notificationElement.setMaxDays(15);
> ```
> [tab] Other Frameworks
>
> ```jsx theme={null}
>
> ```
>
> **Using APIs:**
>
> ```jsx theme={null}
> const notificationElement = Velt.getNotificationElement();
> notificationElement.setMaxDays(15);
> ```
#### panelOpenMode
Notifications Panel opens in one of the following ways:
* `popover`: It opens as a popover on the Notification Tool.
* `sidebar`: It opens as a sidebar from the right edge of the screen.
Default: `popover`.
> [tab] React / Next.js
>
> ```jsx theme={null}
>
>
> ```
> [tab] Other Frameworks
>
> ```jsx theme={null}
>
>
> ```
#### pageSize
Control initial notification load count.
> [tab] React / Next.js
>
> ```jsx theme={null}
>
>
> ```
> [tab] Other Frameworks
>
> ```html theme={null}
>
>
> ```
#### enableReadNotificationsOnForYouTab
* You can control whether read notifications are displayed in the "For You" tab. By default, read notifications are removed from this tab.
* This feature allows you to customize the visibility of read notifications in the "For You" tab, providing more flexibility in how notifications are displayed to users.
Default: `false`.
> [tab] React / Next.js with Hooks
>
> Using Props:
>
> ```jsx theme={null}
>
>
> ```
>
> Using APIs:
>
> ```jsx theme={null}
> const notificationElement = useNotificationUtils();
> // Enable to keep read notifications in the for you tab
> notificationElement.enableReadNotificationsOnForYouTab();
> // Disable to hide read notifications in the for you tab
> notificationElement.disableReadNotificationsOnForYouTab();
> ```
> [tab] React / Next.js
>
> Using Props:
>
> ```jsx theme={null}
>
>
> ```
>
> Using APIs:
>
> ```jsx theme={null}
> const notificationElement = client.getNotificationElement();
> // Enable to keep read notifications in the for you tab
> notificationElement.enableReadNotificationsOnForYouTab();
> // Disable to hide read notifications in the for you tab
> notificationElement.disableReadNotificationsOnForYouTab();
> ```
> [tab] Other Frameworks
>
> Using Props:
>
> ```html theme={null}
>
>
>
>
> ```
>
> Using API:
>
> ```html theme={null}
>
> ```
#### enableCrossOrganization
* When enabled, notifications from docs user has access to in other organizations are merged into the "For You" tab.
* Only the "For You" feed is supported.
* The `enableCrossOrganization` prop accepts a `boolean`, a `CrossOrganizationConfig` object, or a JSON config string; the `enable-cross-organization` attribute accepts `"true"` / `"false"` or a JSON config string.
Default: `false`.
> [tab] React / Next.js
>
> Using Props:
>
> ```jsx theme={null}
> {/* Enable with defaults */}
>
>
>
> {/* Enable with custom config */}
> organizationIds: ['org-1', 'org-2'],
> }} />
> organizationIds: ['org-1', 'org-2'],
> }} />
> ```
>
> Using APIs:
>
> ```jsx theme={null}
> const notificationElement = useNotificationUtils();
>
> // Enable with defaults
> notificationElement.enableCrossOrganization();
>
> // Enable with config
> notificationElement.enableCrossOrganization({
> organizationIds: ['org-1', 'org-2'],
> });
>
> // Disable
> notificationElement.disableCrossOrganization();
>
> // Get current config (one-time)
> const config = notificationElement.getCrossOrganizationConfig();
>
> // Subscribe to config changes
> const subscription = notificationElement.getCrossOrganizationConfig$().subscribe((config) => {
> console.log('Cross-org config:', config);
> });
> ```
> [tab] Other Frameworks
>
> Using Props:
>
> ```html theme={null}
>
>
>
>
>
>
>
>
>
>
>
> ```
>
> Using API:
>
> ```html theme={null}
>
> ```
**`CrossOrganizationConfig` fields:** See [`CrossOrganizationConfig`](/docs/api-reference/sdk/models/data-models#crossorganizationconfig) for the full type definition.
| Property | Type | Default | Notes |
| - | - | - | - |
| `enabled` | `boolean` | `true` | Set to `false` to disable (equivalent to calling `disableCrossOrganization()`). |
| `organizationIds` | `string[]` | None | Allowlist; when omitted, all indexed orgs are eligible. |
| `excludeOrganizationIds` | `string[]` | None | Additional orgs to exclude. Current org always excluded. |
| `feeds` | `('forYou' \| 'all')[]` | None | Only `'forYou'` is supported; `'all'` is ignored with a warning. |
> [!NOTE]
>
> Passing `{ enabled: false }` as the config to `enableCrossOrganization()` routes to disable. Passing `null` or calling without arguments opts in with all defaults.
#### getCrossOrganizationConfig
Retrieve the current cross-organization configuration. Use `getCrossOrganizationConfig$()` to subscribe to ongoing changes.
> [tab] React / Next.js with Hooks
>
> ```jsx theme={null}
> const notificationElement = useNotificationUtils();
>
> // One-time read
> const config = notificationElement.getCrossOrganizationConfig();
>
> // Subscribe to changes
> const subscription = notificationElement.getCrossOrganizationConfig$().subscribe((config) => {
> console.log('Cross-org config updated:', config);
> });
> ```
> [tab] React / Next.js
>
> ```jsx theme={null}
> const notificationElement = client.getNotificationElement();
>
> // One-time read
> const config = notificationElement.getCrossOrganizationConfig();
>
> // Subscribe to changes
> const subscription = notificationElement.getCrossOrganizationConfig$().subscribe((config) => {
> console.log('Cross-org config updated:', config);
> });
> ```
> [tab] Other Frameworks
>
> ```html theme={null}
>
> ```
#### enableUserScopedNotifications
* By default, the "For You" tab and the unread count are derived from the organization's 15 most recently active documents. An unread notification whose document falls outside that window is not fetched, so it disappears from the tab and the count until the document becomes active again.
* When enabled, the SDK also fetches the signed-in user's newest notifications for the current organization directly, independent of that window. Those notifications are merged into the "For You" store, deduped by `notificationId`, and merged additively into the "All" tab.
* The `enableUserScopedNotifications` prop accepts a `boolean`, a `UserScopedNotificationsConfig` object, or a JSON config string; the `enable-user-scoped-notifications` attribute accepts `"true"` / `"false"` or a JSON config string.
Default: `false`.
> [tab] React / Next.js
>
> Using Props:
>
> ```jsx theme={null}
> {/* Enable with the default limit of 25 */}
>
>
>
> {/* Enable with a custom limit */}
> limit: 60,
> }} />
> limit: 60,
> }} />
> ```
>
> Using APIs:
>
> ```jsx theme={null}
> const notificationElement = useNotificationUtils();
>
> // Enable with the default limit of 25
> notificationElement.enableUserScopedNotifications();
>
> // Enable with a custom limit
> notificationElement.enableUserScopedNotifications({
> limit: 60,
> });
>
> // Disable, keeping the configured limit
> notificationElement.disableUserScopedNotifications();
> ```
> [tab] Other Frameworks
>
> Using Props:
>
> ```html theme={null}
>
>
>
>
>
>
>
>
>
>
>
> ```
>
> Using APIs:
>
> ```html theme={null}
>
> ```
**`UserScopedNotificationsConfig` fields:** See [`UserScopedNotificationsConfig`](/docs/api-reference/sdk/models/data-models#userscopednotificationsconfig) for the full type definition.
| Property | Type | Default | Notes |
| - | - | - | - |
| `enabled` | `boolean` | `true` | Set to `false` to disable (equivalent to calling `disableUserScopedNotifications()`). Keeps the configured `limit`. |
| `limit` | `number` | `25` | Maximum user-scoped notifications fetched. Clamped to `[1, 200]`; non-numeric, non-finite, or values below `1` fall back to `25`. |
**Behavior:**
* Setting the prop and calling the API method write to the same setting, so the last write wins. Drive it from one place only, and note that setting it on either `VeltNotificationsTool` or `VeltNotificationsPanel` is equivalent.
* Calling `enableUserScopedNotifications()` before initialization or `setDocument()` is safe. The setting latches and takes effect on the first full fetch after the organization pipeline initializes.
* The user-scoped fetch runs on full fetches only, and is suppressed under `currentDocumentOnly`. Narrowing the scope explicitly wins over this setting.
* Switching organization or document clears the stores as before, and the next full fetch re-sends the setting, so user-scoped notifications never carry across organizations.
* In the "For You" store, a notification that arrives through both the per-document path and the user-scoped path appears once. In the "All" tab, document notifications win on ID collision and user-scoped notifications outrank cross-organization ones; the result is sorted by timestamp descending.
* Cross-organization "For You" behavior and the `maxNotificationDays` retention bound are unchanged.
* The fetch requires matching backend support. Against an older backend it falls back to the windowed behavior instead of failing.
> [!NOTE]
>
> Passing `{ enabled: false }` as the config to `enableUserScopedNotifications()` routes to disable and keeps the previously configured `limit`. Passing `null` or calling without arguments opts in with all defaults.
> [!NOTE]
>
> The first load after opting in at a busy organization surfaces previously invisible unread notifications in one batch. This is the intended correction. The unread count is capped at the configured `limit`.
#### disableUserScopedNotifications
Turn the user-scoped fetch back off. The "For You" tab and the unread count return to the recently-active-documents window with no other change.
> [tab] React / Next.js
>
> ```jsx theme={null}
> const notificationElement = useNotificationUtils();
> notificationElement.disableUserScopedNotifications();
> ```
> [tab] Other Frameworks
>
> ```js theme={null}
> const notificationElement = Velt.getNotificationElement();
> notificationElement.disableUserScopedNotifications();
> ```
#### enableSelfNotifications
* By default notifications api and components exclude notifications where the current user is the action user.
* This feature allows you to enable self notifications.
Default: `false`.
> [tab] React / Next.js
>
> **Using props:**
>
> ```jsx theme={null}
>
>
> ```
>
> **Using API:**
>
> ```jsx theme={null}
> const notificationElement = useNotificationUtils();
> notificationElement.enableSelfNotifications(); // Enables self notifications.
> notificationElement.disableSelfNotifications(); // Disables self notifications.
> ```
> [tab] Other Frameworks
>
> **Using attributes:**
>
> ```html theme={null}
>
>
> ```
>
> **Using API:**
>
> ```jsx theme={null}
> const notificationElement = Velt.getNotificationElement();
> notificationElement.enableSelfNotifications(); // Enables self notifications.
> notificationElement.disableSelfNotifications(); // Disables self notifications.
> ```
# Data
#### getNotificationsData
* Get the notifications data for the current user.
* Velt returns a notification for a private comment only to users who can see that comment. [Learn more →](/docs/async-collaboration/notifications/overview#notifications-for-private-comments)
> [!NOTE]
>
> * The returned data includes notifications from up to the number of days specified by [max days](#setmaxdays) configuration.
> * "For You" tab: By default only the latest 50 notifications are fetched. This is done to reduce clutter and noise.
> * "Document" and "All" tabs: By default, up to 15 notifications are fetched for each of the 15 most recently active documents accessible to the current user. This highlights the most relevant and recent activity.
* Params:
* query: Optional. [`GetNotificationsDataQuery`](/docs/api-reference/sdk/models/data-models#getnotificationsdataquery)
* `type`: Filter for notification type: all, for you, or documents.
* `forYou`: returns notifications where the current user is involved.
* `all` / `documents`: returns all notifications from the documents the user has access to.
* Returns [`Notification[]`](/docs/api-reference/sdk/models/data-models#notification)
> [tab] React / Next.js
>
> **Using Hooks:**
>
> ```jsx theme={null}
> // Without query
> const notificationData = useNotificationsData();
>
> // With query
> const notificationsData = useNotificationsData({ type: 'forYou' });
>
> useEffect(() => {
> if (notificationsData) {
> console.log(notificationsData);
> }
> }, [notificationsData]);
> ```
>
> **Using API:**
>
> ```jsx theme={null}
> const notificationElement = client.getNotificationElement();
>
> // Without query
> let subscription = notificationElement.getNotificationsData().subscribe((notifications) => {
> console.log("Notifications: ", notifications)
> });
>
> // With query
> let subscription = notificationElement.getNotificationsData({ type: 'forYou' }).subscribe((notifications) => {
> console.log("Notifications: ", notifications)
> });
> ```
>
> To unsubscribe from the subscription:
>
> ```jsx theme={null}
> subscription?.unsubscribe()
> ```
> [tab] Other Frameworks
>
> ```jsx theme={null}
> const notificationElement = Velt.getNotificationElement();
>
> // Without query
> let subscription = notificationElement.getNotificationsData().subscribe((notifications) => {
> console.log("Notifications: ", notifications)
> });
>
> // With query
> let subscription = notificationElement.getNotificationsData({ type: 'forYou' }).subscribe((notifications) => {
> console.log("Notifications: ", notifications)
> });
>
> ```
>
> To unsubscribe from the subscription:
>
> ```jsx theme={null}
> subscription?.unsubscribe()
> ```
#### getUnreadNotificationsCount
* Retrieve the count of unread notifications, which includes a breakdown for different tabs.
* The 'Document' tab is not included in the response because it contains all the notifications present in the 'All' tab.
**Sample response:**
```javascript theme={null}
{
forYou: 4, // # of unread notifications in the "For You" tab
all: 5 // # of unread notifications in the "All" or "Document" tab
}
```
> [tab] React / Next.js
>
> Using Hooks:
>
> ```jsx theme={null}
> const unreadCount = useUnreadNotificationsCount();
>
> useEffect(() => {
> console.log('Unread Count', unreadCount);
> }, [unreadCount]);
> ```
>
> Using API:
>
> ```javascript theme={null}
> const notificationElement = client.getNotificationElement();
> notificationElement.getUnreadNotificationsCount().subscribe((data) => {
> console.log('Unread notifications count:', data);
> });
> ```
> [tab] Other Frameworks
>
> ```javascript theme={null}
> const notificationElement = Velt.getNotificationElement();
> notificationElement.getUnreadNotificationsCount().subscribe((data) => {
> console.log('Unread notifications count:', data);
> });
> ```
# Event Subscription
#### on
* Subscribe to Notification Events. Here is the list of events you can subscribe to and the event objects you will receive.
| Event Type | Description | Event Object |
| - | - | - |
| `settingsUpdated` | Triggered when the settings are updated by the user using UI or the API | [SettingsUpdatedEvent](/docs/api-reference/sdk/models/data-models#settingsupdatedevent) |
> [tab] React / Next.js
>
> ```jsx theme={null}
> // Hook
> const settingsUpdatedEvent = useNotificationEventCallback('settingsUpdated')
>
> useEffect(() => {
> console.log('settingsUpdatedEvent', settingsUpdatedEvent)
> }, [settingsUpdatedEvent])
>
>
> // API Method
> const notificationElement = useNotificationUtils();
> notificationElement.on('settingsUpdated').subscribe((event) => {
> console.log('settingsUpdatedEvent', event);
> });
>
> ```
> [tab] Other Frameworks
>
> ```js theme={null}
> const notificationElement = Velt.getNotificationElement();
> notificationElement.on('settingsUpdated').subscribe((event) => {
> console.log('settingsUpdatedEvent', event);
> });
> ```
#### onNotificationClick
* The `onNotificationClick` event fires when a notification is clicked in the Notifications Panel.
* It returns a [`Notification`](/docs/api-reference/sdk/models/data-models#notification) object with details about the clicked notification.
* Listen to this event via either the Notification Tool or the Notification Panel, but not both.
* Use this event to implement custom actions in response to notification clicks, such as navigating to a specific part of the app.
> [tab] React / Next.js
>
> ```jsx theme={null}
> onNotificationClickEvent(notification)} />
>
> onNotificationClickEvent(notification)} />
>
> const onNotificationClickEvent = (notification) => {
> console.log('onNotificationClick: ', notification);
> }
> ```
> [tab] Other Frameworks
>
> ```jsx theme={null}
> const notificationsTool = document.querySelector('velt-notifications-tool');
> notificationsTool?.addEventListener('onNotificationClick', (event) => {
> console.log('onNotificationClick from Tool: ', event.detail);
> });
>
> const notificationsPanel = document.querySelector('velt-notifications-panel');
> notificationsPanel?.addEventListener('onNotificationClick', (event) => {
> console.log('onNotificationClick from Panel: ', event.detail);
> });
> ```
# Actions
#### markNotificationAsReadById
* Mark a single notification as read using its notificationId.
* The notification will be marked as read in all tabs.
> [tab] React / Next.js
>
> ```javascript theme={null}
> const notificationElement = client.getNotificationElement();
> notificationElement.markNotificationAsReadById("notificationId");
> ```
> [tab] Other Frameworks
>
> ```javascript theme={null}
> const notificationElement = Velt.getNotificationElement();
> notificationElement.markNotificationAsReadById("notificationId");
> ```
#### openNotificationsPanel
* Programmatically open or close the notification panel using the provided APIs.
* This will not work if you have embedded the notification panel in your app.
> [tab] React / Next.js
>
> ```jsx theme={null}
> const notificationElement = useNotificationUtils()
> notificationElement.openNotificationsPanel()
> notificationElement.closeNotificationsPanel()
>
> ```
> [tab] Other Frameworks
>
> ```jsx theme={null}
> const notificationElement = Velt.getNotificationElement();
> notificationElement.openNotificationsPanel();
> notificationElement.closeNotificationsPanel();
> ```
#### setAllNotificationsAsRead
* Mark all notifications as read, either globally or for a specific tab.
* Using 'all' or 'document' as the `tabId` marks all notifications as read across all tabs (equivalent to calling `setAllNotificationsAsRead()` without arguments).
* Using 'for-you' as the `tabId` only marks notifications in the 'for-you' tab as read.
> [tab] React / Next.js
>
> ```javascript theme={null}
> const notificationElement = client.getNotificationElement();
>
> // Mark all notifications as read
> notificationElement.setAllNotificationsAsRead();
>
> // Mark all notifications as read for a specific tab
> notificationElement.setAllNotificationsAsRead({ tabId: 'for-you' });
> notificationElement.setAllNotificationsAsRead({ tabId: 'all' });
> notificationElement.setAllNotificationsAsRead({ tabId: 'document' });
> ```
> [tab] Other Frameworks
>
> ```javascript theme={null}
> const notificationElement = Velt.getNotificationElement();
>
> // Mark all notifications as read
> notificationElement.setAllNotificationsAsRead();
>
> // Mark all notifications as read for a specific tab
> notificationElement.setAllNotificationsAsRead({ tabId: 'for-you' });
> notificationElement.setAllNotificationsAsRead({ tabId: 'all' });
> notificationElement.setAllNotificationsAsRead({ tabId: 'document' });
> ```
# Notification Settings
> [!WARNING]
>
> 1. This feature currently only updates the settings for the current user in the current Velt document. If you are using multiple documents or folders, the settings will apply to the root document.
> 2. Make sure to first enable the settings feature in [Velt Console](https://console.velt.dev/dashboard/config/notification).
#### enableSettings
* Enable or disable the settings feature for notifications. This allows users to configure their notification preferences.
* Params: `none`
* Returns: `void`
> [tab] React / Next.js
>
> **Using Props:**
>
> ```jsx theme={null}
> // You can enable this on either the tool or the panel
>
>
> ```
>
> **Using APIs:**
>
> ```jsx theme={null}
> const notificationElement = useNotificationUtils();
> notificationElement.enableSettings(); // enables the settings feature
> notificationElement.disableSettings(); // disables the settings feature
> ```
> [tab] Other Frameworks
>
> **Using Props:**
>
> ```html theme={null}
>
>
> ```
>
> **Using APIs:**
>
> ```js theme={null}
> const notificationElement = Velt.getNotificationElement();
> notificationElement.enableSettings(); // enables the settings feature
> notificationElement.disableSettings(); // disables the settings feature
> ```
#### enableSettingsAtOrganizationLevel
Enable organization-level notification settings. When enabled, settings apply to all documents in the organization instead of per-document.
**Params:** `none`
**Returns:** `void`
> [tab] React / Next.js
>
> **Using Props:**
>
> ```jsx theme={null}
> // Enable organization-level settings on the tool
> settings={true}
> enableSettingsAtOrganizationLevel={true}
> />
>
> // Or on the panel
> settings={true}
> enableSettingsAtOrganizationLevel={true}
> />
> ```
>
> **Using APIs:**
>
> ```jsx theme={null}
> const notificationElement = useNotificationUtils();
> notificationElement.enableSettingsAtOrganizationLevel(); // enable org-level settings
> notificationElement.disableSettingsAtOrganizationLevel(); // disable org-level settings
> ```
> [tab] Other Frameworks
>
> **Using Props:**
>
> ```html theme={null}
>
> settings="true"
> enable-settings-at-organization-level="true">
>
>
>
> settings="true"
> enable-settings-at-organization-level="true">
>
> ```
>
> **Using APIs:**
>
> ```js theme={null}
> const notificationElement = Velt.getNotificationElement();
> notificationElement.enableSettingsAtOrganizationLevel(); // enable org-level settings
> notificationElement.disableSettingsAtOrganizationLevel(); // disable org-level settings
> ```
#### settingsLayout
Control how notification settings are displayed. Two layout modes are available.
Default: `accordion`
**Type:** [`NotificationSettingsLayout`](/docs/api-reference/sdk/models/data-models#notificationsettingslayout)
**Options:**
* `accordion`: Settings displayed in expandable accordion
* `dropdown`: Settings displayed in dropdown menu
> [tab] React / Next.js
>
> ```jsx theme={null}
>
>
> ```
> [tab] Other Frameworks
>
> ```html theme={null}
>
>
> ```
#### setSettingsInitialConfig
* Set the initial default configuration for notification settings. This defines the available settings options and their default values.
* By default we have config added for inbox (in-app notifications) and email.
* You can extend this to add more channels where you intend to send notifications to your users. eg: slack, jira, asana, linear etc.
* If you do extend it to other custom channels, you will need to send the data to those channels yourself using our webhooks. [Learn more](/docs/webhooks/basic)
* This config will automatically generate the settings UI for the user to configure their notification preferences.
* Params: [`NotificationInitialSettingsConfig[]`](/docs/api-reference/sdk/models/data-models#notificationinitialsettingsconfig)
* Here is what the value types mean:
* `ALL`: Subscribes the user to all notifications whether or not the user is involved in the notification on the current document.
* `MINE`: Subscribes the user to notifications that are related to the current user on the current document.
* `NONE`: Subscribes the user to no notifications on this channel on the current document.
* Returns: `void`
Default:
```js theme={null}
[
{
name: 'Inbox',
id: 'inbox',
default: 'ALL',
enable: true,
values: [
{
name: 'All',
id: 'ALL',
},
{
name: 'Only Involved',
id: 'MINE',
},
{
name: 'None',
id: 'NONE',
}
]
},
{
name: 'Email',
id: 'email',
default: 'MINE',
enable: true,
values: [
{
name: 'All',
id: 'ALL',
},
{
name: 'Only Involved',
id: 'MINE',
},
{
name: 'None',
id: 'NONE',
}
]
},
]
```
> [tab] React / Next.js
>
> **Using Hook:**
>
> ```jsx theme={null}
> const { setSettingsInitialConfig, setSettings, settings } = useNotificationSettings();
> setSettingsInitialConfig([
> {
> name: 'Inbox',
> id: 'inbox',
> default: 'MINE',
> enable: true,
> values: [
> {
> name: 'All',
> id: 'ALL',
> },
> {
> name: 'Only Involved',
> id: 'MINE',
> },
> {
> name: 'None',
> id: 'NONE',
> }
> ]
> },
> {
> name: 'Slack',
> id: 'slack',
> default: 'MINE',
> enable: true,
> values: [
> {
> name: 'All',
> id: 'ALL',
> },
> {
> name: 'Only Involved',
> id: 'MINE',
> },
> {
> name: 'None',
> id: 'NONE',
> }
> ]
> },
> {
> name: 'Linear',
> id: 'linear',
> default: 'MINE',
> enable: true,
> values: [
> {
> name: 'All',
> id: 'ALL',
> },
> {
> name: 'Only Involved',
> id: 'MINE',
> },
> {
> name: 'None',
> id: 'NONE',
> }
> ]
> },
> ]);
> ```
>
> **Using API:**
>
> ```javascript theme={null}
> const notificationElement = useNotificationUtils();
> notificationElement.setSettingsInitialConfig([
> {
> name: 'Inbox',
> id: 'inbox',
> default: 'MINE',
> enable: true,
> values: [
> {
> name: 'All',
> id: 'ALL',
> },
> {
> name: 'Only Involved',
> id: 'MINE',
> },
> {
> name: 'None',
> id: 'NONE',
> }
> ]
> },
> {
> name: 'Slack',
> id: 'slack',
> default: 'MINE',
> enable: true,
> values: [
> {
> name: 'All',
> id: 'ALL',
> },
> {
> name: 'Only Involved',
> id: 'MINE',
> },
> {
> name: 'None',
> id: 'NONE',
> }
> ]
> },
> {
> name: 'Linear',
> id: 'linear',
> default: 'MINE',
> enable: true,
> values: [
> {
> name: 'All',
> id: 'ALL',
> },
> {
> name: 'Only Involved',
> id: 'MINE',
> },
> {
> name: 'None',
> id: 'NONE',
> }
> ]
> },
> ]);
> ```
> [tab] Other Frameworks
>
> ```javascript theme={null}
> const notificationElement = Velt.getNotificationElement();
> notificationElement.setSettingsInitialConfig([
> {
> name: 'Inbox',
> id: 'inbox',
> default: 'MINE',
> enable: true,
> values: [
> {
> name: 'All',
> id: 'ALL',
> },
> {
> name: 'Only Involved',
> id: 'MINE',
> },
> {
> name: 'None',
> id: 'NONE',
> }
> ]
> },
> {
> name: 'Slack',
> id: 'slack',
> default: 'MINE',
> enable: true,
> values: [
> {
> name: 'All',
> id: 'ALL',
> },
> {
> name: 'Only Involved',
> id: 'MINE',
> },
> {
> name: 'None',
> id: 'NONE',
> }
> ]
> },
> {
> name: 'Linear',
> id: 'linear',
> default: 'MINE',
> enable: true,
> values: [
> {
> name: 'All',
> id: 'ALL',
> },
> {
> name: 'Only Involved',
> id: 'MINE',
> },
> {
> name: 'None',
> id: 'NONE',
> }
> ]
> },
> ]);
> ```
#### muteAllNotifications
* Mutes all notifications across all the channels for the current user in this current document.
* In case of multiple documents or folders, this will mute all notifications for the user in the root document.
* Params: `none`
* Returns: `void`
> [tab] React / Next.js
>
> ```javascript theme={null}
> const notificationElement = client.getNotificationElement();
> notificationElement.muteAllNotifications();
> ```
> [tab] Other Frameworks
>
> ```javascript theme={null}
> const notificationElement = Velt.getNotificationElement();
> notificationElement.muteAllNotifications();
> ```
#### setSettings
* Update notification settings configuration for the current user.
* Here you need to provide the id of the channel config and its value id.
* Params: [`NotificationSettingsConfig`](/docs/api-reference/sdk/models/data-models#notificationsettingsconfig)
* Here is what the value types mean:
* `ALL`: Subscribes the user to all notifications whether or not the user is involved in the notification on the current document.
* `MINE`: Subscribes the user to notifications that are related to the current user on the current document.
* `NONE`: Subscribes the user to no notifications on this channel on the current document.
* Returns: `void`
> [tab] React / Next.js
>
> **Using Hook:**
>
> ```jsx theme={null}
> const { setSettingsInitialConfig, setSettings, settings } = useNotificationSettings();
> setSettings({
> 'email': 'MINE',
> 'inbox': 'NONE',
> 'slack': 'ALL',
> 'linear': 'MINE'
> });
> ```
>
> **Using API:**
>
> ```javascript theme={null}
> const notificationElement = useNotificationUtils();
> notificationElement.setSettings({
> 'email': 'MINE',
> 'inbox': 'NONE',
> 'slack': 'ALL',
> 'linear': 'MINE'
> });
> ```
> [tab] Other Frameworks
>
> ```javascript theme={null}
> const notificationElement = Velt.getNotificationElement();
> notificationElement.setSettings({
> 'email': 'MINE',
> 'inbox': 'NONE',
> 'slack': 'ALL',
> 'linear': 'MINE'
> });
> ```
#### getSettings
* Get the current notification settings configuration for the user on the current document.
* Params: `none`
* Returns: [`Observable`](/docs/api-reference/sdk/models/data-models#notificationsettingsconfig)
> [tab] React / Next.js
>
> **Using Hook:**
>
> ```jsx theme={null}
> const { setSettingsInitialConfig, setSettings, settings } = useNotificationSettings();
> // setSettingsInitialConfig will set the default settings for the notifications.
> // setSettings will update the settings for the notifications in the server.
> // settings will return the current settings for the notifications. Initially it will be null and will be updated when the settings are fetched.
> ```
>
> **Using API:**
>
> ```jsx theme={null}
> const notificationsElement = useNotificationUtils();
> notificationsElement.getSettings().subscribe((settings) => {
> console.log('current settings are', settings);
> });
> ```
> [tab] Other Frameworks
>
> ```javascript theme={null}
> const notificationsElement = Velt.getNotificationElement();
> notificationsElement.getSettings().subscribe((settings) => {
> console.log('current settings are', settings);
> });
> ```
# Notification Delivery
#### Batching and Delay Configuration
Configure a delay-and-batch pipeline for notification delivery. When enabled, notifications pass through a delay hold, a seen check, and optional batching before being delivered.
> [!NOTE]
>
> This configuration is set at the API Key level in the [Velt Console](https://console.velt.dev/dashboard/config/notification). It applies to all documents in the organization.
**Delivery pipeline:**
1. **Delay:** Holds the notification for `delaySeconds` before proceeding.
2. **Seen check:** If the recipient has already seen the triggering activity during the delay window, the notification is suppressed.
3. **Batch:** Collects additional activities within the batch window before flushing as a single digest.
4. **Deliver:** Sends the notification (or batched digest) to the recipient.
> [!WARNING]
>
> Webhooks and workflow triggers always fire immediately and are never subject to delay or batching.
**Document-level and user-level batching operate independently.** A notification can accumulate in both windows simultaneously; whichever window closes first (by time or `maxActivities`) triggers a flush for that scope.
# In-app Notifications
Source: https://velt.dev/docs/async-collaboration/notifications/overview
By default, the in-app notifications component is connected to Velt's Comments feature. All relevant comment notifications automatically show up here.
You can also add custom notifications from your app into Velt's notifications feature using REST APIs. [Learn more about adding notifications via REST API →](/docs/api-reference/rest-apis/v2/notifications/add-notifications)
In-app notifications are only generated and fetched for documents the user has access to.
## Notifications for Private Comments
A comment notification carries the comment text. For a [private comment](/docs/async-collaboration/comments/customize-behavior#private-comments-beta), Velt limits the audience to the users who can see that comment.
* The comment author and any user or organization named in the comment's visibility normally receive it.
* A user who cannot see the comment receives nothing. Velt sends no redacted placeholder.
This applies on every channel:
* The "For You", "Document", and "All" tabs of the notifications panel.
* [Webhooks](/docs/webhooks/basic).
* Email.
It also applies to every comment notification, including the one Velt sends when a private comment is deleted.
This check runs in addition to [Access Context](/docs/key-concepts/overview#d-set-feature-level-permissions-using-access-context) filtering. A notification must pass both before a user receives it.
Public comments are unaffected. So are notifications created before this release. Custom notifications you add through the [Add Notifications REST API](/docs/api-reference/rest-apis/v2/notifications/add-notifications) are unaffected. They carry no comment.
No integration change required.
## Default Configuration
**Max count:**
* **"For You" tab**: By default, only the latest 50 notifications are fetched. This is done to reduce clutter and noise.
* **"Document" and "All" tabs**: By default, up to 15 notifications are fetched for each of the 15 most recently active documents accessible to the current user. This highlights the most relevant and recent activity.
**Max days:** By default, notifications older than 15 days will not be fetched. This is configurable.
## Components
There are two components associated with the In-app Notifications feature:
* **Velt Notifications Tool**: This opens the Notifications Panel.
* **Velt Notifications Panel**: This shows all the Notifications grouped in categories.
[https://landing-page-demo-velt.vercel.app/?feature=notifications](https://landing-page-demo-velt.vercel.app/?feature=notifications)
[Open in larger window](https://landing-page-demo-velt.vercel.app/?feature=notifications)
# Setup
Source: https://velt.dev/docs/async-collaboration/notifications/setup

## 1. Enable Notifications in the Velt Console
* Go to the [Notifications section](https://console.velt.dev/dashboard/config/notification) in the Configurations section of the Velt Console and enable Notifications.
> [!WARNING]
>
> Notifications will not work if you do not enable this first.
## 2. Add the Notifications Tool component
* Place the `Velt Notifications Tool` component wherever you want the Notifications button to appear.

> [tab] React / Next.js
>
> ```jsx theme={null}
>
>
>
> ```
> [tab] Other Frameworks
>
> ```jsx theme={null}
>
>
>
> ```
## 3. (optional) Embed Notifications Panel
* By default, the Velt Notifications Panel is automatically added or removed when you use the `Velt Notifications Tool`.
* However, if you want to create a dedicated page or dedicated section for Notifications, you can embed the Velt Notifications Panel component directly there.

> [tab] React / Next.js
>
> ```jsx theme={null}
>
>
>
> ```
> [tab] Other Frameworks
>
> ```jsx theme={null}
>
>
>
> ```
## 4. (optional) Enable Notification Settings for Users
* By default, the user notification settings are disabled.
* You need to first enable this feature in the [Velt Console](https://console.velt.dev/dashboard/config/notification).
* Then enable settings on the notifications tool or panel in the UI. [Learn more](/docs/async-collaboration/notifications/customize-behavior#enablesettings)
* You can then:
* Configure default settings with `setSettingsInitialConfig()` API and extend it to add more channels (eg: slack, jira, asana, linear etc.) where you intend to send notifications to your users. [Learn more](/docs/async-collaboration/notifications/customize-behavior#setsettingsinitialconfig)
* Update settings programmatically with `setSettings()` API. [Learn more](/docs/async-collaboration/notifications/customize-behavior#setsettings)
* Get current settings with `getSettings()` API. [Learn more](/docs/async-collaboration/notifications/customize-behavior#getsettings)
* Subscribe to settings updates with `settingsUpdated` event. [Learn more](/docs/async-collaboration/notifications/customize-behavior#on)
> [!WARNING]
>
> This feature currently only updates the settings for the current user in the current Velt document. If you are using multiple documents or folders, the settings will apply to the root document.
> [tab] React / Next.js
>
> **Using Props:**
>
> ```jsx theme={null}
> // You can enable this on either the tool or the panel
>
>
> ```
>
> **Using APIs:**
>
> ```jsx theme={null}
> const notificationElement = useNotificationUtils();
> notificationElement.enableSettings(); // enables the settings feature
> notificationElement.disableSettings(); // disables the settings feature
> ```
> [tab] Other Frameworks
>
> **Using Props:**
>
> ```html theme={null}
>
>
> ```
>
> **Using APIs:**
>
> ```js theme={null}
> const notificationElement = Velt.getNotificationElement();
> notificationElement.enableSettings(); // enables the settings feature
> notificationElement.disableSettings(); // disables the settings feature
> ```
## 5. (optional) Configure Notification Delivery
* Opt in to a delay-and-batch pipeline that holds notifications, suppresses delivery if the recipient has already seen the activity, and groups notifications into digests before sending.
* Configure Notification Service in the [Velt Console](https://console.velt.dev/dashboard/config/notification) under API Key notification settings. [Learn more](/docs/async-collaboration/notifications/customize-behavior#batching-and-delay-configuration)
```jsx React / Next.js theme={null}
import { VeltNotificationsTool } from '@veltdev/react';
function YourComponent() {
return (
)
}
```
```html HTML theme={null}
```
# Customize Behavior
Source: https://velt.dev/docs/async-collaboration/reactions/customize-behavior
## setCustomReactions
* Use this to set custom reactions emojis.
> [tab] React / Next.js
>
> ```jsx theme={null}
> const customReactions = {
> "URL_EMOJI_ID": {
> "url": "https://em-content.zobj.net/source/apple/391/fire_1f525.png"
> },
> "URL_EMOJI_ID_2": {
> "iconUrl": "EMOJI_URL"
> },
> "TEXT_EMOJI_ID": {
> "emoji": "🤣" // emoji as a text
> }
> };
>
>
> ```
>
> API Method:
>
> ```jsx theme={null}
> const reactionElement = client.getReactionElement();
> reactionElement.setCustomReactions(customReactions);
> ```
> [tab] Other Frameworks
>
> ```jsx theme={null}
> const reactionElement = Velt.getReactionElement();
> const customReactions = {
> "URL_EMOJI_ID": {
> "url": "https://em-content.zobj.net/source/apple/391/fire_1f525.png"
> },
> "URL_EMOJI_ID_2": {
> "iconUrl": "EMOJI_URL"
> },
> "TEXT_EMOJI_ID": {
> "emoji": "🤣" // emoji as a text
> }
> };
> reactionElement.setCustomReactions(customReactions);
> ```
# Inline Reactions
Source: https://velt.dev/docs/async-collaboration/reactions/overview
This allows users to add emoji reactions to specific parts of your UI (eg: posts, images etc). This is great for quick emotional responses or feedback.
Add `Velt Inline Reactions Section` component to your app to enable Inline Reactions.
[https://docs-mini-demo.vercel.app/reactions-inline](https://docs-mini-demo.vercel.app/reactions-inline)
[Open in larger window](https://docs-mini-demo.vercel.app/reactions-inline)
# Setup
Source: https://velt.dev/docs/async-collaboration/reactions/setup
> [tab] React / Next.js
>
> ## 1. Import Velt Inline Reactions Section component
>
> Import the `VeltInlineReactionsSection` component.
>
> ```js theme={null}
> import { VeltInlineReactionsSection } from '@veltdev/react';
> ```
>
> ## 2. Add container to hold Inline Reactions component
>
> * Create an element to hold your Inline Reactions component, such as a `div` or `section`.
> * Add a unique element `id` to it.
>
> ```jsx theme={null}
>
> ```
>
> ## 3. Add VeltInlineReactionsSection component
>
> * Add `VeltInlineReactionsSection` component inside your container.
> * Add `targetReactionElementId` property to the Velt Inline Reactions component. This needs to match the id you set to the container. This binds the Inline Reactions component with the desired container.
>
> ```jsx theme={null}
>
> Your Article
>
> targetReactionElementId="container-id"
> />
>
>
> ```
> [tab] Other Frameworks
>
> ## 1. Add container to hold Inline Reactions component
>
> * Create an element to hold your Inline Reactions component, such as a `div` or `section`.
> * Add a unique element `id` to it.
>
> ```html theme={null}
>
> ```
>
> ## 2. Add Velt Inline Reactions Section component
>
> * Add `velt-inline-reactions-section` component inside your container.
> * Add `target-reaction-element-id` property to the Velt Inline Reactions component. This needs to match the id you set to the container. This binds the Inline Reactions component with the desired container.
>
> ```jsx theme={null}
>
>
> Your Article
>
> target-reaction-element-id="container-id">
>
>
>
> ```
```jsx React / Next.js theme={null}
import { VeltInlineReactionsSection } from '@veltdev/react';
export default function App() {
return (
);
}
```
```html HTML theme={null}
```
# Customize Behavior
Source: https://velt.dev/docs/async-collaboration/recorder/customize-behavior
# AI
#### recordingTranscription
* Controls whether to enable AI transcription for recordings.
* If this is disabled, then the recording will not be sent to LLMs for transcription.
* You can either use the props or the API method to enable/disable this feature.
Default: `enabled`
> [tab] React / Next.js
>
> **Using Props:**
>
> ```jsx theme={null}
>
>
> ```
>
> **Using API:**
>
> ```jsx theme={null}
> const recorderElement = client.getRecorderElement();
> recorderElement.enableRecordingTranscription();
> recorderElement.disableRecordingTranscription();
> ```
> [tab] Other Frameworks
>
> **Using Props:**
>
> ```html theme={null}
>
>
> ```
>
> **Using API:**
>
> ```js theme={null}
> const recorderElement = Velt.getRecorderElement();
> recorderElement.enableRecordingTranscription();
> recorderElement.disableRecordingTranscription();
> ```
#### summary
Controls whether to display a summary transcript of the recording. When enabled, an AI-generated summary of the recording's content will be shown.
Default: `true`
> [tab] React / Next.js
>
> ```jsx theme={null}
>
> ```
> [tab] Other Frameworks
>
> ```jsx theme={null}
>
> ```
# Recording Configuration
#### setMaxLength
* Sets the maximum duration for recordings in seconds.
* You can either use props on components or API methods to configure this feature.
* Default: No limit
> [tab] React / Next.js
>
> **Using Props:**
>
> ```jsx theme={null}
>
>
> ```
>
> **Using API:**
>
> ```jsx theme={null}
> const recorderElement = useRecorderUtils();
> recorderElement.setMaxLength(10);
> ```
> [tab] Other Frameworks
>
> **Using Props:**
>
> ```html theme={null}
>
>
> ```
>
> **Using API:**
>
> ```js theme={null}
> const recorderElement = Velt.getRecorderElement();
> recorderElement.setMaxLength(10);
> ```
#### enablePictureInPicture
* Enables Picture-in-Picture (PiP) mode for screen recordings when camera is enabled.
* This allows users to continue recording while multitasking, improving workflow efficiency for tutorial creation and documentation.
> [!WARNING]
>
> Picture-in-Picture is only supported in Chrome browsers and only works for screen recordings when the camera is active. This feature is disabled by default.
> [tab] React / Next.js
>
> **Using Props:**
>
> ```jsx theme={null}
>
>
> ```
>
> **Using API:**
>
> ```jsx theme={null}
> const recorderElement = useRecorderUtils();
> recorderElement.enablePictureInPicture();
> ```
> [tab] Other Frameworks
>
> **Using Props:**
>
> ```html theme={null}
>
>
> ```
>
> **Using API:**
>
> ```js theme={null}
> const recorderElement = Velt.getRecorderElement();
> recorderElement.enablePictureInPicture();
> ```
#### disablePictureInPicture
* Disables Picture-in-Picture (PiP) mode for screen recordings.
* This prevents users from using the PiP functionality during recording sessions.
> [!WARNING]
>
> Picture-in-Picture is only supported in Chrome browsers and only works for screen recordings when the camera is active. This feature is disabled by default.
> [tab] React / Next.js
>
> **Using Props:**
>
> ```jsx theme={null}
>
>
> ```
>
> **Using API:**
>
> ```jsx theme={null}
> const recorderElement = useRecorderUtils();
> recorderElement.disablePictureInPicture();
> ```
> [tab] Other Frameworks
>
> **Using Props:**
>
> ```html theme={null}
>
>
> ```
>
> **Using API:**
>
> ```js theme={null}
> const recorderElement = Velt.getRecorderElement();
> recorderElement.disablePictureInPicture();
> ```
#### enableRecordingMic
* Turn on user microphone on the recorder control panel.
> [tab] React / Next.js
>
> **Using API:**
>
> ```jsx theme={null}
> const recorderElement = useRecorderUtils();
> recorderElement.enableRecordingMic(); // Enables the microphone.
> recorderElement.disableRecordingMic(); // Disables the microphone.
> ```
> [tab] Other Frameworks
>
> **Using API:**
>
> ```jsx theme={null}
> const recorderElement = Velt.getRecorderElement();
> recorderElement.enableRecordingMic(); // Enables the microphone.
> recorderElement.disableRecordingMic(); // Disables the microphone.
> ```
#### setRecordingQualityConstraints
* Defines quality constraints (e.g., resolution, frame rate) for the raw media input from the user's screen, camera, or microphone, applied before recording begins.
* Higher quality constraints will result in higher upload, download and processing times.
* **Params:** [RecorderQualityConstraints](/docs/api-reference/sdk/models/data-models#recorderqualityconstraints)
* **Returns:** `void`
* **Default:**
```js theme={null}
{
'safari': {
audio: {
sampleRate: 48000,
echoCancellation: true,
noiseSuppression: true,
autoGainControl: true
},
video: {
width: { min: 640, ideal: 1280, max: 1280 },
height: { min: 360, ideal: 720, max: 720 },
frameRate: { min: 15, ideal: 20, max: 30 },
aspectRatio: { ideal: 1.777777778 }
}
},
'other': {
audio: {
sampleRate: 48000,
echoCancellation: true,
noiseSuppression: true,
autoGainControl: true
},
video: {
width: { min: 640, ideal: 1280, max: 1280 },
height: { min: 360, ideal: 720, max: 720 },
frameRate: { min: 15, ideal: 20, max: 30 },
aspectRatio: { ideal: 1.777777778 }
}
}
}
```
> [tab] React / Next.js
>
> ```jsx theme={null}
> const recorderElement = useRecorderUtils();
>
> recorderElement.setRecordingQualityConstraints({
> 'other': {
> 'video': {
> width: { exact: 3024 },
> height: { exact: 1542 },
> frameRate: { exact: 20 },
> }
> }
> });
> ```
> [tab] Other Frameworks
>
> ```js theme={null}
> const recorderElement = Velt.getRecorderElement();
>
> recorderElement.setRecordingQualityConstraints({
> 'other': {
> 'video': {
> width: { exact: 3024 },
> height: { exact: 1542 },
> frameRate: { exact: 20 },
> }
> }
> });
> ```
#### setRecordingEncodingOptions
* Controls the output quality and size of the video or audio file you save after it's been captured.
* Higher quality options will result in higher upload, download and processing times.
* We automatically select the best file format (MIME type) based on the browser and device compatibility. Here is the preferred order in which this is selected:
* `video/mp4;codecs=h264,aac`
* `video/mp4`
* `audio/mp4`
* `video/webm;codecs=vp9,opus`
* `video/webm;codecs=vp8,opus`
* `video/webm;codecs=h264,opus`
* `video/webm`
* **Params:** [RecorderEncodingOptions](/docs/api-reference/sdk/models/data-models#recorderencodingoptions)
* **Returns:** `void`
* **Default:**
```js theme={null}
{
'safari': {
videoBitsPerSecond: 2500000,
audioBitsPerSecond: 128000
},
'other': {
videoBitsPerSecond: 1000000,
audioBitsPerSecond: 128000
}
}
```
> [tab] React / Next.js
>
> ```jsx theme={null}
> const recorderElement = useRecorderUtils();
>
> recorderElement.setRecordingEncodingOptions({
> 'other': {
> videoBitsPerSecond: 2000000,
> audioBitsPerSecond: 128000
> }
> });
> ```
> [tab] Other Frameworks
>
> ```js theme={null}
> const recorderElement = Velt.getRecorderElement();
>
> recorderElement.setRecordingEncodingOptions({
> 'other': {
> videoBitsPerSecond: 2000000,
> audioBitsPerSecond: 128000
> }
> });
> ```
# Permissions
#### requestScreenPermission
* Requests screen capture permissions from the user. This is useful for enabling screen preview functionality in the Recording Preview Dialog.
* **Returns:** `Promise`
> [tab] React / Next.js
>
> ```jsx theme={null}
> const recorderElement = useRecorderUtils();
> await recorderElement.requestScreenPermission();
> ```
> [tab] Other Frameworks
>
> ```js theme={null}
> const recorderElement = Velt.getRecorderElement();
> await recorderElement.requestScreenPermission();
> ```
#### askDevicePermission
* Programmatically requests audio and video permissions from the user. This is useful for creating a custom onboarding flow for device permissions.
* **Params:** `RecorderDevicePermissionOptions`
* **Returns:** `Promise`
> [tab] React / Next.js
>
> ```jsx theme={null}
> const recorderElement = useRecorderUtils();
>
> recorderElement.askDevicePermission({
> audio: true,
> video: true
> });
> ```
> [tab] Other Frameworks
>
> ```js theme={null}
> const recorderElement = Velt.getRecorderElement();
>
> recorderElement.askDevicePermission({
> audio: true,
> video: true
> });
> ```
# Data
#### deleteRecordings
* Deletes recordings by their recorder IDs.
* **Params:** [RecorderRequestQuery](/docs/api-reference/sdk/models/data-models#recorderrequestquery) (optional)
* **Returns:** [`Promise`](/docs/api-reference/sdk/models/data-models#deleterecordingsresponse)
> [tab] React / Next.js
>
> **Using API:**
>
> ```ts theme={null}
> const recorderElement = useRecorderUtils();
> await recorderElement.deleteRecordings({
> recorderIds: ['RECORDER_ID_1']
> });
>
> ```
> [tab] Other Frameworks
>
> ```js theme={null}
> const recorderElement = Velt.getRecorderElement();
> await recorderElement.deleteRecordings({
> recorderIds: ['RECORDER_ID_1']
> });
> ```
#### downloadLatestVideo
* Downloads the latest version of a recording.
* **Params:** `recorderId: string`
* **Returns:** `Promise`
> [tab] React / Next.js
>
> ```js theme={null}
> const recorderElement = client.getRecorderElement();
> await recorderElement.downloadLatestVideo('RECORDER_ID');
> ```
> [tab] Other Frameworks
>
> ```js theme={null}
> const recorderElement = Velt.getRecorderElement();
> await recorderElement.downloadLatestVideo('RECORDER_ID');
> ```
#### fetchRecordings
* Fetches all recordings from either the current document or specified recorder IDs.
* **Params:** [RecorderRequestQuery](/docs/api-reference/sdk/models/data-models#recorderrequestquery) (optional)
* **Returns:** [`Promise`](/docs/api-reference/sdk/models/data-models#getrecordingsresponse)
> [tab] React / Next.js
>
> ```jsx theme={null}
> const recorderElement = useRecorderUtils();
>
> // Fetch all recordings in the current document
> const recorderData = await recorderElement.fetchRecordings();
>
> // Fetch recordings for a specific recorder ID
> const recorderData = await recorderElement.fetchRecordings({
> recorderIds: ['RECORDER_ID']
> });
> ```
> [tab] Other Frameworks
>
> ```js theme={null}
> const recorderElement = Velt.getRecorderElement();
>
> // Fetch all recordings in the current document
> const recorderData = await recorderElement.fetchRecordings();
>
> // Fetch recordings for a specific recorder ID
> const recorderData = await recorderElement.fetchRecordings({
> recorderIds: ['RECORDER_ID']
> });
> ```
#### getRecordings
* Subscribe to all recording data from either the current document or specified recorder IDs.
* **Params:** [RecorderRequestQuery](/docs/api-reference/sdk/models/data-models#recorderrequestquery) (optional)
* **Returns:** [`Observable`](/docs/api-reference/sdk/models/data-models#getrecordingsresponse)
> [tab] React / Next.js
>
> **Using Hook:**
>
> ```jsx theme={null}
> const recordings = useRecordings();
>
> useEffect(() => {
> console.log('recordings', recordings);
> }, [recordings]);
> ```
>
> **Using API:**
>
> ```jsx theme={null}
> const recorderElement = useRecorderUtils();
> // Subscribe to all recordings in the current document
> recorderElement.getRecordings().subscribe((data) => {
> console.log('recordings', data);
> });
>
> // Subscribe to recordings with specific recorder IDs
> recorderElement.getRecordings({
> recorderIds: ['RECORDER_ID']
> }).subscribe((data) => {
> console.log('recordings', data);
> });
> ```
> [tab] Other Frameworks
>
> ```js theme={null}
> const recorderElement = Velt.getRecorderElement();
>
> // Subscribe to all recordings in the current document
> recorderElement.getRecordings().subscribe((data) => {
> console.log('recordings', data);
> });
>
> // Subscribe to recordings with specific recorder IDs
> recorderElement.getRecordings({
> recorderIds: ['RECORDER_ID']
> }).subscribe((data) => {
> console.log('recordings', data);
> });
> ```
# Event Subscription
#### on
* Subscribe to Recorder Events. Here is the list of events you can subscribe to and the event objects you will receive.
| Event Type | Description | Event Object |
| - | - | - |
| `transcriptionDone` | Triggered when a transcription is generated and ready | [TranscriptionDoneEvent](/docs/api-reference/sdk/models/data-models#transcriptiondoneevent) |
| `recordingDoneLocal` | Triggered immediately after a recording annotation is saved locally — before cloud upload and transcription begin. The `assets[0].url` is a blob URL at this point; the permanent CDN URL arrives later via `recordingDone`. Only fires when `sourceFeature === 'recording'`. | [RecordingDoneLocalEvent](/docs/api-reference/sdk/models/data-models#recordingdonelocalevent) |
| `recordingDone` | Triggered when a recording is completed | [RecordingDoneEvent](/docs/api-reference/sdk/models/data-models#recordingdoneevent) |
| `deleteRecording` | Triggered when a recording is deleted | [RecordingDeleteEvent](/docs/api-reference/sdk/models/data-models#recordingdeleteevent) |
| `recordingEditDone` | Triggered when the "Done" button is clicked in the recording editor. Fires after edits are saved, or immediately if no edits were made. | [RecordingEditDoneEvent](/docs/api-reference/sdk/models/data-models#recordingeditdoneevent) |
| `recordingStarted` | Triggered when the recording starts. | [RecordingStartedEvent](/docs/api-reference/sdk/models/data-models#recordingstartedevent) |
| `recordingPaused` | Triggered when the recording is paused. | [RecordingPausedEvent](/docs/api-reference/sdk/models/data-models#recordingpausedevent) |
| `recordingResumed` | Triggered when the recording is resumed after being paused. | [RecordingResumedEvent](/docs/api-reference/sdk/models/data-models#recordingresumedevent) |
| `recordingCancelled` | Triggered when the recording is cancelled. | [RecordingCancelledEvent](/docs/api-reference/sdk/models/data-models#recordingcancelledevent) |
| `recordingStopped` | Triggered when the recording is stopped. | [RecordingStoppedEvent](/docs/api-reference/sdk/models/data-models#recordingstoppedevent) |
| `recordingSaveInitiated` | Triggered when a recording saved is initiated | [RecordingSaveInitiatedEvent](/docs/api-reference/sdk/models/data-models#recordingsaveinitiatedevent) |
| `error` | Triggered when an error occurs. eg: `editFailed`, `recordingFailed`, `transcriptionFailed` | [RecordingErrorEvent](/docs/api-reference/sdk/models/data-models#recordingerrorevent) |
> [tab] React / Next.js
>
> ```jsx theme={null}
> // Hook
> const recorderEventCallbackData = useRecorderEventCallback('transcriptionDone');
> useEffect(() => {
> if (recorderEventCallbackData) {
> // Handle recorder action callback event response
> }
> }, [recorderEventCallbackData]);
>
> // API Method
> const recorderElement = client.getRecorderElement();
> recorderElement.on('transcriptionDone').subscribe((event) => {
> // Handle the event response
> });
>
> ```
> [tab] Other Frameworks
>
> ```js theme={null}
> const recorderElement = Velt.getRecorderElement();
> recorderElement.on('transcriptionDone').subscribe((event) => {
> // Handle the event response
> });
> ```
# Editor
#### autoOpenVideoEditor
* Controls whether to open the video editor automatically when the recording is done.
* Available in `Velt Recorder Control Panel` component.
Default: `false`
> [tab] React / Next.js
>
> ```jsx theme={null}
>
> ```
> [tab] Other Frameworks
>
> ```html theme={null}
>
> ```
#### retakeOnVideoEditor
* Controls whether to enable the retake button on video editor. This will take the user back to the control panel to start a new recording.
Default: `false`
> [tab] React / Next.js
>
> **Using Props (use any one of the following):**
>
> ```jsx theme={null}
>
>
>
> ```
>
> **Using APIs:**
>
> ```jsx theme={null}
> const recorderElement = useRecorderUtils();
>
> // Enable/disable retake button on video editor
> recorderElement.enableRetakeOnVideoEditor();
> recorderElement.disableRetakeOnVideoEditor();
> ```
> [tab] Other Frameworks
>
> **Using Attributes: (use any one of the following)**
>
> ```html theme={null}
>
>
>
> ```
>
> **Using APIs:**
>
> ```jsx theme={null}
> const recorderElement = Velt.getRecorderElement();
>
> // Enable/disable retake button on video editor
> recorderElement.enableRetakeOnVideoEditor();
> recorderElement.disableRetakeOnVideoEditor();
> ```
#### enableOnboardingTooltip
* Controls whether to enable the onboarding tooltip on video editor.
Default: `false`
> [tab] React / Next.js
>
> **Using APIs:**
>
> ```jsx theme={null}
> const recorderElement = useRecorderUtils();
>
> // Enable/disable onboarding tooltip
> recorderElement.enableOnboardingTooltip();
> recorderElement.disableOnboardingTooltip();
> ```
> [tab] Other Frameworks
>
> **Using APIs:**
>
> ```jsx theme={null}
> const recorderElement = Velt.getRecorderElement();
>
> // Enable/disable onboarding tooltip
> recorderElement.enableOnboardingTooltip();
> recorderElement.disableOnboardingTooltip();
> ```
#### videoEditor
* Controls whether to enable the video editor for the `Velt Recorder Player`.
* Works for Video and Screen Recordings.
* Available in `Velt Recorder Notes`, `Velt Recorder Player` and `Velt Recorder Control Panel` components. You could use any of these.
Default: `false`
> [tab] React / Next.js
>
> **Using Props:**
>
> ```jsx theme={null}
> // Use any one of these.
>
>
>
> ```
>
> **Using API:**
>
> ```jsx theme={null}
> const recorderElement = client.getRecorderElement();
> recorderElement.enableVideoEditor();
> recorderElement.disableVideoEditor();
> ```
> [tab] Other Frameworks
>
> **Using Props:**
>
> ```html theme={null}
>
>
>
>
> ```
>
> **Using API:**
>
> ```jsx theme={null}
> const recorderElement = Velt.getRecorderElement();
> recorderElement.enableVideoEditor();
> recorderElement.disableVideoEditor();
> ```
#### videoEditorTimelinePreview
* Controls whether to display image snapshots of frames in the video editor timeline.
* This helps users quickly navigate to specific scenes without scrubbing through the entire video.
Default: `false`
> [!NOTE]
>
> The timeline preview only works when both `videoEditorTimelinePreview` and `videoEditor` are set to `true`.
> [tab] React / Next.js
>
> **Using Props:**
>
> ```jsx theme={null}
>
>
> ```
> [tab] Other Frameworks
>
> **Using Props:**
>
> ```html theme={null}
>
>
> ```
# UI/UX
#### openPictureInPicture
* Opens the Picture-in-Picture window during an active recording session.
* This allows programmatic control to open the PiP window for improved multitasking during recording.
> [!WARNING]
>
> Picture-in-Picture is only supported in Chrome browsers and only works for screen recordings when the camera is active. This feature is disabled by default.
> [tab] React / Next.js
>
> **Using API:**
>
> ```jsx theme={null}
> const recorderElement = useRecorderUtils();
> recorderElement.openPictureInPicture();
> ```
> [tab] Other Frameworks
>
> **Using API:**
>
> ```js theme={null}
> const recorderElement = Velt.getRecorderElement();
> recorderElement.openPictureInPicture();
> ```
#### exitPictureInPicture
* Closes the Picture-in-Picture window during an active recording session.
* This allows programmatic control to exit the PiP window and return to normal recording view.
> [!WARNING]
>
> Picture-in-Picture is only supported in Chrome browsers and only works for screen recordings when the camera is active. This feature is disabled by default.
> [tab] React / Next.js
>
> **Using API:**
>
> ```jsx theme={null}
> const recorderElement = useRecorderUtils();
> recorderElement.exitPictureInPicture();
> ```
> [tab] Other Frameworks
>
> **Using API:**
>
> ```js theme={null}
> const recorderElement = Velt.getRecorderElement();
> recorderElement.exitPictureInPicture();
> ```
#### buttonLabel
Sets a custom label for the `Velt Recorder Tool`.
> [tab] React / Next.js
>
> ```js theme={null}
>
> ```
> [tab] Other Frameworks
>
> ```js theme={null}
>
> ```
#### playVideoInFullScreen
* Controls whether to play the recorded video in fullscreen mode.
* You can use this prop on any of the following components:
* `Velt Recorder Notes`
* `Velt Recorder Control Panel`
* `Velt Recorder Player`
Default: `false`
> [tab] React / Next.js
>
> ```jsx theme={null}
> // Change behaviour globally
>
>
> // Change behaviour for specific player
>
> ```
> [tab] Other Frameworks
>
> ```html theme={null}
>
>
>
> ```
#### playbackOnPreviewClick
Control playback behavior on preview click. Enable or disable the click-to-play/pause functionality on recording previews.
Default: `true`
> [tab] React / Next.js
>
> **Using Props:**
>
> ```jsx theme={null}
>
> ```
>
> **Using API:**
>
> ```jsx theme={null}
> const recorderElement = client.getRecorderElement();
> recorderElement.enablePlaybackOnPreviewClick();
> recorderElement.disablePlaybackOnPreviewClick();
> ```
> [tab] Other Frameworks
>
> **Using Props:**
>
> ```html theme={null}
>
> ```
>
> **Using API:**
>
> ```js theme={null}
> const recorderElement = Velt.getRecorderElement();
> recorderElement.enablePlaybackOnPreviewClick();
> recorderElement.disablePlaybackOnPreviewClick();
> ```
#### recordingCountdown
* Controls whether to display a countdown timer before a recording starts.
* You can either use the props or the API method to enable/disable this feature.
Default: `enabled`
> [tab] React / Next.js
>
> **Using Props:**
>
> ```jsx theme={null}
>
>
> ```
>
> **Using API:**
>
> ```jsx theme={null}
> const recorderElement = client.getRecorderElement();
> recorderElement.enableRecordingCountdown();
> recorderElement.disableRecordingCountdown();
> ```
> [tab] Other Frameworks
>
> **Using Props:**
>
> ```html theme={null}
>
>
> ```
>
> **Using API:**
>
> ```jsx theme={null}
> const recorderElement = Velt.getRecorderElement();
> recorderElement.enableRecordingCountdown();
> recorderElement.disableRecordingCountdown();
> ```
#### settingsEmbedded
* Controls whether to embed the settings in the `Velt Recorder Control Panel` component.
* Available in `Velt Recorder Control Panel` component.
* Please use this together with the Control Panel Wireframes so that you can move the settings panel in a different part of the control panel UI.
Default: `false`
> [tab] React / Next.js
>
> ```jsx theme={null}
>
> ```
> [tab] Other Frameworks
>
> ```html theme={null}
>
> ```
#### mode
The `Velt Recorder Control Panel` has two display modes:
* `floating`: Shows a preview in the bottom left corner of the page, regardless of component placement
* `thread`: Displays the component at its placed location in the DOM
Default: `floating`
> [tab] React / Next.js
>
> ```js theme={null}
>
>
> ```
> [tab] Other Frameworks
>
> ```html theme={null}
>
>
> ```
#### type
Sets the recording mode for the `Velt Recorder Tool`.
Available modes:
* `all` - Records audio, video and screen
* `audio` - Records audio only
* `video` - Records video only
* `screen` - Records screen only
Default: `audio`
> [tab] React / Next.js
>
> ```js theme={null}
>
>
>
>
> ```
> [tab] Other Frameworks
>
> ```js theme={null}
>
>
>
>
> ```
# Legacy Methods
#### onRecordedData
The `onRecordedData` callback is triggered when a recording is completed.
* Callback returns [RecorderData](/docs/api-reference/sdk/models/data-models#recorderdata) object.
> [tab] React / Next.js
>
> **Using Props:**
>
> ```jsx theme={null}
> const onRecordedData = (recorderAddEvent) => {
> console.log(recorderAddEvent);
> }
> return (
>
> )
>
> ```
> [tab] Other Frameworks
>
> **Using Event Listener:**
>
> ```js theme={null}
> const recorderControlPanel = document.querySelector('velt-recorder-control-panel');
> recorderControlPanel?.addEventListener('onRecordedData', (s) => {
> console.log('onRecordedData', s.detail);
> });
> ```
# Recorder
Source: https://velt.dev/docs/async-collaboration/recorder/overview
The Recorder allows your users to create audio, screen, and video recordings.
The Velt Recorder consists of 4 key components:
* **Velt Recorder Notes**: Enables pinning recordings to specific locations on the screen
* **Velt Recorder Tool**: A button to initiate recordings
* **Velt Recorder Control Panel**: Controls for managing active recordings (start/stop/pause)
* **Velt Recorder Player**: Plays back recordings using their unique ID
* **Velt Video Editor**: An embeddable component for viewing and editing video annotations.
> [tab] All
>
> [https://recorder-landing-page-demo.vercel.app/?type=all\&backgroundColor=black\&darkMode=true](https://recorder-landing-page-demo.vercel.app/?type=all\&backgroundColor=black\&darkMode=true)
>
> [Open in larger window](https://recorder-landing-page-demo.vercel.app/?type=all\&backgroundColor=black\&darkMode=true)
> [tab] Audio
>
> [https://recorder-landing-page-demo.vercel.app/?type=audio\&backgroundColor=black\&darkMode=true](https://recorder-landing-page-demo.vercel.app/?type=audio\&backgroundColor=black\&darkMode=true)
>
> [Open in larger window](https://recorder-landing-page-demo.vercel.app/?type=audio\&backgroundColor=black\&darkMode=true)
> [tab] Video
>
> [https://recorder-landing-page-demo.vercel.app/?type=video\&backgroundColor=black\&darkMode=true](https://recorder-landing-page-demo.vercel.app/?type=video\&backgroundColor=black\&darkMode=true)
>
> [Open in larger window](https://recorder-landing-page-demo.vercel.app/?type=video\&backgroundColor=black\&darkMode=true)
> [tab] Screen
>
> [https://recorder-landing-page-demo.vercel.app/?type=screen\&backgroundColor=black\&darkMode=true](https://recorder-landing-page-demo.vercel.app/?type=screen\&backgroundColor=black\&darkMode=true)
>
> [Open in larger window](https://recorder-landing-page-demo.vercel.app/?type=screen\&backgroundColor=black\&darkMode=true)
# Setup
Source: https://velt.dev/docs/async-collaboration/recorder/setup
**1. Add the Velt Recorder Tool component**
* Add the `Velt Recorder Tool` component wherever you want the recorder button to appear.
* Set the `type` attribute of the `Velt Recorder Tool` component to one of the following:
* `all`
* `audio`
* `video`
* `screen`
> [tab] React / Next.js
>
> ```js theme={null}
>
>
>
> ```
> [tab] HTML/ Other frameworks
>
> ```html theme={null}
>
>
>
> ```
**2. Add the Velt Recorder Control Panel component**
* Add the `Velt Recorder Control Panel` component wherever you want the control panel to appear.
* When a user clicks on the `Velt Recorder Tool` button, the `Velt Recorder Control Panel` component will show the recording preview with options to save, pause, or delete the recording.
* Set the `mode` attribute on the `VeltRecorderControlPanel` component to either `floating` (default) or `thread`.
To learn more about `floating` or `thread` mode [read here](/docs/async-collaboration/recorder/customize-behavior#mode).
> [tab] React / Next.js
>
> ```js theme={null}
>
>
>
>
> ```
> [tab] HTML/ Other frameworks
>
> ```html theme={null}
>
>
>
>
> ```
**3. Render recorded data in Velt Recorder Player**
* After a user has finished recording, you will receive the recorded data in an event callback.
* Add the `Velt Recorder Player` component with the `recorderId` from the event callback.
* It displays the recorded data with controls such as pause, play, edit and delete.
> [tab] React / Next.js
>
> ```js theme={null}
> const recorderAddEvent = useRecorderAddHandler();
> const [recorderId, setRecorderId] = useState(null);
> useEffect(() => {
> setRecorderId(recorderAddEvent.id);
> }, [recorderAddEvent]);
>
>
> {recorderId && }
>
> ```
> [tab] HTML/ Other frameworks
>
> ```js theme={null}
> const recorderElement = Velt.getRecorderElement();
> recorderElement.onRecordedData().subscribe((recorderAddEvent) => {
> setRecorderId(recorderAddEvent.id);
> });
> ```
>
> ```html theme={null}
>
>
>
> ```
**4. Enable Recording Editor (optional)**
* Recording Editor is currently in beta and is not enabled by default.
* It is only available for video and screen recordings.
* It has the following default keyboard shortcuts:
* `s`: Split the video at the selected frame.
* `d`, `delete`, or `backspace`: Delete the selected video section.
* `space`: Toggle video play/pause.
> [tab] React / Next.js
>
> ```js theme={null}
> const recorderElement = client.getRecorderElement();
> recorderElement.enableVideoEditor();
> ```
> [tab] HTML/ Other frameworks
>
> ```js theme={null}
> const recorderElement = Velt.getRecorderElement();
> recorderElement.enableVideoEditor();
> ```
**5. Embed Velt Video Editor (optional)**
* Embed the `Velt Video Editor` standalone component directly into your application.
* It can be used to view and edit video recordings.
* You can initialize the editor with a video from a URL, a Blob, or by using a `recorderId`.
> [tab] React / Next.js
>
> ```jsx theme={null}
> blob={blob}
> url="videourl.mp4"
> darkMode={true}
> variant="xyz"
> recorderId="zK3iEAfvs1Htu3QYPy5S"
> />
> ```
> [tab] Other Frameworks
>
> ```html theme={null}
> blob="blob"
> url="videourl.mp4"
> recorder-id="zK3iEAfvs1Htu3QYPy5S"
> dark-mode="true"
> variant="xyz"
> >
> ```
```js React / Next.js theme={null}
import { VeltRecorderTool, VeltRecorderControlPanel, VeltRecorderPlayer } from '@veltdev/react'
function TaskInputBox() {
return (
)
}
```
```html HTML theme={null}
```
# Suggestions (Beta)
Source: https://velt.dev/docs/async-collaboration/suggestions/overview
Capture edits from humans or AI agents as reviewable suggestions in Velt, with diff-style accept and reject actions on the comment dialog.
## Overview
The Suggestions API adds **suggestion mode** to any input, editor, or custom component in your app. When it's on, edits from a human (or an AI agent) aren't written straight to your data. They're captured as proposed changes that a reviewer accepts or rejects from the comment dialog, diff-style, like Google Docs suggestions. On accept, your app applies the change.
You mark any DOM element as a **suggestion target** with a single attribute. The SDK captures the before and after values, saves each edit as a [`Suggestion`](/docs/api-reference/sdk/models/data-models#suggestiont), and shows accept/reject buttons on the comment dialog.
> [!NOTE]
>
> The accept/reject UI renders on the Velt comment dialog, so your app needs Velt [Comments](/docs/async-collaboration/comments/overview) set up. That's where reviewers act on a suggestion.
## How it works
1. **You enable suggestion mode.** The SDK starts watching every element tagged with `data-velt-suggestion-target=""`, including elements added to the DOM later.
2. **A user focuses a target.** The SDK snapshots the target's current value as the `oldValue` for that edit session.
3. **A user edits and commits the change** (for example, by clicking away from a text field). The SDK reads the new value, compares it to the snapshot, and creates a **pending** [`Suggestion`](/docs/api-reference/sdk/models/data-models#suggestiont) only if they differ.
4. **A reviewer accepts or rejects** from the comment dialog. The outcome is emitted on the comment element as the `suggestionAccepted` / `suggestionRejected` events.
5. **Your app applies the change.** Your `suggestionAccepted` handler reads `commentAnnotation.suggestion.newValue` and writes it into your own state or backend.
## Properties
* A suggestion is a regular comment annotation with `type: "suggestion"` and a populated [`suggestion`](/docs/api-reference/sdk/models/data-models#suggestiondata) field. There is no separate suggestions data store. An annotation marked `type: "suggestion"` (or `commentType: "suggestion"`) without a full `suggestion` payload (for example, one created over REST) is backfilled to a pending suggestion state at render time, so accept and reject still work.
* Suggestion mode is global for the current user and **not persisted**. A page reload returns to normal editing until you enable it again.
* An edit is committed when the user finishes it, not on every keystroke. Text-like inputs (text, number, date, textarea, contenteditable) commit when the field loses focus (`focusout`), so each focus session produces at most one suggestion. Dropdowns, checkboxes, and radios commit on `change`, since picking a value is the whole edit.
* Unchanged values never create suggestions. Focusing and blurring without editing is ignored, and `commitSuggestion` rejects a `newValue` that's identical to the old value.
* Events come from two elements: accept/reject outcomes are emitted on the **comment element**, while the rest of the lifecycle (`suggestionCreated`, `suggestionStale`, `targetEditStart`, `targetEditCommit`) is emitted on the **SuggestionElement**. See [Event subscription](#event-subscription).
* **The SDK never mutates your data.** It captures intent, orchestrates review, and persists the outcome. Applying the change is your code's job.
* Drift detection is best-effort. On accept, if a getter is registered, the live value is compared against `oldValue`; a mismatch sets `driftDetected: true` on the suggestion. v1 records the flag; a future release will surface a confirmation prompt.
* Stale wins over drift. If the target DOM node can't be resolved at accept time, the suggestion transitions to `stale` immediately and drift detection is skipped.
## APIs
### Frontend APIs
Follow these steps to add suggestions to your app. Steps 1 and 2 are the minimum to capture suggestions; step 3 controls *how* edits become suggestions, step 4 applies them once accepted, and step 5 lets you query suggestions for your own UI.
All Suggestions methods live on a single `SuggestionElement` instance. Get it once and reuse it. In React, the hooks shown below wrap it for you, so you rarely need the element directly:
> [tab] React / Next.js
>
> ```jsx theme={null}
> import { useSuggestionUtils } from '@veltdev/react';
>
> const suggestionElement = useSuggestionUtils();
> ```
> [tab] Other Frameworks
>
> ```js theme={null}
> const suggestionElement = Velt.getSuggestionElement();
> ```
#### 1. Define Suggestion Targets
Add the `data-velt-suggestion-target=""` attribute to any element you want to track. The `targetId` is an ID you own and should stay stable, like the ID of the record the input edits. Don't generate a random ID on each render: if the `targetId` changes, the SDK can't match suggestions back to the element.
> [tab] React / Next.js
>
> ```jsx theme={null}
>
> ```
> [tab] Other Frameworks
>
> ```html theme={null}
>
> ```
**Do you need `registerTarget`? Usually not.** For a single input, the SDK reads the value on its own: it checks for a registered getter first, then the form value (`.value` / `.checked`), then `textContent`. So **a plain ` ` needs no `registerTarget` call**. You only need it when one target covers several inputs at once, like a table row with a `qty` field and a `price` field. There's no single `.value` to read in that case, so you provide a getter function that returns the whole object:
> [tab] React / Next.js
>
> ```jsx theme={null}
> import { useRegisterTarget, useUnregisterTarget } from '@veltdev/react';
> import { useEffect } from 'react';
>
> function EditableRow() {
> const { registerTarget } = useRegisterTarget();
> const { unregisterTarget } = useUnregisterTarget();
>
> useEffect(() => {
> registerTarget({
> targetId: 'row.123',
> getter: () => ({
> qty: Number(document.getElementById('qty-input').value),
> price: Number(document.getElementById('price-input').value),
> }),
> });
> return () => unregisterTarget('row.123');
> }, []);
>
> return (
>
>
>
>
> );
> }
> ```
> [tab] Other Frameworks
>
> ```js theme={null}
> suggestionElement.registerTarget({
> targetId: 'row.123',
> getter: () => ({
> qty: Number(document.getElementById('qty-input').value),
> price: Number(document.getElementById('price-input').value),
> }),
> });
>
> // Later, to remove the getter:
> suggestionElement.unregisterTarget('row.123');
> ```
> [!WARNING]
>
> **Your getter must return what the user currently sees, not what's saved.** The SDK calls it twice: on focus to capture `oldValue`, and on commit to capture `newValue`. If it reads from app state that only updates *after* the user saves (common when suggestion mode is on), both calls return the same value and no suggestion is ever created. Read from the DOM (`input.value`), or for controlled inputs that update state on every keystroke, from that state.
> [!NOTE]
>
> `registerTarget()` doesn't return an unsubscribe function. To remove a registration, call `unregisterTarget(targetId)`.
##### Setter
Add a `setter` to let the SDK write values into a target your app owns, such as form state. It runs only on the client of the user who made the change.
* `reason: 'restore'`: runs after the edit is committed, with the value from before the edit. Set `restoreOnCommit: false` to skip it.
* `reason: 'accept'`: runs when this client accepts a suggestion, with the accepted value. `context.suggestion` is the accepted [Suggestion](/docs/api-reference/sdk/models/data-models#suggestiont).
Without a `setter`, the SDK never writes to the target.
> [tab] React / Next.js
>
> ```jsx theme={null}
> // Hook
> const { registerTarget } = useRegisterTarget();
>
> registerTarget({
> targetId: 'assignee',
> getter: () => form.assignee,
> setter: (value, context) => {
> form.assignee = value;
> if (context.reason === 'accept') saveForm();
> },
> });
>
> // API Method
> const suggestionElement = client.getSuggestionElement();
> suggestionElement.registerTarget({
> targetId: 'assignee',
> getter: () => form.assignee,
> setter: (value, context) => {
> form.assignee = value;
> if (context.reason === 'accept') saveForm();
> },
> });
> ```
> [tab] Other Frameworks
>
> ```js theme={null}
> const suggestionElement = Velt.getSuggestionElement();
> suggestionElement.registerTarget({
> targetId: 'assignee',
> getter: () => form.assignee,
> setter: (value, context) => {
> form.assignee = value;
> if (context.reason === 'accept') saveForm();
> },
> });
> ```
> [!NOTE]
>
> Save the accepted value inside the `'accept'` call. Don't save on every edit while suggestion mode is on.
##### Inline tracked changes
A `contenteditable` suggestion target (outside `.ProseMirror`) shows pending suggestions in the field. Removed text is struck through and added text is green. Click a change to open its thread. Each separate edit becomes its own suggestion.
This is on by default. Call `disableInlineSuggestions()` if you save the field's `innerHTML` or your framework controls its children. Call `enableInlineSuggestions()` to turn it back on.
> [tab] React / Next.js
>
> ```jsx theme={null}
> // Hook
> const { disableInlineSuggestions } = useDisableInlineSuggestions();
> const { enableInlineSuggestions } = useEnableInlineSuggestions();
> disableInlineSuggestions();
> enableInlineSuggestions();
>
> // API Method
> const suggestionElement = client.getSuggestionElement();
> suggestionElement.disableInlineSuggestions();
> suggestionElement.enableInlineSuggestions();
> ```
> [tab] Other Frameworks
>
> ```js theme={null}
> const suggestionElement = Velt.getSuggestionElement();
> suggestionElement.disableInlineSuggestions();
> suggestionElement.enableInlineSuggestions();
> ```
Rich-text editors can pass [SuggestionTextChange](/docs/api-reference/sdk/models/data-models#suggestiontextchange) as `textChange` on `commitSuggestion` or the `onTargetEditCommit` result. For `contenteditable` targets, the SDK sets it if you omit it.
Style the changes with these CSS custom properties:
| Custom property | Default |
| - | - |
| `--velt-suggestion-removed-color` | `#b42318` |
| `--velt-suggestion-removed-bg` | `rgba(180, 35, 24, 0.10)` |
| `--velt-suggestion-added-color` | `#067647` |
| `--velt-suggestion-added-bg` | `rgba(6, 118, 71, 0.14)` |
#### 2. Enable Suggestion Mode
Nothing is captured until you turn suggestion mode on, typically from a "Suggest changes" toggle in your toolbar. It applies to the whole page for the current user and **resets on page reload**, so enable it again after a refresh. Pass an optional [`EnableSuggestionModeConfig`](/docs/api-reference/sdk/models/data-models#enablesuggestionmodeconfig) to control how edits become suggestions (see [step 3](#3-capture-edits-as-suggestions)).
> [tab] React / Next.js
>
> ```jsx theme={null}
> import { useEnableSuggestionMode, useDisableSuggestionMode } from '@veltdev/react';
>
> function Toolbar() {
> const { enableSuggestionMode } = useEnableSuggestionMode();
> const { disableSuggestionMode } = useDisableSuggestionMode();
>
> return (
> enableSuggestionMode()}>Suggest changes
> );
> }
> ```
> [tab] Other Frameworks
>
> ```js theme={null}
> suggestionElement.enableSuggestionMode();
>
> // Later, return targets to normal editing:
> suggestionElement.disableSuggestionMode();
> ```
To show the current mode in your UI (for example, to highlight the "Suggesting" toggle), subscribe to it instead of reading it once:
> [tab] React / Next.js
>
> ```jsx theme={null}
> import { useSuggestionModeState } from '@veltdev/react';
>
> const isSuggesting = useSuggestionModeState(); // boolean, updates reactively
> ```
> [tab] Other Frameworks
>
> ```js theme={null}
> // Synchronous read
> const isSuggesting = suggestionElement.isSuggestionModeEnabled();
>
> // Reactive stream
> suggestionElement.isSuggestionModeEnabled$().subscribe((isEnabled) => {
> console.log('Suggestion mode:', isEnabled);
> });
> ```
#### 3. Capture Edits as Suggestions
When a user finishes an edit, you decide how it becomes a suggestion. There are four ways, from simplest to most control. Use one per target; only one of them handles any given edit.
**Option 1: Zero-config auto-commit (default)**
The simplest setup: enable suggestion mode with no handler at all. Every finished edit on a tagged target automatically becomes a pending suggestion, using the SDK's default diff summary (a styled before/after diff; see [Rich HTML summaries with `summaryHtml`](#rich-html-summaries-with-summaryhtml)). This is controlled by the `autoCommit` flag on [`EnableSuggestionModeConfig`](/docs/api-reference/sdk/models/data-models#enablesuggestionmodeconfig), which **defaults to `true`**. Pass `autoCommit: false` for **detect-only mode**: edits still fire the `targetEditCommit` event, but no suggestion is created until you call the `commitSuggestion` function on the event payload (see Option 3).
> [tab] React / Next.js
>
> ```jsx theme={null}
> import { useEnableSuggestionMode } from '@veltdev/react';
>
> const { enableSuggestionMode } = useEnableSuggestionMode();
>
> // Zero-config: edits on tagged targets auto-commit as suggestions.
> enableSuggestionMode();
>
> // Detect-only: events fire, but nothing commits until you
> // call `commitSuggestion` on the event payload (Option 3).
> enableSuggestionMode({ autoCommit: false });
> ```
> [tab] Other Frameworks
>
> ```js theme={null}
> // Zero-config: edits on tagged targets auto-commit as suggestions.
> suggestionElement.enableSuggestionMode();
>
> // Detect-only: events fire, but nothing commits until you
> // call `commitSuggestion` on the event payload (Option 3).
> suggestionElement.enableSuggestionMode({ autoCommit: false });
> ```
> [!NOTE]
>
> `autoCommit` is ignored when you pass `onTargetEditCommit` (Option 2): the handler always wins, even when it returns `null` to skip creating a suggestion (see the Tip under Option 2). Calling `disableSuggestionMode()` clears the flag; if you re-enable suggestion mode without passing `autoCommit: false` again, you're back to the default (`true`).
**Option 2: Customize each suggestion with `onTargetEditCommit`**
Pass `onTargetEditCommit` when you enable suggestion mode. The SDK calls it with the old and new values every time a user finishes an edit. Return an object and the SDK creates the suggestion right away, using your `summary`, `summaryHtml`, and `metadata`. Use this when you want per-edit control over the suggestion body without subscribing to the `targetEditCommit` event (Option 3). (`onTargetEditStart` fires when editing begins; it's informational in v1 and its return value is reserved for future use.)
> [tab] React / Next.js
>
> ```jsx theme={null}
> const { enableSuggestionMode } = useEnableSuggestionMode();
>
> enableSuggestionMode({
> onTargetEditStart: ({ targetId, oldValue }) => {
> // Informational: a user just started editing `targetId` (oldValue snapshotted).
> },
> onTargetEditCommit: ({ targetId, oldValue, newValue }) => {
> // Returning a result auto-creates the suggestion.
> return {
> summary: `${targetId}: ${oldValue} → ${newValue}`,
> metadata: { source: 'inline-edit' },
> };
> },
> });
> ```
> [tab] Other Frameworks
>
> ```js theme={null}
> suggestionElement.enableSuggestionMode({
> onTargetEditCommit: ({ targetId, oldValue, newValue }) => {
> return {
> summary: `${targetId}: ${oldValue} → ${newValue}`,
> metadata: { source: 'inline-edit' },
> };
> },
> });
> ```
> [!TIP]
>
> Don't want every edit to become a suggestion automatically? Return `null` from `onTargetEditCommit` (or leave the handler out **and** pass `autoCommit: false`) and handle the edit yourself with the `targetEditCommit` event below, for example to validate the value or ask the user to confirm first.
**Option 3: Decide per edit with the `targetEditCommit` event**
Enable suggestion mode with `autoCommit: false` and no `onTargetEditCommit` handler, then subscribe to the `targetEditCommit` event. The event gives you the edit details plus a `commitSuggestion` function that's already tied to that edit. Call it to create the suggestion (you can override `summary` / `summaryHtml` / `metadata`), or don't call it to discard the edit. Nothing is created until you call it. Without `autoCommit: false`, the SDK commits each edit itself (Option 1); once that auto-commit succeeds, the event's `commitSuggestion` becomes a no-op for that edit (if the auto-commit fails, you can still call it to retry).
> [tab] React / Next.js
>
> ```jsx theme={null}
> import { useEnableSuggestionMode, useSuggestionEventCallback } from '@veltdev/react';
> import { useEffect } from 'react';
>
> function CommitGate() {
> const { enableSuggestionMode } = useEnableSuggestionMode();
>
> useEffect(() => {
> // Detect-only: without this, the SDK auto-commits before your gate runs.
> enableSuggestionMode({ autoCommit: false });
> }, []);
>
> const commitEvent = useSuggestionEventCallback('targetEditCommit');
>
> useEffect(() => {
> if (!commitEvent) return;
> const { details, commitSuggestion } = commitEvent;
> if (isValid(details.newValue)) {
> commitSuggestion({ summary: `Update ${details.targetId}` });
> }
> }, [commitEvent]);
>
> return null;
> }
> ```
> [tab] Other Frameworks
>
> ```js theme={null}
> // Detect-only: without this, the SDK auto-commits before your gate runs.
> suggestionElement.enableSuggestionMode({ autoCommit: false });
>
> suggestionElement.on('targetEditCommit').subscribe(({ details, commitSuggestion }) => {
> // `commitSuggestion` is already tied to this edit. Call it to create
> // the suggestion, or skip it to discard this edit.
> if (isValid(details.newValue)) {
> commitSuggestion({ summary: `Update ${details.targetId}` });
> }
> });
> ```
**Option 4: Create suggestions manually with `startSuggestion` / `commitSuggestion`**
When there's no input for the SDK to watch (a custom widget, a canvas element, or an "AI proposes a change" button), create the suggestion yourself. Call `startSuggestion(targetId)` to capture the current value as `oldValue`, then `commitSuggestion(config)` with the `newValue` to create it.
> [tab] React / Next.js
>
> ```jsx theme={null}
> import { useStartSuggestion, useCommitSuggestion } from '@veltdev/react';
>
> function ProposeButton() {
> const { startSuggestion } = useStartSuggestion();
> const { commitSuggestion } = useCommitSuggestion();
>
> const propose = async () => {
> startSuggestion('row.123'); // snapshot oldValue now
> const { id } = await commitSuggestion({
> targetId: 'row.123',
> newValue: { qty: 7, price: 99 },
> summary: 'Bump qty + price',
> metadata: { source: 'manual' },
> });
> console.log('Created suggestion', id);
> };
>
> return Propose change ;
> }
> ```
> [tab] Other Frameworks
>
> ```js theme={null}
> suggestionElement.startSuggestion('row.123');
>
> const { id } = await suggestionElement.commitSuggestion({
> targetId: 'row.123',
> newValue: { qty: 7, price: 99 },
> summary: 'Bump qty + price',
> metadata: { source: 'manual' },
> });
> ```
> [!NOTE]
>
> `commitSuggestion` only works while suggestion mode is on and the `targetId` is known to the SDK (tagged in the DOM or registered via `registerTarget`). It also creates nothing when `newValue` is identical to the captured `oldValue`.
##### Rich HTML summaries with `summaryHtml`
When a suggestion is created, the SDK adds a first comment to its thread. That comment is the body the suggestion card displays, built from the `summary` you provide. Pass an optional `summaryHtml` alongside `summary` (in the config you pass to `commitSuggestion`, in the object you return from `onTargetEditCommit`, or in the overrides you pass to the event's `commitSuggestion` function) to render a formatted body, for example a color-coded before/after diff. `summaryHtml` becomes the comment's `commentHtml`; plain `summary` (or the SDK's default diff text) stays in `commentText` as the fallback.
If you pass only `summary`, the comment's `commentHtml` is the HTML-escaped summary wrapped in a `` tag, so existing `summary`-only usage renders exactly as before. If you provide neither, the SDK renders a default styled HTML diff (old value in red italic, new value in green italic).
> [tab] React / Next.js
>
> ```jsx theme={null}
> import { useCommitSuggestion } from '@veltdev/react';
>
> const { commitSuggestion } = useCommitSuggestion();
>
> await commitSuggestion({
> targetId: 'price-field',
> newValue: 6000,
> summary: 'Price: $5,000 → $6,000',
> summaryHtml: '
Price: $5,000 $6,000
',
> });
> ```
> [tab] Other Frameworks
>
> ```js theme={null}
> await suggestionElement.commitSuggestion({
> targetId: 'price-field',
> newValue: 6000,
> summary: 'Price: $5,000 → $6,000',
> summaryHtml: 'Price: $5,000 $6,000
',
> });
> ```
> [!NOTE]
>
> `summaryHtml` is sanitized with DOMPurify at render time: `
```
# Node SDK for self-hosting and REST API calls
Source: https://velt.dev/docs/backend-sdks/node
Integrate the Velt Node SDK in Node.js or TypeScript to self-host data with MongoDB or PostgreSQL and S3, or call Velt's REST APIs from your backend.
## Overview
The [Velt Node SDK](https://www.npmjs.com/package/@veltdev/node) exposes two independent backends:
| Backend | Namespace | Use case |
| - | - | - |
| Self-hosting | `sdk.selfHosting.*` | Store Velt data in your own MongoDB or PostgreSQL, plus AWS S3 for attachments |
| REST API | `sdk.api.*` | Call Velt's REST APIs directly from your backend |
**Self-hosting backend** (`sdk.selfHosting.*`) simplifies backend implementation by **90%**. Instead of writing custom database queries and storage logic, you:
1. Pass your DB and storage configs to the SDK
2. Call the relevant SDK method with the raw request payload
3. Return the resulting response directly to the client
**REST API backend** (`sdk.api.*`) provides parity with [Velt's REST APIs](/docs/api-reference/rest-apis/v2/organizations/get-organizations-v2). 19 services, fully-typed TypeScript request objects, and raw Velt API responses. No database or AWS configuration needed.
## Installation
Install the driver for the database you self-host on. The core package carries no database driver.
```bash theme={null}
npm install @veltdev/node # REST API backend only
npm install @veltdev/node mongodb # + self-hosting on MongoDB
npm install @veltdev/node pg # + self-hosting on PostgreSQL
npm install @aws-sdk/client-s3 # only if you use S3 for attachments
npm install jose@^5 # only for the built-in JWT/JWKS verifyToken path
```
A `database` config whose driver is not installed fails at `initialize()` with the command to run, for example `MongoDB support requires 'npm install mongodb'` or `PostgreSQL support requires 'npm install pg'`.
> [!WARNING]
>
> **Upgrading from 1.x:** version 2.0.0 changes these behaviors.
>
> * The database driver is checked at `initialize()`. A config with a `database` block fails at startup when its driver (`mongodb` or `pg`) is not installed. If you only call `sdk.api.*`, remove the `database` block instead.
> * `saveAttachment` stores a closed set of fields: `attachmentId`, `file` (the URL), `name`, `mimeType`, and `metadata` (`organizationId`, `documentId`, `folderId`, `attachmentId`, `commentAnnotationId`, `apiKey`). Other fields, a top-level `url`, and null metadata keys are no longer stored. A save without a `file` URL or file data returns 400.
> * An empty `organizationId` in `getComments`, `getReactions`, `getRecorderAnnotations`, and `getNotifications` returns 400 with `errorCode: 'INVALID_INPUT'`.
> * An unknown `database.type` throws at `initialize()`. A second SDK instance pointed at a different database without `await sdk.close()` throws at its first `sdk.selfHosting.*` call.
### Requirements
* Node.js 18+
* TypeScript 5.x (optional; JavaScript is fully supported)
* For self-hosting, one of:
* MongoDB 6+ (Percona Server or MongoDB Atlas) with `mongodb` ^6
* PostgreSQL 14+ with `pg` ^8.16
* `@aws-sdk/client-s3` ^3 and `jose` ^5 (for [`verifyToken`](#verifytoken)) as optional peer dependencies
## Quick Start
### Initialize the SDK
> [tab] Self-hosting
>
> Self-hosting initialization (MongoDB or PostgreSQL, plus optional AWS S3):
>
> ```ts theme={null}
> import { VeltSDK } from '@veltdev/node';
>
> const sdk = VeltSDK.initialize({
> database: {
> // MongoDB (default type)
> connection_string: 'mongodb+srv://user:pass@cluster.mongodb.net/velt-db',
>
> // PostgreSQL: set the type and use a PostgreSQL connection string instead
> // type: 'postgresql',
> // connection_string: 'postgresql://user:pass@host:5432/velt',
> },
> apiKey: 'YOUR_VELT_API_KEY',
> authToken: 'YOUR_VELT_AUTH_TOKEN'
> });
> ```
> [tab] REST API
>
> REST API initialization needs no `database` block:
>
> ```ts theme={null}
> import { VeltSDK } from '@veltdev/node';
>
> const sdk = VeltSDK.initialize({
> apiKey: 'YOUR_VELT_API_KEY',
> authToken: 'YOUR_VELT_AUTH_TOKEN'
> });
>
> // All sdk.api.* services are now available
> const result = await sdk.api.organizations.getOrganizations({ organizationIds: ['org-123'] });
> ```
>
> Set `VELT_API_KEY` and `VELT_AUTH_TOKEN` environment variables as an alternative to passing credentials in the config object. On an SDK initialized without a `database` block, `sdk.selfHosting.*` methods throw a `VeltDatabaseError` saying a `database` block is required.
### Shutdown
Call `await sdk.close()` when your process exits to release the database connection pool.
## Configuration
### Environment Variables
| Variable | Config key equivalent | Purpose |
| - | - | - |
| `VELT_API_KEY` | `apiKey` | Velt API key for authenticating REST API calls |
| `VELT_AUTH_TOKEN` | `authToken` | Velt auth token for authenticating REST API calls |
| `VELT_WORKSPACE_ID` | — | Default workspace ID for workspace-scoped operations |
| `VELT_WORKSPACE_AUTH_TOKEN` | — | Auth token scoped to a specific workspace |
| `AWS_ACCESS_KEY_ID` | — | AWS access key for S3 attachments |
| `AWS_SECRET_ACCESS_KEY` | — | AWS secret key for S3 attachments |
| `AWS_REGION` | — | AWS region for S3 |
| `AWS_S3_BUCKET_NAME` | — | S3 bucket name for attachments |
| `AWS_S3_ENDPOINT_URL` | — | Custom S3 endpoint (e.g., for MinIO) |
### Self-Hosting Configuration
> [tab] Database
>
> Configure the database that stores comments, reactions, and user data. `type` selects the backend: `mongodb` (default) or `postgresql`. Every `sdk.selfHosting.*` method behaves the same on both.
>
> ```ts MongoDB theme={null}
> const sdk = VeltSDK.initialize({
> database: {
> // Option 1: Connection string (the database name comes from its path)
> connection_string: 'mongodb+srv://user:pass@cluster.mongodb.net/velt-db',
>
> // Option 2: Individual components
> // host: 'localhost:27017',
> // username: 'your-username',
> // password: 'your-password',
> // auth_database: 'admin',
> // database_name: 'velt-db',
>
> // Optional (defaults shown)
> // type: 'mongodb',
> // use_srv: true, // use mongodb+srv:// (auto-detected for *.mongodb.net hosts)
> // pool_min_size: 1,
> // pool_max_size: 5,
> }
> });
> ```
>
> ```ts PostgreSQL theme={null}
> const sdk = VeltSDK.initialize({
> database: {
> type: 'postgresql',
> // Option 1: Connection string (URI or libpq key/value form)
> connection_string: 'postgresql://user:pass@host:5432/velt',
>
> // Option 2: Individual components
> // host: 'host', // may include the port, for example 'host:5433'
> // port: 5432,
> // username: 'your-username',
> // password: 'your-password',
> // database_name: 'velt',
>
> // Optional (defaults shown)
> // schema: 'public',
> // sslmode: 'prefer', // use 'verify-full' with sslrootcert for remote databases
> // sslrootcert: undefined, // path to the CA certificate file
> // connect_timeout: 10, // seconds
> // application_name: 'velt-node/',
> // pool_min_size: 1,
> // pool_max_size: 5,
> // pool_timeout: 10, // seconds a query waits for a pooled connection
> // manage_schema: true,
> // connection_options: {}, // extra connection parameters passed to node-postgres
> }
> });
> ```
>
> `database_name` overrides the database named in `connection_string` on both backends. `pool_min_size` and `pool_max_size` apply to both and are validated at `initialize()`.
>
> **How PostgreSQL storage works**
>
> * One table per collection (`comment_annotations`, `reaction_annotations`, `recorder_annotations`, `notifications`, `activities`, `attachments`, `users`) with a single JSONB `data` column that holds the document, plus expression indexes on the fields the SDK queries. The `collections` option renames these tables.
> * On first connection the SDK creates the schema, tables, and indexes (`manage_schema: true`). The role needs `CREATE` on the schema. Concurrent application starts coordinate through a per-schema advisory lock, so they do not race; a process that waits more than 60 seconds skips setup and logs a warning.
> * For locked-down roles set `manage_schema: false` and apply the DDL yourself. Generate it for your exact config and hand it to a migration role:
>
> ```ts theme={null}
> import { Config, postgresSchemaSql } from '@veltdev/node';
>
> console.log(postgresSchemaSql(new Config({ database: { type: 'postgresql', connection_string: 'postgresql://...' } })));
> ```
>
> * `schema` is the PostgreSQL schema that holds the tables. It is unrelated to the `user_schema` option, which maps user fields.
> * `sslmode` follows libpq names: `disable`, `allow`, `prefer`, `require`, `verify-ca`, `verify-full`. In Node, `prefer` (the default) connects **without TLS**, because node-postgres cannot fall back from TLS to plaintext. `require` encrypts without verifying the certificate (it verifies the CA when you set `sslrootcert`), and `verify-ca` and `verify-full` verify it. An unknown `sslmode` fails at `initialize()`. For any database that is not on the same host, set `sslmode: 'verify-full'` with `sslrootcert: '/path/to/ca.pem'`.
> * Each process opens its own connection pool, so a Node `cluster`, PM2, or several containers open one pool per worker.
> * The SDK does not migrate data between MongoDB and PostgreSQL.
> [tab] AWS (Attachments)
>
> Configure AWS S3 for storing file attachments. Alternatively, set the AWS environment variables listed above.
>
> ```ts theme={null}
> const sdk = VeltSDK.initialize({
> database: {
> host: 'localhost:27017',
> username: 'your-username',
> password: 'your-password',
> auth_database: 'admin',
> database_name: 'velt-db',
> },
> // AWS credentials can also be provided via environment variables
> apiKey: 'YOUR_VELT_API_KEY',
> authToken: 'YOUR_VELT_AUTH_TOKEN'
> });
> ```
> [tab] Complete Example
>
> Full configuration with database and credentials. For PostgreSQL, replace the `database` block with `{ type: 'postgresql', connection_string: 'postgresql://user:pass@host:5432/velt' }`.
>
> ```ts theme={null}
> import { VeltSDK } from '@veltdev/node';
>
> const sdk = VeltSDK.initialize({
> database: {
> host: 'localhost:27017',
> username: 'your-username',
> password: 'your-password',
> auth_database: 'admin',
> database_name: 'velt-db',
> },
> apiKey: 'YOUR_VELT_API_KEY',
> authToken: 'YOUR_VELT_AUTH_TOKEN'
> });
>
> // Graceful shutdown
> process.on('SIGTERM', async () => {
> await sdk.close();
> process.exit(0);
> });
> ```
> [tab] Resolver Auth
>
> Configure `resolverAuth` to verify the credential the Velt frontend forwards to endpoint-based resolvers. See [`verifyToken`](#verifytoken) for the full reference, error codes, and security guarantees.
>
> ```ts theme={null}
> const sdk = VeltSDK.initialize({
> database: {
> host: 'localhost:27017',
> username: 'your-username',
> password: 'your-password',
> auth_database: 'admin',
> database_name: 'velt-db',
> },
> apiKey: 'YOUR_VELT_API_KEY',
> authToken: 'YOUR_VELT_AUTH_TOKEN',
> resolverAuth: {
> jwt: { algorithms: ['RS256'], jwksUrl: 'https://your-idp.example.com/.well-known/jwks.json' },
> // or: verify: async (token, headers) => claims
> },
> });
> ```
## Self-Hosting Backend
The SDK loads each self-hosting service asynchronously on first access via `await sdk.selfHosting.getXxx()`. It caches the service after the first call.
`await sdk.selfHosting.database` returns the connected `DatabaseAdapter`: the raw adapter for the configured database (`MongoDBAdapter` or `PostgresAdapter`), with `find`, `findOne`, `insertOne`, `updateOne`, `updateMany`, `deleteOne`, and `deleteMany`. The first access connects and creates indexes; later accesses return the same adapter. Use it for a readiness check or to write data the resolvers do not write, such as seeding users. Pass collection names as configured in `collections`. On PostgreSQL the adapter accepts the query operators the SDK itself uses: equality, `$in`, `$nin`, `$eq`, `$ne`, `$exists`, and top-level `$and` and `$or`.
```ts theme={null}
const db = await sdk.selfHosting.database;
await db.insertOne('users', { userId: 'user-1', name: 'John Doe', email: 'john@example.com' });
```
### Comments
Access via `await sdk.selfHosting.getComments()`.
#### `getComments`
* Fetches comments for a document from your database.
* Params: [GetCommentsRequest (SH)](/docs/api-reference/sdk/models/data-models#getcommentsrequest-sh-node)
* Returns: [VeltSelfHostingResponse](/docs/api-reference/sdk/models/data-models#veltselfhostingresponse-node)
```ts theme={null}
const commentsService = await sdk.selfHosting.getComments();
const result = await commentsService.getComments({
organizationId: 'org-123',
documentIds: ['doc-1'],
});
```
**Response**
```ts theme={null}
{
success: true,
statusCode: 200,
data: { /* comment annotations keyed by annotationId */ }
}
```
#### `saveComments`
* Saves (creates or updates) comment annotations to your database.
* Params: [SaveCommentsRequest (SH)](/docs/api-reference/sdk/models/data-models#savecommentsrequest-sh-node)
* Returns: [VeltSelfHostingResponse](/docs/api-reference/sdk/models/data-models#veltselfhostingresponse-node)
```ts theme={null}
const commentsService = await sdk.selfHosting.getComments();
const result = await commentsService.saveComments({
metadata: { organizationId: 'org-123', documentId: 'doc-1' },
commentAnnotation: {
'annotation-1': {
annotationId: 'annotation-1',
comments: { '123456': { commentId: '123456', commentText: 'Hello' } },
metadata: {},
},
},
});
```
**Response**
```ts theme={null}
{ success: true, statusCode: 200, data: { saved: true } }
```
> **Resolver contract:** When `saveComments` runs as a save-resolver handler, the inbound `event` may be a [`ResolverActions`](/docs/api-reference/sdk/models/data-models#resolveractions) **or** a [`CommentResolverSaveEvent`](/docs/api-reference/sdk/models/data-models#commentresolversaveevent) member (or a raw string), and the request may include `targetComment?: PartialComment` — the comment the action occurred on (request context only, never persisted). See [`SaveCommentResolverRequest`](/docs/api-reference/sdk/models/data-models#savecommentresolverrequest).
#### `deleteComment`
* Deletes a single comment annotation from your database.
* Params: [DeleteCommentRequest (SH)](/docs/api-reference/sdk/models/data-models#deletecommentrequest-sh-node)
* Returns: [VeltSelfHostingResponse](/docs/api-reference/sdk/models/data-models#veltselfhostingresponse-node)
```ts theme={null}
const commentsService = await sdk.selfHosting.getComments();
const result = await commentsService.deleteComment({
commentAnnotationId: 'annotation-1',
metadata: { organizationId: 'org-123' },
});
```
**Response**
```ts theme={null}
{ success: true, statusCode: 200, data: { deleted: true } }
```
### Reactions
Access via `await sdk.selfHosting.getReactions()`.
#### `getReactions`
* Fetches reactions for a document from your database.
* Params: [GetReactionsRequest (SH)](/docs/api-reference/sdk/models/data-models#getreactionsrequest-sh-node)
* Returns: [VeltSelfHostingResponse](/docs/api-reference/sdk/models/data-models#veltselfhostingresponse-node)
```ts theme={null}
const reactionsService = await sdk.selfHosting.getReactions();
const result = await reactionsService.getReactions({
organizationId: 'org-123',
documentIds: ['doc-1'],
});
```
**Response**
```ts theme={null}
{ success: true, statusCode: 200, data: { /* reaction annotations */ } }
```
#### `saveReactions`
* Persists reactions to your database.
* Params: [SaveReactionsRequest (SH)](/docs/api-reference/sdk/models/data-models#savereactionsrequest-sh-node)
* Returns: [VeltSelfHostingResponse](/docs/api-reference/sdk/models/data-models#veltselfhostingresponse-node)
* The reacting user is set via `from` (renamed from `user` in **v1.0.5**, matching the frontend `PartialReactionAnnotation.from`).
```ts theme={null}
const reactionsService = await sdk.selfHosting.getReactions();
const result = await reactionsService.saveReactions({
metadata: { organizationId: 'org-123', documentId: 'doc-1' },
reactionAnnotation: {
'reaction-1': { annotationId: 'reaction-1', icon: 'thumbsup', from: { userId: 'u-1' }, metadata: {} },
},
});
```
**Response**
```ts theme={null}
{ success: true, statusCode: 200, data: { saved: true } }
```
#### `deleteReaction`
* Deletes a single reaction from your database.
* Params: [DeleteReactionRequest (SH)](/docs/api-reference/sdk/models/data-models#deletereactionrequest-sh-node)
* Returns: [VeltSelfHostingResponse](/docs/api-reference/sdk/models/data-models#veltselfhostingresponse-node)
```ts theme={null}
const reactionsService = await sdk.selfHosting.getReactions();
const result = await reactionsService.deleteReaction({
reactionAnnotationId: 'reaction-1',
metadata: { organizationId: 'org-123' },
});
```
**Response**
```ts theme={null}
{ success: true, statusCode: 200, data: { deleted: true } }
```
### Attachments
Access via `await sdk.selfHosting.getAttachments()`.
#### `getAttachment`
* Fetches an attachment record by organization and attachment ID.
* Params: positional — `organizationId` (string), `attachmentId` (number)
* Returns: [VeltSelfHostingResponse](/docs/api-reference/sdk/models/data-models#veltselfhostingresponse-node)
```ts theme={null}
const attachmentsService = await sdk.selfHosting.getAttachments();
const result = await attachmentsService.getAttachment('org-123', 12345);
```
**Response**
```ts theme={null}
{
success: true,
statusCode: 200,
data: {
attachmentId: 12345,
file: 'https://s3.amazonaws.com/...',
name: 'document.pdf',
mimeType: 'application/pdf',
metadata: { organizationId: 'org-123', documentId: 'doc-1' }
}
}
```
#### `saveAttachment`
* Persists attachment metadata, optionally uploading the file body to S3.
* Params: [SaveAttachmentRequest (SH)](/docs/api-reference/sdk/models/data-models#saveattachmentrequest-sh-node) plus optional positional `fileData` (Buffer), `fileName` (string), `mimeType` (string)
* Returns: [VeltSelfHostingResponse](/docs/api-reference/sdk/models/data-models#veltselfhostingresponse-node)
```ts theme={null}
const attachmentsService = await sdk.selfHosting.getAttachments();
const result = await attachmentsService.saveAttachment(
{
metadata: { organizationId: 'org-123', documentId: 'doc-1' },
attachment: {
attachmentId: 12345,
name: 'document.pdf',
mimeType: 'application/pdf',
},
},
fileBuffer, // optional Buffer for S3 upload
'document.pdf', // optional
'application/pdf' // optional
);
```
**Response**
```ts theme={null}
{ success: true, statusCode: 200, data: { url: 'https://s3.amazonaws.com/...' } }
```
#### `deleteAttachment`
* Deletes an attachment record (and S3 object, if applicable).
* Params: [DeleteAttachmentRequest (SH)](/docs/api-reference/sdk/models/data-models#deleteattachmentrequest-sh-node)
* Returns: [VeltSelfHostingResponse](/docs/api-reference/sdk/models/data-models#veltselfhostingresponse-node)
```ts theme={null}
const attachmentsService = await sdk.selfHosting.getAttachments();
const result = await attachmentsService.deleteAttachment({
attachmentId: 12345,
metadata: { organizationId: 'org-123' },
});
```
**Response**
```ts theme={null}
{ success: true, statusCode: 200, data: { deleted: true } }
```
### Users
Access via `await sdk.selfHosting.getUsers()`.
#### `getUsers`
* Fetches users from your database.
* Params: [GetUsersSelfHostingRequest (SH)](/docs/api-reference/sdk/models/data-models#getusersselfhostingrequest-sh-node)
* Returns: [VeltSelfHostingResponse](/docs/api-reference/sdk/models/data-models#veltselfhostingresponse-node)
```ts theme={null}
const usersService = await sdk.selfHosting.getUsers();
const result = await usersService.getUsers({
organizationId: 'org-123',
userIds: ['user-1'],
});
```
**Response**
```ts theme={null}
{
success: true,
statusCode: 200,
data: [{ userId: 'user-1', name: 'John Doe', email: 'john@example.com' }]
}
```
#### `resolveUserIdsByEmail`
* Resolves a list of email addresses to their user IDs. Backs the frontend's anonymous-user data provider.
* Params: [ResolveUserIdsByEmailRequest](/docs/api-reference/sdk/models/data-models#resolveuseridsbyemailrequest)
* Returns: [VeltSelfHostingResponse](/docs/api-reference/sdk/models/data-models#veltselfhostingresponse-node)
```ts theme={null}
const usersService = await sdk.selfHosting.getUsers();
const result = await usersService.resolveUserIdsByEmail({
organizationId: 'org-123',
emails: ['alice@example.com', 'bob@example.com'],
});
```
The SDK honors custom `user_schema` field mappings. It de-duplicates repeated addresses and drops empty entries. Like `getUsers`, the lookup does not filter by organization.
**Response**
`data` is a map of email to user ID. Addresses that do not match a user are absent from the map:
```ts theme={null}
{
success: true,
statusCode: 200,
data: { 'alice@example.com': 'user-1', 'bob@example.com': 'user-2' }
}
```
### Recorder
Access via `await sdk.selfHosting.getRecorder()`.
#### `getRecorderAnnotations`
* Fetches recorder annotations from your database.
* Params: [GetRecorderAnnotationsRequest (SH)](/docs/api-reference/sdk/models/data-models#getrecorderannotationsrequest-sh-node)
* Returns: [VeltSelfHostingResponse](/docs/api-reference/sdk/models/data-models#veltselfhostingresponse-node)
```ts theme={null}
const recorderService = await sdk.selfHosting.getRecorder();
const result = await recorderService.getRecorderAnnotations({
organizationId: 'org-123',
documentIds: ['doc-1'],
});
```
**Response**
```ts theme={null}
{ success: true, statusCode: 200, data: { /* recorder annotations */ } }
```
#### `saveRecorderAnnotation`
* Saves a single recorder annotation.
* Params: [SaveRecorderAnnotationRequest (SH)](/docs/api-reference/sdk/models/data-models#saverecorderannotationrequest-sh-node)
* Returns: [VeltSelfHostingResponse](/docs/api-reference/sdk/models/data-models#veltselfhostingresponse-node)
```ts theme={null}
const recorderService = await sdk.selfHosting.getRecorder();
const result = await recorderService.saveRecorderAnnotation({
metadata: { organizationId: 'org-123', documentId: 'doc-1' },
recorderAnnotation: { annotationId: 'rec-1', metadata: {} },
});
```
**Response**
```ts theme={null}
{ success: true, statusCode: 200, data: { saved: true } }
```
#### `deleteRecorderAnnotation`
* Deletes a recorder annotation.
* Params: [DeleteRecorderAnnotationRequest (SH)](/docs/api-reference/sdk/models/data-models#deleterecorderannotationrequest-sh-node)
* Returns: [VeltSelfHostingResponse](/docs/api-reference/sdk/models/data-models#veltselfhostingresponse-node)
```ts theme={null}
const recorderService = await sdk.selfHosting.getRecorder();
const result = await recorderService.deleteRecorderAnnotation({
recorderAnnotationId: 'rec-1',
metadata: { organizationId: 'org-123' },
});
```
**Response**
```ts theme={null}
{ success: true, statusCode: 200, data: { deleted: true } }
```
### Notifications
Access via `await sdk.selfHosting.getNotifications()`.
#### `getNotifications`
* Fetches notifications for a user from your database.
* Params: [GetNotificationsSelfHostingRequest (SH)](/docs/api-reference/sdk/models/data-models#getnotificationsselfhostingrequest-sh-node)
* Returns: [VeltSelfHostingResponse](/docs/api-reference/sdk/models/data-models#veltselfhostingresponse-node)
```ts theme={null}
const notificationsService = await sdk.selfHosting.getNotifications();
const result = await notificationsService.getNotifications({
organizationId: 'org-123',
userId: 'user-1',
});
```
**Response**
```ts theme={null}
{ success: true, statusCode: 200, data: [/* notifications */] }
```
#### `saveNotifications`
* Persists one or more notifications to your database.
* Params: [SaveNotificationsRequest (SH)](/docs/api-reference/sdk/models/data-models#savenotificationsrequest-sh-node)
* Returns: [VeltSelfHostingResponse](/docs/api-reference/sdk/models/data-models#veltselfhostingresponse-node)
```ts theme={null}
const notificationsService = await sdk.selfHosting.getNotifications();
await notificationsService.saveNotifications({
metadata: { organizationId: 'org-123', documentId: 'doc-1' },
notifications: [{ id: 'n-1', actionUser: { userId: 'user-1' }, displayBodyMessage: 'Hello' }],
});
```
**Response**
```ts theme={null}
{ success: true, statusCode: 200, data: { saved: true } }
```
#### `deleteNotification`
* Deletes a notification from your database.
* Params: [DeleteNotificationRequest (SH)](/docs/api-reference/sdk/models/data-models#deletenotificationrequest-sh-node)
* Returns: [VeltSelfHostingResponse](/docs/api-reference/sdk/models/data-models#veltselfhostingresponse-node)
```ts theme={null}
const notificationsService = await sdk.selfHosting.getNotifications();
await notificationsService.deleteNotification({
notificationId: 'n-1',
metadata: { organizationId: 'org-123', userId: 'user-1' },
});
```
**Response**
```ts theme={null}
{ success: true, statusCode: 200, data: { deleted: true } }
```
### Activities
Access via `await sdk.selfHosting.getActivities()`.
#### `getActivities`
* Fetches activity logs from your database.
* Params: [GetActivitiesSelfHostingRequest (SH)](/docs/api-reference/sdk/models/data-models#getactivitiesselfhostingrequest-sh-node)
* Returns: [VeltSelfHostingResponse](/docs/api-reference/sdk/models/data-models#veltselfhostingresponse-node)
```ts theme={null}
const activitiesService = await sdk.selfHosting.getActivities();
const result = await activitiesService.getActivities({
organizationId: 'org-123',
documentId: 'doc-1',
});
```
**Response**
```ts theme={null}
{ success: true, statusCode: 200, data: [/* activities */] }
```
#### `saveActivities`
* Persists activity log entries to your database.
* Params: [SaveActivitiesRequest (SH)](/docs/api-reference/sdk/models/data-models#saveactivitiesrequest-sh-node)
* Returns: [VeltSelfHostingResponse](/docs/api-reference/sdk/models/data-models#veltselfhostingresponse-node)
```ts theme={null}
const activitiesService = await sdk.selfHosting.getActivities();
await activitiesService.saveActivities({
metadata: { organizationId: 'org-123', documentId: 'doc-1' },
activities: [{ id: 'activity-1', featureType: 'comment', actionType: 'comment.add' }],
});
```
**Response**
```ts theme={null}
{ success: true, statusCode: 200, data: { saved: true } }
```
### verifyToken
`sdk.selfHosting.verifyToken` verifies the auth credential the Velt frontend forwards to endpoint-based resolvers. It is **database-free** (it does not open or query MongoDB), **fail-closed** (every error path returns `{ verified: false }`, never throws), and **authentication only** (claims are returned verbatim; it makes no authorization decision).
> **Optional dependency:** `npm install jose@^5` (optional `peerDependency`, pinned `^5` for Node 18 — jose v6 needs the WebCrypto global absent on Node 18). If `jose` is missing and the built-in JWT path is used, `verifyToken` returns `{ verified: false, errorCode: 'DEPENDENCY_MISSING' }`. The custom `verify` callback path needs no dependency.
#### Configuration
Configure `resolverAuth` on `VeltSDK.initialize`. Provide the built-in `jwt` path, a custom `verify` callback, or both. When both are set, the custom callback takes priority.
> [tab] JWT / JWKS
>
> ```ts theme={null}
> const sdk = VeltSDK.initialize({
> database: {
> host: 'localhost:27017',
> username: 'your-username',
> password: 'your-password',
> auth_database: 'admin',
> database_name: 'velt-db',
> },
> apiKey: 'YOUR_VELT_API_KEY',
> authToken: 'YOUR_VELT_AUTH_TOKEN',
> resolverAuth: {
> jwt: {
> algorithms: ['RS256'], // REQUIRED — algorithm allowlist (pinning)
> jwksUrl: 'https://your-idp.example.com/.well-known/jwks.json',
> // publicKey: '-----BEGIN PUBLIC KEY-----\n...', // OR a static PEM
> // secret: 'hs256-shared-secret', // OR an HMAC secret for HS*
> issuer: 'https://your-idp.example.com/',
> audience: 'your-api-audience',
> leeway: 5, // clock tolerance in seconds
> require: ['exp'], // required claims
> },
> header: 'Authorization', // default
> scheme: 'Bearer', // default
> },
> });
> ```
> [tab] Custom verify callback
>
> ```ts theme={null}
> const sdk = VeltSDK.initialize({
> database: {
> host: 'localhost:27017',
> username: 'your-username',
> password: 'your-password',
> auth_database: 'admin',
> database_name: 'velt-db',
> },
> apiKey: 'YOUR_VELT_API_KEY',
> authToken: 'YOUR_VELT_AUTH_TOKEN',
> resolverAuth: {
> verify: async (token, headers) => {
> // Validate the token yourself; return the claims, or a falsy value to fail closed.
> const claims = await myValidate(token);
> return claims; // { sub: 'user-1', ... }
> },
> header: 'Authorization',
> scheme: 'Bearer',
> },
> });
> ```
#### Usage
Call `verifyToken` from your endpoint-based resolver route, then branch on `result.verified`.
```ts theme={null}
const result = await sdk.selfHosting.verifyToken({ headers: request.headers });
if (!result.verified) {
// result.error is a generic, code-based message; result.errorCode is machine-readable
return response.status(401).json({ error: result.error, code: result.errorCode });
}
const userId = result.claims?.sub;
```
Per-call `options` override the configured `resolverAuth` (the `jwt` block is deep-merged):
```ts theme={null}
// Pass a raw token directly instead of headers
await sdk.selfHosting.verifyToken({ token: rawToken });
// Override a single jwt option for this call (deep-merged with configured jwt)
await sdk.selfHosting.verifyToken({ headers: request.headers, jwt: { leeway: 30 } });
```
**Signature**
```ts theme={null}
verifyToken(
options?: {
headers?: Record | Headers | Iterable<[string, string]>;
token?: string;
} & Partial
) => Promise
```
* Params: inline options object with `headers`, `token`, and per-call [`ResolverAuthConfig`](/docs/api-reference/sdk/models/data-models#resolverauthconfig-node) overrides. This parameter shape is not exported as a named SDK type.
* Returns: [`VerifyTokenResult`](/docs/api-reference/sdk/models/data-models#verifytokenresult-node)
The verification logic is implemented by the `ResolverAuthService` class (also exported from `@veltdev/node`) for advanced callers who need to construct it directly; `sdk.selfHosting.verifyToken` is the standard entry point.
#### Error codes
On failure, `result.errorCode` is one of the [`ResolverAuthErrorCode`](/docs/api-reference/sdk/models/data-models#resolverautherrorcode-node) values (also exported as the readonly `string[]` const `RESOLVER_AUTH_ERROR_CODES`).
| Code | When |
| - | - |
| `NOT_CONFIGURED` | Neither `jwt` nor a `verify` callback is configured. |
| `MISSING_TOKEN` | No token found in headers, or wrong scheme. |
| `EXPIRED` | JWT `exp` claim has passed (beyond `leeway`). |
| `INVALID_SIGNATURE` | Signature verification failed, or malformed token. |
| `CLAIM_MISMATCH` | Configured `issuer`/`audience` wrong or absent; or a required claim is missing. |
| `ALGORITHM_NOT_ALLOWED` | `alg=none`; algorithm outside the allowlist; mixed symmetric+asymmetric allowlist; missing allowlist. |
| `KEY_RESOLUTION_FAILED` | No usable key; JWKS URL is not HTTPS; JWKS fetch failed or returned non-2xx; redirect downgrade detected. |
| `DEPENDENCY_MISSING` | Built-in JWT path used but `jose` is not installed. |
| `VERIFICATION_FAILED` | Custom callback threw or returned falsy; unexpected internal error (fail-closed catch-all). |
#### Security guarantees
* `alg=none` is always rejected, even if present in the allowlist.
* Mixed symmetric+asymmetric allowlists are refused (prevents HS/RS confusion).
* A PEM placed in `jwt.secret` is refused.
* JWKS is fetched only over HTTPS — `http` is rejected pre-fetch, and a redirect downgrade is rejected.
* JWKS responses are cached per URL with a 5-minute TTL (not per `kid`).
* The token-header `alg` is checked against the allowlist before any JWKS fetch.
* The `error` field is generic and code-based — it never contains the token or secret.
## REST API Backend
The `sdk.api.*` namespace gives you parity with [Velt's REST APIs](/docs/api-reference/rest-apis/v2/organizations/get-organizations-v2) across 19 services, including token generation with [`sdk.api.accessControl.generateToken`](#generatetoken). Each method takes a fully-typed TypeScript request object and returns the raw Velt API response. You only need `apiKey` and `authToken`; initialize without a `database` block.
Every `sdk.api.*` method requires an `organizationId` in its request payload. Velt enforces data isolation per-organization server-side.
### Response Envelope
Every `sdk.api.*` method resolves to a `VeltApiResponse`. The SDK does not throw on an API error; check `error` first.
```ts theme={null}
interface VeltApiResponse {
result?: TResult; // present on success
error?: { message: string; status: string; details?: unknown }; // present on failure
}
interface ApiResult {
status: string; message: string; data?: TData; nextPageToken?: string;
}
const res = await sdk.api.organizations.getOrganizations({ organizationIds: ['org-123'] });
if (res.error) throw new Error(res.error.message);
const orgs = res.result?.data;
```
`TResult` depends on the service: `ApiResult` for most services, the raw value (`unknown`) for `sdk.api.memory`, a per-method `Approval*Result` object for `sdk.api.approval` (`listDefinitions` and `listExecutions` page by `nextCursor`), and `AskAiResult` (`{ success, text?, error? }`) for `sdk.api.rewriter.askAi`. `data` is untyped; narrow it to the shape shown in each method's response example. REST user fields (`users[]`, `from`, `assignedTo`, `actionUser`, `notifyUsers`, `addPermissions.user`) take `RestUser`: `accessRole` is `'editor' | 'viewer'`, each `contacts[]` entry needs `userId`, and `role` needs `id`.
### Field Allowlist
The REST add/update methods on `activities`, `commentAnnotations`, and `notifications` accept an optional second argument, `FieldFilterOptions`. Pass `{ filterUnknownFields: true }` to narrow the request to exactly the fields the corresponding Velt backend endpoint accepts. See the note at the top of each service section for the behavior summary; the per-endpoint field lists are below.
```ts theme={null}
interface FieldFilterOptions {
/** When true, narrow the request to only the fields the Velt backend endpoint
* accepts, silently dropping unknown keys. Fail-open. Defaults to false. */
filterUnknownFields?: boolean;
}
```
#### Exported filter utilities
The field-allowlist module is exported from `@veltdev/node` so advanced callers can reuse the same logic.
```ts theme={null}
// Functions
pickKnownFields(data: T, keys: readonly string[]): Partial;
filterRequest(request: T, spec: FilterSpec): T;
// Types
interface FilterSpec {
keys: readonly string[]; // allowed top-level keys at this level (everything else dropped)
arrays?: Record; // known array-of-object fields, filtered per item
objects?: Record; // known single-object fields, filtered recursively
}
```
* `pickKnownFields(data, keys)` — keeps only own-enumerable keys present in `keys`; values kept by reference (no recursion); non-object/array/null inputs returned unchanged.
* `filterRequest(request, spec)` — applies a `FilterSpec` recursively; never mutates input; fail-open (returns the original request on any error).
* Eight per-method specs are exported: `ADD_ACTIVITIES_SPEC`, `UPDATE_ACTIVITIES_SPEC`, `ADD_COMMENT_ANNOTATIONS_SPEC`, `UPDATE_COMMENT_ANNOTATIONS_SPEC`, `ADD_COMMENTS_SPEC`, `UPDATE_COMMENTS_SPEC`, `ADD_NOTIFICATIONS_SPEC`, `UPDATE_NOTIFICATIONS_SPEC`.
#### Allowlisted fields per endpoint
When `filterUnknownFields: true`, only these keys survive (unknown keys dropped):
| Spec (endpoint) | Top-level keys | Nested item filtering |
| - | - | - |
| `ADD_ACTIVITIES_SPEC` (`/v2/activities/add`) | `organizationId`, `documentId`, `activities` | `activities[]`: `id`, `featureType`, `actionType`, `actionUser`, `targetEntityId`, `isActivityResolverUsed`, `targetSubEntityId`, `changes`, `entityData`, `entityTargetData`, `displayMessageTemplate`, `displayMessageTemplateData`, `actionIcon` |
| `UPDATE_ACTIVITIES_SPEC` (`/v2/activities/update`) | `organizationId`, `activities` | `activities[]`: `id`, `changes`, `entityData`, `entityTargetData`, `displayMessageTemplate`, `displayMessageTemplateData`, `actionIcon` |
| `ADD_COMMENT_ANNOTATIONS_SPEC` (`/v2/commentannotations/add`) | `organizationId`, `documentId`, `commentAnnotations`, `verifyUserPermissions`, `createDocument`, `createOrganization` | `commentAnnotations[]`: `location`, `annotationId`, `targetElement`, `commentData`, `comments`, `status`, `commentType`, `type`, `assignedTo`, `priority`, `context`, `visibility`, `lastUpdated`, `createdAt`, `pageInfo`, `isPageAnnotation`, `positionX`, `positionY`, `screenWidth`, `screenHeight`, `screenScrollHeight`, `screenScrollTop` — its `comments[]`/`commentData[]` use the annotation comment-data set (below) |
| `UPDATE_COMMENT_ANNOTATIONS_SPEC` (`/v2/commentannotations/update`) | `organizationId`, `documentId`, `annotationIds`, `locationIds`, `userIds`, `updateUsers`, `updatedData` | `updatedData`: `location`, `targetElement`, `from`, `status`, `assignedTo`, `priority`, `context`, `visibility`, `createdAt`, `lastUpdated` |
| `ADD_COMMENTS_SPEC` (`/v2/commentannotations/comments/add`) | `organizationId`, `documentId`, `annotationId`, `commentData`, `comments`, `verifyUserPermissions`, `createDocument`, `createOrganization` | `commentData[]`/`comments[]`: comment-data set (below) |
| `UPDATE_COMMENTS_SPEC` (`/v2/commentannotations/comments/update`) | `organizationId`, `documentId`, `annotationId`, `commentIds`, `userIds`, `updatedData` | `updatedData`: `commentText`, `commentHtml`, `from`, `createdAt`, `taggedUserContacts`, `isCommentResolverUsed`, `isCommentTextAvailable`, `lastUpdated`, `context`, `attachments` |
| `ADD_NOTIFICATIONS_SPEC` (`/v2/notifications/add`) | `organizationId`, `documentId`, `notificationId`, `actionUser`, `isNotificationResolverUsed`, `displayHeadlineMessageTemplate`, `displayHeadlineMessageTemplateData`, `displayBodyMessage`, `displayBodyMessageTemplate`, `displayBodyMessageTemplateData`, `notifyUsers`, `notificationSourceData`, `location`, `metadata`, `notifyAll`, `createDocument`, `createOrganization`, `verifyUserPermissions`, `context`, `isCrossOrganizationEnabled` | the notification is the request itself — nested open-typed dicts pass through whole |
| `UPDATE_NOTIFICATIONS_SPEC` (`/v2/notifications/update`) | `organizationId`, `documentId`, `locationId`, `userId`, `verifyUserPermissions`, `notifications` | `notifications[]`: `id`, `actionUser`, `displayHeadlineMessageTemplate`, `displayHeadlineMessageTemplateData`, `displayBodyMessage`, `displayBodyMessageTemplate`, `displayBodyMessageTemplateData`, `notifyUsers`, `notificationSourceData`, `location`, `metadata`, `context`, `readByUserIds`, `persistReadForUsers` |
The comment-annotation specs above reference two comment-data key sets:
* Annotation-level `commentData`/`comments` (`ANNOTATION_COMMENT_DATA_KEYS`): `commentText`, `commentHtml`, `commentId`, `from`, `lastUpdated`, `createdAt`, `taggedUserContacts`, `isCommentResolverUsed`, `isCommentTextAvailable`, `triggerNotification`, `triggerActivities`, `agent` — carries the trigger flags but not `context`/`attachments`.
* Comments-endpoint `commentData`/`comments` (`COMMENT_DATA_KEYS`): `commentText`, `commentHtml`, `commentId`, `from`, `lastUpdated`, `createdAt`, `taggedUserContacts`, `isCommentResolverUsed`, `isCommentTextAvailable`, `context`, `attachments`, `agent` — carries `context`/`attachments` but not the trigger flags.
> [!NOTE]
>
> `UPDATE_NOTIFICATIONS_SPEC` intentionally excludes `isRead`/`isArchived` — they are absent from the backend `UpdateNotificationsSchemaV2` and unsupported by `/v2/notifications/update`, so they are dropped when filtering is on.
### Organizations
**Namespace:** `sdk.api.organizations`
#### `addOrganizations`
* Creates one or more organizations.
* Params: [AddOrganizationsRequest](/docs/api-reference/sdk/models/data-models#addorganizationsrequest-node)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse-node)
```ts theme={null}
await sdk.api.organizations.addOrganizations({
organizations: [{ organizationId: 'org-123', organizationName: 'My Organization' }],
});
```
**Response**
```ts theme={null}
{
result: {
status: 'success',
message: 'Organization(s) added successfully.',
data: {
'org-123': { success: true, id: '02cf91e5...', message: 'Added Successfully' }
}
}
}
```
#### `getOrganizations`
* Retrieves organizations. Optionally filter by IDs with pagination.
* Params: [GetOrganizationsRequest](/docs/api-reference/sdk/models/data-models#getorganizationsrequest-node)
* Returns: [GetOrganizationsResponse](/docs/api-reference/sdk/models/data-models#getorganizationsresponse-node)
```ts theme={null}
await sdk.api.organizations.getOrganizations({
organizationIds: ['org-123'],
pageSize: 10,
pageToken: 'next-page-token',
});
```
**Response**
```ts theme={null}
{
result: {
status: 'success',
message: 'Organization(s) retrieved successfully.',
data: [
{ id: 'org-123', organizationName: 'Your Organization Name', disabled: false }
],
nextPageToken: 'pageToken'
}
}
```
#### `updateOrganizations`
* Updates organization properties.
* Params: [UpdateOrganizationsRequest](/docs/api-reference/sdk/models/data-models#updateorganizationsrequest-node)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse-node)
```ts theme={null}
await sdk.api.organizations.updateOrganizations({
organizations: [{ organizationId: 'org-123', organizationName: 'Updated Name' }],
});
```
**Response**
```ts theme={null}
{ result: { status: 'success', message: 'Organization(s) updated successfully.', data: {} } }
```
#### `deleteOrganizations`
* Deletes one or more organizations.
* Params: [DeleteOrganizationsRequest](/docs/api-reference/sdk/models/data-models#deleteorganizationsrequest-node)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse-node)
```ts theme={null}
await sdk.api.organizations.deleteOrganizations({ organizationIds: ['org-123'] });
```
**Response**
```ts theme={null}
{ result: { status: 'success', message: 'Organization(s) deleted successfully.', data: {} } }
```
#### `updateOrganizationDisableState`
* Enables or disables one or more organizations.
* Params: [UpdateOrganizationDisableStateRequest](/docs/api-reference/sdk/models/data-models#updateorganizationdisablestaterequest-node)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse-node)
```ts theme={null}
await sdk.api.organizations.updateOrganizationDisableState({
organizationIds: ['org-123'],
disabled: true,
});
```
**Response**
```ts theme={null}
{ result: { status: 'success', message: 'Organization(s) disable state updated.', data: {} } }
```
### Folders
**Namespace:** `sdk.api.folders`
#### `addFolder`
* Creates one or more folders inside an organization.
* Params: [AddFolderRequest](/docs/api-reference/sdk/models/data-models#addfolderrequest-node)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse-node)
```ts theme={null}
await sdk.api.folders.addFolder({
organizationId: 'org-123',
folders: [{ folderId: 'folder-1', folderName: 'My Folder' }],
createOrganization: true,
});
```
**Response**
```ts theme={null}
{ result: { status: 'success', message: 'Folder(s) added successfully.', data: {} } }
```
#### `getFolders`
* Retrieves folders. Optionally filter by folder ID with depth control.
* Params: [GetFoldersRequest](/docs/api-reference/sdk/models/data-models#getfoldersrequest-node)
* Returns: [GetFoldersResponse](/docs/api-reference/sdk/models/data-models#getfoldersresponse-node)
```ts theme={null}
await sdk.api.folders.getFolders({
organizationId: 'org-123',
folderId: 'folder-1',
maxDepth: 3,
});
```
**Response**
```ts theme={null}
{
result: {
status: 'success',
message: 'Folders retrieved successfully.',
data: [
{
folderId: 'folder-1',
folderName: 'Folder 1',
organizationId: 'org-123',
parentFolderId: 'root',
createdAt: 1738695615706,
lastUpdated: 1738696287859
}
]
}
}
```
#### `updateFolder`
* Updates folder properties.
* Params: [UpdateFolderRequest](/docs/api-reference/sdk/models/data-models#updatefolderrequest-node)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse-node)
```ts theme={null}
await sdk.api.folders.updateFolder({
organizationId: 'org-123',
folders: [{ folderId: 'folder-1', folderName: 'Renamed' }],
});
```
**Response**
```ts theme={null}
{ result: { status: 'success', message: 'Folder(s) updated successfully.', data: {} } }
```
#### `deleteFolder`
* Deletes a folder.
* Params: [DeleteFolderRequest](/docs/api-reference/sdk/models/data-models#deletefolderrequest-node)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse-node)
```ts theme={null}
await sdk.api.folders.deleteFolder({ organizationId: 'org-123', folderId: 'folder-1' });
```
**Response**
```ts theme={null}
{ result: { status: 'success', message: 'Folder deleted successfully.', data: {} } }
```
#### `updateFolderAccess`
* Updates access type for one or more folders.
* Params: [UpdateFolderAccessRequest](/docs/api-reference/sdk/models/data-models#updatefolderaccessrequest-node)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse-node)
```ts theme={null}
await sdk.api.folders.updateFolderAccess({
organizationId: 'org-123',
folderIds: ['folder-1'],
accessType: 'restricted',
});
```
**Response**
```ts theme={null}
{ result: { status: 'success', message: 'Folder access updated successfully.', data: {} } }
```
### Documents
**Namespace:** `sdk.api.documents`
#### `addDocuments`
* Creates one or more documents.
* Params: [AddDocumentsRequest](/docs/api-reference/sdk/models/data-models#adddocumentsrequest-node)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse-node)
```ts theme={null}
await sdk.api.documents.addDocuments({
organizationId: 'org-123',
documents: [
{ documentId: 'doc-1', documentName: 'My Document' },
{ documentId: 'doc-2', documentName: 'Another Document' },
],
createOrganization: true,
folderId: 'folder-1',
createFolder: true,
});
```
**Response**
```ts theme={null}
{
result: {
status: 'success',
message: 'Document(s) added successfully.',
data: {
'doc-1': { success: true, message: 'Added Successfully' },
'doc-2': { success: true, message: 'Added Successfully' }
}
}
}
```
#### `getDocuments`
* Retrieves documents with optional filters and pagination.
* Params: [GetDocumentsRequest](/docs/api-reference/sdk/models/data-models#getdocumentsrequest-node)
* Returns: [GetDocumentsResponse](/docs/api-reference/sdk/models/data-models#getdocumentsresponse-node)
```ts theme={null}
await sdk.api.documents.getDocuments({
organizationId: 'org-123',
documentIds: ['doc-1'],
folderId: 'folder-1',
pageSize: 10,
});
```
**Response**
```ts theme={null}
{
result: {
status: 'success',
message: 'Document(s) retrieved successfully.',
data: [
{ documentName: 'yourDocumentName', disabled: false, accessType: 'public', id: 'yourDocumentId' }
],
pageToken: 'nextPageToken'
}
}
```
#### `updateDocuments`
* Updates document properties.
* Params: [UpdateDocumentsRequest](/docs/api-reference/sdk/models/data-models#updatedocumentsrequest-node)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse-node)
```ts theme={null}
await sdk.api.documents.updateDocuments({
organizationId: 'org-123',
documents: [{ documentId: 'doc-1', documentName: 'Renamed' }],
});
```
**Response**
```ts theme={null}
{ result: { status: 'success', message: 'Document(s) updated successfully.', data: {} } }
```
#### `deleteDocuments`
* Deletes one or more documents.
* Params: [DeleteDocumentsRequest](/docs/api-reference/sdk/models/data-models#deletedocumentsrequest-node)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse-node)
```ts theme={null}
await sdk.api.documents.deleteDocuments({
organizationId: 'org-123',
documentIds: ['doc-1', 'doc-2'],
});
```
**Response**
```ts theme={null}
{ result: { status: 'success', message: 'Document(s) deleted successfully.', data: {} } }
```
#### `moveDocuments`
* Moves documents into a folder.
* Params: [MoveDocumentsRequest](/docs/api-reference/sdk/models/data-models#movedocumentsrequest-node)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse-node)
```ts theme={null}
await sdk.api.documents.moveDocuments({
organizationId: 'org-123',
documentIds: ['doc-1', 'doc-2'],
folderId: 'target-folder-id',
});
```
**Response**
```ts theme={null}
{ result: { status: 'success', message: 'Document(s) moved successfully.', data: {} } }
```
#### `updateDocumentAccess`
* Updates access type for one or more documents.
* Params: [UpdateDocumentAccessRequest](/docs/api-reference/sdk/models/data-models#updatedocumentaccessrequest-node)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse-node)
```ts theme={null}
await sdk.api.documents.updateDocumentAccess({
organizationId: 'org-123',
documentIds: ['doc-1', 'doc-2'],
accessType: 'organizationPrivate',
});
```
**Response**
```ts theme={null}
{ result: { status: 'success', message: 'Document access updated successfully.', data: {} } }
```
#### `updateDocumentDisableState`
* Enables or disables one or more documents.
* Params: [UpdateDocumentDisableStateRequest](/docs/api-reference/sdk/models/data-models#updatedocumentdisablestaterequest-node)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse-node)
```ts theme={null}
await sdk.api.documents.updateDocumentDisableState({
organizationId: 'org-123',
documentIds: ['doc-1'],
disabled: true,
});
```
**Response**
```ts theme={null}
{ result: { status: 'success', message: 'Document(s) disable state updated.', data: {} } }
```
#### `migrateDocuments`
* Starts a document migration job.
* Params: [MigrateDocumentsRequest](/docs/api-reference/sdk/models/data-models#migratedocumentsrequest-node)
* Returns: [MigrateDocumentsResponse](/docs/api-reference/sdk/models/data-models#migratedocumentsresponse-node)
> Note: `migrateDocuments` is asynchronous and returns a `migrationId`. Poll completion with `migrateDocumentsStatus`.
```ts theme={null}
await sdk.api.documents.migrateDocuments({
organizationId: 'org-123',
documentId: 'old-doc-id',
newDocumentId: 'new-doc-id',
});
```
**Response**
```ts theme={null}
{
result: {
status: 'success',
message: 'Document migration started successfully.',
data: { migrationId: 'yourMigrationId' }
}
}
```
#### `migrateDocumentsStatus`
* Polls the status of a migration job.
* Params: [MigrateDocumentsStatusRequest](/docs/api-reference/sdk/models/data-models#migratedocumentsstatusrequest-node)
* Returns: [MigrateDocumentsStatusResponse](/docs/api-reference/sdk/models/data-models#migratedocumentsstatusresponse-node)
```ts theme={null}
await sdk.api.documents.migrateDocumentsStatus({
organizationId: 'org-123',
migrationId: 'migration-1',
});
```
**Response**
```ts theme={null}
{
result: {
status: 'success',
message: 'Migration status retrieved successfully.',
data: { migrationId: 'yourMigrationId', status: 'completed' }
}
}
```
#### `getDocumentsCount`
* Return a document count for an organization (optionally scoped to a folder, or narrowed by metadata filters).
* Params: [GetDocumentsCountRequest](/docs/api-reference/sdk/models/data-models#getdocumentscountrequest-node)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse-node)
```ts theme={null}
await sdk.api.documents.getDocumentsCount({ organizationId: 'org-123' });
await sdk.api.documents.getDocumentsCount({ organizationId: 'org-123', folderId: 'folder-1', excludeFolderDocs: true });
// Narrow the count with metadata filters (same shape as getDocuments; max 10).
await sdk.api.documents.getDocumentsCount({
organizationId: 'org-123',
filters: [
{ key: 'projectType', operator: '==', value: 'design' },
{ key: 'category', operator: 'in', value: ['a', 'b'] },
],
});
```
`filters` cannot be combined with `excludeFolderDocs` — the API rejects the combination.
**Response**
```ts theme={null}
{ result: { status: 'success', message: 'Documents count retrieved successfully.', data: { count: 42 } } }
```
When `filters` is supplied, the response data also carries `filtersApplied`. A `false` value means the filtered aggregate could not be computed and `count` is an unfiltered fallback, so check it if you need the count to be exact:
```ts theme={null}
{ result: { status: 'success', message: 'Documents count retrieved successfully.', data: { count: 7, filtersApplied: true } } }
```
### Users
**Namespace:** `sdk.api.users`
#### `addUsers`
* Adds one or more users to an organization, document, or folder.
* Params: [AddUsersRequest](/docs/api-reference/sdk/models/data-models#addusersrequest-node)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse-node)
```ts theme={null}
await sdk.api.users.addUsers({
organizationId: 'org-123',
users: [{ userId: 'user-1', name: 'John Doe', email: 'john@example.com', accessRole: 'editor' }],
createOrganization: true,
});
```
**Response**
```ts theme={null}
{ result: { status: 'success', message: 'User(s) added successfully.', data: {} } }
```
#### `getUsers`
* Retrieves users with optional filters and pagination.
* Params: [GetUsersRequest](/docs/api-reference/sdk/models/data-models#getusersrequest-node)
* Returns: [GetUsersResponse](/docs/api-reference/sdk/models/data-models#getusersresponse-node)
```ts theme={null}
await sdk.api.users.getUsers({
organizationId: 'org-123',
userIds: ['user-1'],
documentId: 'doc-1',
pageSize: 100,
allDocuments: true,
groupByDocumentId: true,
});
```
**Response**
```ts theme={null}
{
result: {
status: 'success',
message: 'User(s) retrieved successfully.',
data: [
{ email: 'userEmail@domain.com', name: 'userName', userId: 'yourUserId' }
],
nextPageToken: 'pageToken'
}
}
```
#### `updateUsers`
* Updates user properties.
* Params: [UpdateUsersRequest](/docs/api-reference/sdk/models/data-models#updateusersrequest-node)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse-node)
```ts theme={null}
await sdk.api.users.updateUsers({
organizationId: 'org-123',
users: [{ userId: 'user-1', name: 'Jane Doe', accessRole: 'viewer' }],
});
```
**Response**
```ts theme={null}
{ result: { status: 'success', message: 'User(s) updated successfully.', data: {} } }
```
#### `deleteUsers`
* Removes users from an organization.
* Params: [DeleteUsersRequest](/docs/api-reference/sdk/models/data-models#deleteusersrequest-node)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse-node)
```ts theme={null}
await sdk.api.users.deleteUsers({ organizationId: 'org-123', userIds: ['user-1'] });
```
**Response**
```ts theme={null}
{ result: { status: 'success', message: 'User(s) deleted successfully.', data: {} } }
```
#### `getUsersCount`
* Count users in an org (optionally scoped to a document or all documents).
* Params: [GetUsersCountRequest](/docs/api-reference/sdk/models/data-models#getuserscountrequest-node)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse-node)
```ts theme={null}
await sdk.api.users.getUsersCount({ organizationId: 'org-123', allDocuments: true });
```
**Response**
```ts theme={null}
{ result: { status: 'success', message: 'Users count retrieved successfully.', data: { count: 12 } } }
```
#### `getDocUsers`
* Get document-level users (optionally including involved documents).
* Params: [GetDocUsersRequest](/docs/api-reference/sdk/models/data-models#getdocusersrequest-node)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse-node)
```ts theme={null}
await sdk.api.users.getDocUsers({ organizationId: 'org-123', userIds: ['user-1'] });
```
**Response**
```ts theme={null}
{
result: {
status: 'success',
message: 'Document users retrieved successfully.',
data: [{ userId: 'user-1', name: 'John Doe', email: 'john@example.com' }]
}
}
```
#### `addUserInvite`
* Create an org/doc/folder user invite.
* Params: [AddUserInviteRequest](/docs/api-reference/sdk/models/data-models#adduserinviterequest-node)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse-node)
```ts theme={null}
await sdk.api.users.addUserInvite({ email: 'invitee@example.com', organizationId: 'org-123', type: 'doc_user', documentId: 'doc-1' });
```
**Response**
```ts theme={null}
{ result: { status: 'success', message: 'User invite created successfully.', data: {} } }
```
#### `respondToUserInvite`
* Accept/reject/withdraw an invite.
* Params: [RespondToUserInviteRequest](/docs/api-reference/sdk/models/data-models#respondtouserinviterequest-node)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse-node)
```ts theme={null}
await sdk.api.users.respondToUserInvite({ email: 'invitee@example.com', organizationId: 'org-123', type: 'doc_user', documentId: 'doc-1', status: 'ACCEPTED', user: { userId: 'user-9', name: 'New User', email: 'invitee@example.com' }, authToken: 'user-auth-token' });
```
**Response**
```ts theme={null}
{ result: { status: 'success', message: 'Invite response recorded successfully.', data: {} } }
```
#### `getUserInvites`
* List invites for an org (paged).
* Params: [GetUserInvitesRequest](/docs/api-reference/sdk/models/data-models#getuserinvitesrequest-node)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse-node)
```ts theme={null}
await sdk.api.users.getUserInvites({ organizationId: 'org-123' });
```
**Response**
```ts theme={null}
{
result: {
status: 'success',
message: 'User invites retrieved successfully.',
data: [{ email: 'invitee@example.com', type: 'doc_user', status: 'PENDING' }],
nextPageToken: 'pageToken'
}
}
```
#### `getUserInvitations`
* List invitations for a specific email (paged, filterable).
* Params: [GetUserInvitationsRequest](/docs/api-reference/sdk/models/data-models#getuserinvitationsrequest-node)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse-node)
```ts theme={null}
await sdk.api.users.getUserInvitations({ organizationId: 'org-123', email: 'invitee@example.com' });
```
**Response**
```ts theme={null}
{
result: {
status: 'success',
message: 'User invitations retrieved successfully.',
data: [{ organizationId: 'org-123', type: 'doc_user', status: 'PENDING' }],
nextPageToken: 'pageToken'
}
}
```
#### `getInvitedPendingUsersCount`
* Count pending invited users by invite type.
* Params: [GetInvitedPendingUsersCountRequest](/docs/api-reference/sdk/models/data-models#getinvitedpendinguserscountrequest-node)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse-node)
```ts theme={null}
await sdk.api.users.getInvitedPendingUsersCount({ organizationId: 'org-123', type: 'org_user' });
```
**Response**
```ts theme={null}
{ result: { status: 'success', message: 'Pending invited users count retrieved successfully.', data: { count: 3 } } }
```
### User Groups
**Namespace:** `sdk.api.userGroups`
#### `addUserGroups`
* Creates one or more user groups.
* Params: [AddUserGroupsRequest](/docs/api-reference/sdk/models/data-models#addusergroupsrequest-node)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse-node)
```ts theme={null}
await sdk.api.userGroups.addUserGroups({
organizationId: 'org-123',
organizationUserGroups: [{ groupId: 'engineering', groupName: 'Engineering' }],
createOrganization: true,
});
```
**Response**
```ts theme={null}
{ result: { status: 'success', message: 'User group(s) added successfully.', data: {} } }
```
#### `addUsersToGroup`
* Adds users to an existing group.
* Params: [AddUsersToGroupRequest](/docs/api-reference/sdk/models/data-models#adduserstogrouprequest-node)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse-node)
```ts theme={null}
await sdk.api.userGroups.addUsersToGroup({
organizationId: 'org-123',
organizationUserGroupId: 'engineering',
userIds: ['user-1', 'user-2'],
});
```
**Response**
```ts theme={null}
{ result: { status: 'success', message: 'Users added to group successfully.', data: {} } }
```
#### `deleteUsersFromGroup`
* Removes users from a group, or removes all users.
* Params: [DeleteUsersFromGroupRequest](/docs/api-reference/sdk/models/data-models#deleteusersfromgrouprequest-node)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse-node)
```ts theme={null}
await sdk.api.userGroups.deleteUsersFromGroup({
organizationId: 'org-123',
organizationUserGroupId: 'engineering',
userIds: ['user-1'],
});
```
**Response**
```ts theme={null}
{ result: { status: 'success', message: 'Users removed from group successfully.', data: {} } }
```
### Notifications
**Namespace:** `sdk.api.notifications`
> [!NOTE]
>
> **Filtering unknown fields**: The add/update methods below accept an optional `options?: FieldFilterOptions` second argument. When `{ filterUnknownFields: true }` is passed, unknown/custom keys are dropped before the request is sent, narrowing the payload to exactly the fields the Velt backend endpoint accepts. Open-typed objects (`actionUser`, `context`, `metadata`, user objects) pass through whole. Filtering is fail-open: if it errors, the original payload is sent, so a write is never blocked. `UPDATE_NOTIFICATIONS_SPEC` intentionally excludes `isRead`/`isArchived` — they are unsupported by `/v2/notifications/update`, so they are dropped when filtering is on. See [Field Allowlist](#field-allowlist) for the full per-endpoint field list.
#### `addNotifications`
* Adds one or more notifications targeted to specific users.
* Params: [AddNotificationsRequest](/docs/api-reference/sdk/models/data-models#addnotificationsrequest-node)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse-node)
* Accepts an optional `options?: FieldFilterOptions` second argument — pass `{ filterUnknownFields: true }` to drop unknown fields before sending (see the note above).
```ts theme={null}
await sdk.api.notifications.addNotifications({
organizationId: 'org-123',
documentId: 'doc-1',
actionUser: { userId: 'user-1', name: 'John Doe', email: 'john@example.com' },
displayHeadlineMessageTemplate: '{actionUser} commented on your document',
displayBodyMessage: 'Check out the new comment',
notifyUsers: [{ userId: 'user-2', name: 'Jane Doe' }],
createOrganization: true,
createDocument: true,
});
```
**Response**
```ts theme={null}
{ result: { status: 'success', message: 'Notification(s) added successfully.', data: {} } }
```
#### `getNotifications`
* Gets notifications for a user with optional filters and pagination.
* Params: [GetNotificationsRequest](/docs/api-reference/sdk/models/data-models#getnotificationsrequest-node)
* Returns: [GetNotificationsResponse](/docs/api-reference/sdk/models/data-models#getnotificationsresponse-node)
* Velt filters results by comment visibility: a notification for a private comment is returned only to users who can see that comment.
```ts theme={null}
await sdk.api.notifications.getNotifications({
organizationId: 'org-123',
userId: 'user-2',
pageSize: 10,
order: 'desc',
});
```
**Response**
```ts theme={null}
{
result: {
status: 'success',
message: 'Notification(s) retrieved successfully.',
data: [
{
id: 'notificationId',
notificationSource: 'custom',
actionUser: { userId: 'user-1', name: 'John Doe', email: 'john@example.com' },
displayBodyMessage: 'Check out the new comment',
displayHeadlineMessageTemplate: '{actionUser} commented on your document',
timestamp: 1722409519944
}
],
pageToken: 'nextPageToken'
}
}
```
#### `updateNotifications`
* Updates existing notifications (e.g., mark as read).
* Params: [UpdateNotificationsRequest](/docs/api-reference/sdk/models/data-models#updatenotificationsrequest-node)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse-node)
* Accepts an optional `options?: FieldFilterOptions` second argument — pass `{ filterUnknownFields: true }` to drop unknown fields before sending (see the note above).
```ts theme={null}
await sdk.api.notifications.updateNotifications({
organizationId: 'org-123',
userId: 'user-2',
notifications: [{ notificationId: 'n-1', read: true }],
});
```
**Response**
```ts theme={null}
{ result: { status: 'success', message: 'Notification(s) updated successfully.', data: {} } }
```
#### `deleteNotifications`
* Deletes one or more notifications.
* Params: [DeleteNotificationsRequest](/docs/api-reference/sdk/models/data-models#deletenotificationsrequest-node)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse-node)
```ts theme={null}
await sdk.api.notifications.deleteNotifications({
organizationId: 'org-123',
userId: 'user-2',
notificationIds: ['n-1'],
});
```
**Response**
```ts theme={null}
{ result: { status: 'success', message: 'Notification(s) deleted successfully.', data: {} } }
```
#### `getNotificationConfig`
* Gets notification preferences for a user.
* Params: [GetNotificationConfigRequest](/docs/api-reference/sdk/models/data-models#getnotificationconfigrequest-node)
* Returns: [GetNotificationConfigResponse](/docs/api-reference/sdk/models/data-models#getnotificationconfigresponse-node)
```ts theme={null}
await sdk.api.notifications.getNotificationConfig({
organizationId: 'org-123',
userId: 'user-1',
});
```
**Response**
```ts theme={null}
{
result: {
status: 'success',
message: 'User config fetched successfully.',
data: [
{
config: { inbox: 'ALL', email: 'ALL' },
metadata: { organizationId: 'org-123', apiKey: 'API_KEY', documentId: 'doc-1', userId: 'user-1' }
}
]
}
}
```
#### `setNotificationConfig`
* Sets notification preferences for one or more users.
* Params: [SetNotificationConfigRequest](/docs/api-reference/sdk/models/data-models#setnotificationconfigrequest-node)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse-node)
```ts theme={null}
await sdk.api.notifications.setNotificationConfig({
organizationId: 'org-123',
userIds: ['user-1', 'user-2'],
config: { inbox: 'ALL', email: 'MINE', slack: 'NONE' },
});
```
**Response**
```ts theme={null}
{ result: { status: 'success', message: 'User config set successfully.', data: {} } }
```
### Comment Annotations
**Namespace:** `sdk.api.commentAnnotations`
> [!NOTE]
>
> **Filtering unknown fields**: The add/update methods below accept an optional `options?: FieldFilterOptions` second argument. When `{ filterUnknownFields: true }` is passed, request entity collections are narrowed to only the fields the Velt backend endpoint accepts, dropping unknown/custom keys before the request is sent. Open-typed objects (`from`, `context`, `metadata`, user objects) pass through whole — their nested contents are never filtered. Filtering is fail-open: if it errors, the original payload is sent, so a write is never blocked. See [Field Allowlist](#field-allowlist) for the full per-endpoint field list.
```ts theme={null}
// Extra fields (internalId) are dropped before the request is sent.
await sdk.api.commentAnnotations.addCommentAnnotations(
{
organizationId: 'org-123',
documentId: 'doc-1',
commentAnnotations: [
{
location: { id: 'section-1' },
commentData: [{ commentText: 'Review this', from: { userId: 'user-1' } }],
internalId: 'app-specific-field', // dropped when filtering is enabled
},
],
},
{ filterUnknownFields: true },
);
```
#### `addCommentAnnotations`
* Creates comment annotations on a document.
* `location.id` is required. `status` needs `id`, `name` and `type` (`'default' | 'ongoing' | 'terminal'`); `priority` needs `id` and `name`; `visibility` needs `organizationId` for `organizationPrivate` and `userIds` for `restricted`; `pageInfo` needs `url` and `path`.
* Params: [AddCommentAnnotationsRequest](/docs/api-reference/sdk/models/data-models#addcommentannotationsrequest-node)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse-node)
* Accepts an optional `options?: FieldFilterOptions` second argument — pass `{ filterUnknownFields: true }` to drop unknown fields before sending (see the note above).
```ts theme={null}
await sdk.api.commentAnnotations.addCommentAnnotations({
organizationId: 'org-123',
documentId: 'doc-1',
commentAnnotations: [{
location: { id: 'section-1', locationName: 'Introduction' },
commentData: [{
commentText: 'This needs review',
commentHtml: 'This needs review
',
from: { userId: 'user-1', name: 'John Doe', email: 'john@example.com' },
}],
}],
});
```
**Response**
```ts theme={null}
{ result: { status: 'success', message: 'Annotation(s) added successfully.', data: {} } }
```
#### `getCommentAnnotations`
* Retrieves comment annotations for a document with optional filters and pagination.
* Params: [GetCommentAnnotationsRequest](/docs/api-reference/sdk/models/data-models#getcommentannotationsrequest-node)
* Returns: [GetCommentAnnotationsResponse](/docs/api-reference/sdk/models/data-models#getcommentannotationsresponse-node)
```ts theme={null}
await sdk.api.commentAnnotations.getCommentAnnotations({
organizationId: 'org-123',
documentId: 'doc-1',
statusIds: ['OPEN'],
pageSize: 10,
});
```
**Agent filters**
Scope a listing to agent-authored annotations with one of `agentId`, `executionId`, `agentType`, `agentSource`, `agentSuggestions`, or `agentComments`. Supply **at most one per request**.
```ts theme={null}
// All annotations authored by a specific agent
await sdk.api.commentAnnotations.getCommentAnnotations({
organizationId: 'org-123',
documentId: 'doc-1',
agentId: 'agent-7',
});
// Only fresh (unaccepted) agent suggestions
await sdk.api.commentAnnotations.getCommentAnnotations({
organizationId: 'org-123',
documentId: 'doc-1',
agentSuggestions: true,
});
```
> [!NOTE]
>
> Agent filtering is annotation-scoped and requires advanced queries to be enabled on your workspace. When they are not enabled, the API fails closed rather than returning unfiltered results.
**Response**
```ts theme={null}
{
result: {
status: 'success',
message: 'Annotations fetched successfully.',
data: [
{
type: 'comment',
comments: [
{
commentId: 123456,
commentText: 'This is a sample comment text.',
commentHtml: 'This is a sample comment text.
',
from: { userId: 'user123', name: 'John Doe', email: 'john.doe@example.com' },
createdAt: 1687344600000
}
],
status: { id: 'OPEN', name: 'Open', type: 'default' }
}
]
}
}
```
#### `getCommentAnnotationsCount`
* Gets total and unread annotation counts per document.
* `documentIds` is required (1 to 25 IDs); the API rejects the call with `INVALID_ARGUMENT` when it is omitted.
* Params: [GetCommentAnnotationsCountRequest](/docs/api-reference/sdk/models/data-models#getcommentannotationscountrequest-node)
* Returns: [GetCommentAnnotationsCountResponse](/docs/api-reference/sdk/models/data-models#getcommentannotationscountresponse-node)
```ts theme={null}
await sdk.api.commentAnnotations.getCommentAnnotationsCount({
organizationId: 'org-123',
documentIds: ['doc-1', 'doc-2'],
userId: 'user-1',
});
```
> [!WARNING]
>
> The count endpoint does **not** support agent filtering, and agent filter fields sent to it are ignored rather than rejected — you would receive unfiltered totals with no error. To count an agent-scoped subset, call [`getCommentAnnotations`](#getcommentannotations) with an agent filter and count the result.
**Response**
```ts theme={null}
{
result: {
status: 'success',
message: 'Comment count retrieved successfully.',
data: {
'doc-1': { total: 4, unread: 2 },
'doc-2': { total: 2, unread: 0 }
}
}
}
```
#### `updateCommentAnnotations`
* Updates fields on existing annotations (e.g., resolve them).
* Params: [UpdateCommentAnnotationsRequest](/docs/api-reference/sdk/models/data-models#updatecommentannotationsrequest-node)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse-node)
* Accepts an optional `options?: FieldFilterOptions` second argument — pass `{ filterUnknownFields: true }` to drop unknown fields before sending (see the note above).
```ts theme={null}
await sdk.api.commentAnnotations.updateCommentAnnotations({
organizationId: 'org-123',
documentId: 'doc-1',
annotationIds: ['annotation-id-1'],
updatedData: { status: { id: 'RESOLVED', name: 'Resolved', type: 'terminal' } },
});
```
**Response**
```ts theme={null}
{ result: { status: 'success', message: 'Annotation(s) updated successfully.', data: {} } }
```
#### `deleteCommentAnnotations`
* Deletes comment annotations.
* Params: [DeleteCommentAnnotationsRequest](/docs/api-reference/sdk/models/data-models#deletecommentannotationsrequest-node)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse-node)
```ts theme={null}
await sdk.api.commentAnnotations.deleteCommentAnnotations({
organizationId: 'org-123',
documentId: 'doc-1',
annotationIds: ['annotation-id-1'],
});
```
**Agent filters**
`agentSuggestions`, `agentId`, and `agentUrls` narrow a delete to agent-authored annotations. They combine, so you can scope a sweep precisely — for example, "this agent's still-pending suggestions on these pages", which leaves a concurrent crawl's freshly-created annotations untouched.
```ts theme={null}
await sdk.api.commentAnnotations.deleteCommentAnnotations({
organizationId: 'org-123',
documentId: 'doc-1',
agentId: 'agent-7',
agentSuggestions: true,
agentUrls: ['https://app.example.com/page-1', 'https://app.example.com/page-2'],
});
```
`agentUrls` matches annotations scoped to **any** of the supplied pages.
> [!WARNING]
>
> Agent filters require advanced queries to be enabled on your workspace. When they are not enabled — or when none of the supplied `agentUrls` resolve — the API fails closed and deletes nothing, rather than widening to a document-wide delete.
**Response**
```ts theme={null}
{ result: { status: 'success', message: 'Annotation(s) deleted successfully.', data: {} } }
```
#### `addComments`
* Adds comments to an existing annotation.
* Params: [AddCommentsRequest](/docs/api-reference/sdk/models/data-models#addcommentsrequest-node)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse-node)
* Accepts an optional `options?: FieldFilterOptions` second argument — pass `{ filterUnknownFields: true }` to drop unknown fields before sending (see the note above).
```ts theme={null}
await sdk.api.commentAnnotations.addComments({
organizationId: 'org-123',
documentId: 'doc-1',
annotationId: 'annotation-id-1',
commentData: [{
commentText: 'I agree, let me fix this',
from: { userId: 'user-2', name: 'Jane Doe' },
}],
});
```
**Response**
```ts theme={null}
{ result: { status: 'success', message: 'Comment(s) added successfully.', data: {} } }
```
#### `getComments`
* Retrieves comments within a specific annotation.
* Params: [GetCommentsRequest](/docs/api-reference/sdk/models/data-models#getcommentsrequest-node)
* Returns: [GetCommentsResponse](/docs/api-reference/sdk/models/data-models#getcommentsresponse-node)
```ts theme={null}
await sdk.api.commentAnnotations.getComments({
organizationId: 'org-123',
documentId: 'doc-1',
annotationId: 'annotation-id-1',
userIds: ['user-1'],
});
```
**Response**
```ts theme={null}
{
result: {
status: 'success',
message: 'Comments(s) retrieved successfully.',
data: [
{
commentId: 153783,
commentText: 'Sample Comment Text',
commentHtml: 'Hello Updated 2
',
from: { userId: 'yourUserId', name: 'User Name', email: 'user@example.com' },
lastUpdated: '2024-06-20T09:53:42.258Z',
status: 'added',
type: 'text'
}
]
}
}
```
#### `updateComments`
* Updates comments within a specific annotation.
* Params: [UpdateCommentsRequest](/docs/api-reference/sdk/models/data-models#updatecommentsrequest-node)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse-node)
* Accepts an optional `options?: FieldFilterOptions` second argument — pass `{ filterUnknownFields: true }` to drop unknown fields before sending (see the note above).
```ts theme={null}
await sdk.api.commentAnnotations.updateComments({
organizationId: 'org-123',
documentId: 'doc-1',
annotationId: 'annotation-id-1',
commentIds: [123456],
updatedData: { commentText: 'Updated text', commentHtml: 'Updated text
' },
});
```
**Response**
```ts theme={null}
{ result: { status: 'success', message: 'Comment(s) updated successfully.', data: {} } }
```
#### `deleteComments`
* Deletes individual comments from an annotation.
* Params: [DeleteCommentsRequest](/docs/api-reference/sdk/models/data-models#deletecommentsrequest-node)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse-node)
```ts theme={null}
await sdk.api.commentAnnotations.deleteComments({
organizationId: 'org-123',
documentId: 'doc-1',
annotationId: 'annotation-id-1',
commentIds: [123456],
});
```
**Response**
```ts theme={null}
{ result: { status: 'success', message: 'Comment(s) deleted successfully.', data: {} } }
```
### Activities
**Namespace:** `sdk.api.activities`
> [!NOTE]
>
> **Filtering unknown fields**: The add/update methods below accept an optional `options?: FieldFilterOptions` second argument. When `{ filterUnknownFields: true }` is passed, request entity collections are narrowed to only the fields the Velt backend endpoint accepts, dropping unknown/custom keys before the request is sent. Open-typed objects (`actionUser`, `entityData`, `context`, `metadata`) pass through whole — their nested contents are never filtered. Filtering is fail-open: if it errors, the original payload is sent, so a write is never blocked. See [Field Allowlist](#field-allowlist) for the full per-endpoint field list.
#### `addActivities`
* Logs activity events.
* `changes` is a record keyed by field name (`{ title: { from, to } }`), not an array. A `custom` activity requires `targetEntityId`.
* Params: [AddActivitiesRequest](/docs/api-reference/sdk/models/data-models#addactivitiesrequest-node)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse-node)
* Accepts an optional `options?: FieldFilterOptions` second argument — pass `{ filterUnknownFields: true }` to drop unknown fields before sending (see the note above).
```ts theme={null}
await sdk.api.activities.addActivities({
organizationId: 'org-123',
documentId: 'doc-456',
activities: [{
featureType: 'comment',
actionType: 'comment.add',
actionUser: { userId: 'user-1', name: 'John Doe', email: 'john@example.com' },
displayMessageTemplate: '{{user}} added a comment',
}],
});
```
**Response**
```ts theme={null}
{ result: { status: 'success', message: 'Activity(s) added successfully.', data: {} } }
```
#### `getActivities`
* Retrieves activity events with optional filters and pagination.
* Params: [GetActivitiesRequest](/docs/api-reference/sdk/models/data-models#getactivitiesrequest-node)
* Returns: [GetActivitiesResponse](/docs/api-reference/sdk/models/data-models#getactivitiesresponse-node)
```ts theme={null}
await sdk.api.activities.getActivities({
organizationId: 'org-123',
documentId: 'doc-456',
featureTypes: ['comment'],
order: 'desc',
pageSize: 50,
});
```
**Response**
```ts theme={null}
{
result: {
status: 'success',
message: 'Activity(s) retrieved successfully.',
data: [
{
id: 'activity-001',
featureType: 'comment',
actionType: 'comment.add',
actionUser: { userId: 'user-1', email: 'user@example.com', name: 'User Name' },
targetEntityId: 'annotation-789',
displayMessageTemplate: '{{user}} added a comment',
metadata: { apiKey: 'yourApiKey', documentId: 'doc-456', organizationId: 'org-123' },
timestamp: 1722409519944
}
],
pageToken: 'nextPageToken'
}
}
```
#### `updateActivities`
* Updates existing activity events.
* Each item is identified by `id` (`activityId` is a deprecated alias). `changes` is a record keyed by field name.
* Params: [UpdateActivitiesRequest](/docs/api-reference/sdk/models/data-models#updateactivitiesrequest-node)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse-node)
* Accepts an optional `options?: FieldFilterOptions` second argument — pass `{ filterUnknownFields: true }` to drop unknown fields before sending (see the note above).
```ts theme={null}
await sdk.api.activities.updateActivities({
organizationId: 'org-123',
activities: [{ id: 'activity-001', displayMessageTemplate: '{{user}} updated the comment' }],
});
```
**Response**
```ts theme={null}
{ result: { status: 'success', message: 'Activity(s) updated successfully.', data: {} } }
```
#### `deleteActivities`
* Deletes activity events for a document.
* Params: [DeleteActivitiesRequest](/docs/api-reference/sdk/models/data-models#deleteactivitiesrequest-node)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse-node)
```ts theme={null}
await sdk.api.activities.deleteActivities({
organizationId: 'org-123',
documentId: 'doc-456',
});
```
**Response**
```ts theme={null}
{ result: { status: 'success', message: 'Activity(s) deleted successfully.', data: {} } }
```
### Access Control
**Namespace:** `sdk.api.accessControl`
#### `addPermissions`
* Grants a user access to one or more resources.
* Params: [AddPermissionsRequest](/docs/api-reference/sdk/models/data-models#addpermissionsrequest-node)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse-node)
```ts theme={null}
await sdk.api.accessControl.addPermissions({
user: { userId: 'user-1' },
permissions: {
resources: [
{ type: 'organization', id: 'org-123', accessRole: 'editor' },
{ type: 'document', id: 'doc-1', organizationId: 'org-123', accessRole: 'viewer', expiresAt: 1728902400 },
],
},
});
```
**Response**
```ts theme={null}
{ result: { status: 'success', message: 'Permissions added successfully.', data: {} } }
```
#### `getPermissions`
* Retrieves permissions for users on resources. Pass at least one of `folderIds` or `documentIds`; the API rejects a call with neither.
* Params: [GetPermissionsRequest](/docs/api-reference/sdk/models/data-models#getpermissionsrequest-node)
* Returns: [GetPermissionsResponse](/docs/api-reference/sdk/models/data-models#getpermissionsresponse-node)
```ts theme={null}
await sdk.api.accessControl.getPermissions({
organizationId: 'org-123',
userIds: ['user-1'],
documentIds: ['doc-1'],
});
```
By default the API errors if any supplied folder or document ID does not resolve. Pass `skipResourceExistenceValidation: true` to skip that check and return whatever permissions exist:
```ts theme={null}
await sdk.api.accessControl.getPermissions({
organizationId: 'org-123',
userIds: ['user-1'],
documentIds: ['doc-1', 'doc-might-not-exist'],
skipResourceExistenceValidation: true,
});
```
**Response**
```ts theme={null}
{
result: {
status: 'success',
message: 'User permissions retrieved successfully.',
data: {
'user-1': {
documents: { 'doc-1': { accessRole: 'viewer', accessType: 'restricted' } },
organization: { 'org-123': { accessRole: 'editor' } }
}
}
}
}
```
#### `removePermissions`
* Revokes a user's access to one or more resources.
* Params: [RemovePermissionsRequest](/docs/api-reference/sdk/models/data-models#removepermissionsrequest-node)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse-node)
```ts theme={null}
await sdk.api.accessControl.removePermissions({
userId: 'user-1',
permissions: {
resources: [
{ type: 'organization', id: 'org-123' },
{ type: 'document', id: 'doc-1', organizationId: 'org-123' },
],
},
});
```
**Response**
```ts theme={null}
{ result: { status: 'success', message: 'Permissions removed successfully.', data: {} } }
```
#### `generateSignature`
* Generates a signed payload for the Permission Provider flow.
* Params: [GenerateSignatureRequest](/docs/api-reference/sdk/models/data-models#generatesignaturerequest-node)
* Returns: [GenerateSignatureResponse](/docs/api-reference/sdk/models/data-models#generatesignatureresponse-node)
```ts theme={null}
await sdk.api.accessControl.generateSignature({
permissions: [{
userId: 'user-1',
resourceId: 'doc-1',
type: 'document',
hasAccess: true,
accessRole: 'viewer',
}],
});
```
**Response**
```ts theme={null}
{
result: {
status: 'success',
message: 'Signature generated successfully.',
data: { signature: 'a1b2c3d4e5f6...' }
}
}
```
#### `generateToken`
* Generates a JWT auth token for a user with embedded permissions.
* Calls `POST /v2/auth/generate_token`, the endpoint documented in the [Generate Token REST API](/docs/api-reference/rest-apis/v2/auth/generate-token) and used by the [JWT guide](/docs/security/jwt-tokens).
* Expects `GenerateTokenRequest { userId: string; userProperties: { name?, email?, photoUrl?, color?, textColor?, ... }; permissions: { resources?: Resource[] } }`, passed as a request object like every other `sdk.api.*` method.
* Returns the raw Velt API envelope `VeltApiResponse`: `{ result: { status, message, data: { token } } }`.
* Params: [GenerateTokenRequest](/docs/api-reference/sdk/models/data-models#generatetokenrequest-node)
* Returns: [GenerateTokenResponse](/docs/api-reference/sdk/models/data-models#generatetokenresponse-node)
```ts theme={null}
await sdk.api.accessControl.generateToken({
userId: 'user-1',
userProperties: { name: 'John Doe', email: 'john@example.com', isAdmin: false },
permissions: {
resources: [
{ type: 'organization', id: 'org-123', accessRole: 'viewer' },
{ type: 'document', id: 'doc-1', organizationId: 'org-123', accessRole: 'editor' },
],
},
});
```
**Response**
```ts theme={null}
{
result: {
status: 'success',
message: 'Token generated successfully.',
data: { token: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...' }
}
}
```
### CRDT
**Namespace:** `sdk.api.crdt`
Supports `text`, `map`, `array`, and `xml` CRDT data types.
#### `addCrdtData`
* Stores CRDT (Yjs) editor data for a document.
* Params: [AddCrdtDataRequest](/docs/api-reference/sdk/models/data-models#addcrdtdatarequest-node)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse-node)
```ts theme={null}
await sdk.api.crdt.addCrdtData({
organizationId: 'org-123',
documentId: 'doc-1',
editorId: 'my-collab-note',
data: 'Hello, collaborative world!',
type: 'text',
});
```
**Response**
```ts theme={null}
{ result: { status: 'success', message: 'CRDT data added successfully.', data: {} } }
```
#### `getCrdtData`
* Retrieves CRDT data for a document, optionally filtered by editor.
* Params: [GetCrdtDataRequest](/docs/api-reference/sdk/models/data-models#getcrdtdatarequest-node)
* Returns: [GetCrdtDataResponse](/docs/api-reference/sdk/models/data-models#getcrdtdataresponse-node)
```ts theme={null}
await sdk.api.crdt.getCrdtData({
organizationId: 'org-123',
documentId: 'doc-1',
editorId: 'my-collab-note',
});
```
**Response**
```ts theme={null}
{
result: {
status: 'success',
message: 'CRDT data retrieved successfully.',
data: [
{
data: 'Hello, collaborative world!',
id: 'my-collab-note',
lastUpdate: '2025-01-20T10:30:00.000Z',
lastUpdatedBy: 'user-123',
sessionId: 'session-abc-456'
}
]
}
}
```
#### `updateCrdtData`
* Updates existing CRDT editor data.
* Params: [UpdateCrdtDataRequest](/docs/api-reference/sdk/models/data-models#updatecrdtdatarequest-node)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse-node)
```ts theme={null}
await sdk.api.crdt.updateCrdtData({
organizationId: 'org-123',
documentId: 'doc-1',
editorId: 'my-collab-note',
data: 'Updated collaborative content!',
type: 'text',
});
```
**Response**
```ts theme={null}
{ result: { status: 'success', message: 'CRDT data updated successfully.', data: {} } }
```
#### `deleteCrdtData`
* Delete CRDT editor data for a document. Omit `editorIds` to delete CRDT data for all editors of the document.
* Params: [DeleteCrdtDataRequest](/docs/api-reference/sdk/models/data-models#deletecrdtdatarequest-node)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse-node)
```ts theme={null}
await sdk.api.crdt.deleteCrdtData({ organizationId: 'org-123', documentId: 'doc-1', editorIds: ['my-collab-note'] });
await sdk.api.crdt.deleteCrdtData({ organizationId: 'org-123', documentId: 'doc-1' });
```
**Response**
```ts theme={null}
{ result: { status: 'success', message: 'CRDT data deleted successfully.', data: {} } }
```
### Presence
**Namespace:** `sdk.api.presence`
#### `addPresence`
* Adds users to presence on a document.
* Params: [AddPresenceRequest](/docs/api-reference/sdk/models/data-models#addpresencerequest-node)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse-node)
```ts theme={null}
await sdk.api.presence.addPresence({
organizationId: 'org-123',
documentId: 'doc-456',
users: [
{ userId: 'user-1', name: 'John Doe', email: 'john@example.com', status: 'online' },
{ userId: 'user-2', name: 'Jane Doe', status: 'away' },
],
});
```
**Response**
```ts theme={null}
{ result: { status: 'success', message: 'Presence added successfully.', data: {} } }
```
#### `updatePresence`
* Updates presence status for one or more users.
* Params: [UpdatePresenceRequest](/docs/api-reference/sdk/models/data-models#updatepresencerequest-node)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse-node)
```ts theme={null}
await sdk.api.presence.updatePresence({
organizationId: 'org-123',
documentId: 'doc-456',
users: [{ userId: 'user-1', status: 'away' }],
});
```
**Response**
```ts theme={null}
{ result: { status: 'success', message: 'Presence updated successfully.', data: {} } }
```
#### `deletePresence`
* Removes users from presence on a document.
* Params: [DeletePresenceRequest](/docs/api-reference/sdk/models/data-models#deletepresencerequest-node)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse-node)
```ts theme={null}
await sdk.api.presence.deletePresence({
organizationId: 'org-123',
documentId: 'doc-456',
userIds: ['user-1', 'user-2'],
});
```
**Response**
```ts theme={null}
{ result: { status: 'success', message: 'Presence removed successfully.', data: {} } }
```
### Livestate
**Namespace:** `sdk.api.livestate`
#### `broadcastEvent`
* Broadcasts an ephemeral live-state event to all clients on a document.
* Params: [BroadcastEventRequest](/docs/api-reference/sdk/models/data-models#broadcasteventrequest-node)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse-node)
```ts theme={null}
await sdk.api.livestate.broadcastEvent({
organizationId: 'org-123',
documentId: 'doc-1',
liveStateDataId: 'my-live-state',
data: { status: 'active', message: 'Hello World' },
merge: true,
});
```
**Response**
```ts theme={null}
{ result: { status: 'success', message: 'Event broadcast successfully.', data: {} } }
```
### Recordings
**Namespace:** `sdk.api.recordings`
#### `getRecordings`
* Retrieves recording metadata for a document. Pass `documentId` to target the document; omitting it returns an empty list, not the organization's recordings. `recordingIds` filters the fetched page.
* Params: [GetRecordingsRequest](/docs/api-reference/sdk/models/data-models#getrecordingsrequest-node)
* Returns: [GetRecordingsResponse](/docs/api-reference/sdk/models/data-models#getrecordingsresponse-node)
```ts theme={null}
await sdk.api.recordings.getRecordings({
organizationId: 'org-123',
documentId: 'doc-456',
recordingIds: ['rec-1'],
pageSize: 10,
pageToken: 'next-page-token',
});
```
**Response**
```ts theme={null}
{
result: {
status: 'success',
message: 'Recorder annotations retrieved successfully.',
data: [
{
type: 'recorder',
recordingType: 'screen',
mode: 'floating',
metadata: { apiKey: 'YOUR_API_KEY', documentId: 'doc-456', organizationId: 'org-123' },
recordedTime: { duration: 4204.55, display: '00:00:04' },
displayName: 'Screen Recording 1773814490242.mp4',
annotationId: 'ypvmVTROaNU1qP4kq7Cc',
attachments: [{
attachmentId: 875113,
url: 'https://storage.googleapis.com/...',
mimeType: 'video/mp4',
name: 'recording_1773814490242.mp4',
type: 'mp4',
size: 103551
}],
latestVersion: 5
}
],
pageToken: 'nextPageToken'
}
}
```
### Rewriter
**Namespace:** `sdk.api.rewriter`
Supports OpenAI, Anthropic, and Gemini models.
#### `askAi`
* Calls the Velt AI rewriter with a model, prompt, and text.
* Params: [AskAiRequest](/docs/api-reference/sdk/models/data-models#askairequest-node)
* Returns: [AskAiResponse](/docs/api-reference/sdk/models/data-models#askairesponse-node)
> Note: `askAi` may take several seconds to respond. The SDK does not enforce a client-side timeout.
```ts theme={null}
await sdk.api.rewriter.askAi({
model: 'gpt-4o',
prompt: 'Fix the grammar and spelling in the following text.',
text: 'Their going to the store to by some apples.',
});
```
**Response**
```ts theme={null}
{
result: {
success: true,
text: 'The rewritten or processed text returned by the model.'
}
}
```
### GDPR
**Namespace:** `sdk.api.gdpr`
#### `deleteAllUserData`
* Requests deletion of all data associated with one or more users.
* Params: [DeleteAllUserDataRequest](/docs/api-reference/sdk/models/data-models#deletealluserdatarequest-node)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse-node)
> Note: `deleteAllUserData` is asynchronous and returns a job ID. Poll completion with `getDeleteUserDataStatus`.
```ts theme={null}
await sdk.api.gdpr.deleteAllUserData({
userIds: ['user-1', 'user-2'],
organizationIds: ['org-123'],
});
```
**Response**
```ts theme={null}
{
result: {
status: 'success',
message: 'User data deletion job queued.',
data: { jobId: 'delete-job-id' }
}
}
```
#### `getAllUserData`
* Exports all data for a single user (paginated).
* Params: [GetAllUserDataRequest](/docs/api-reference/sdk/models/data-models#getalluserdatarequest-node)
* Returns: [GetAllUserDataResponse](/docs/api-reference/sdk/models/data-models#getalluserdataresponse-node)
```ts theme={null}
await sdk.api.gdpr.getAllUserData({
organizationId: 'org-123',
userId: 'user-1',
pageToken: 'next-page-token',
});
```
Pass `veltUserIds` to export data for a set of Velt-side user IDs instead of the single `userId`, and `veltAllOrganizations` to span every organization rather than just `organizationId`. `uniqueId` is accepted but ignored and is not returned in the response:
```ts theme={null}
await sdk.api.gdpr.getAllUserData({
organizationId: 'org-123',
userId: 'user-1',
veltUserIds: ['velt-user-1', 'velt-user-2'],
veltAllOrganizations: true,
});
```
**Response**
```ts theme={null}
{
result: {
status: 'success',
message: 'Data fetched successfully.',
data: {
comments: [/* up to 100 items */],
reactions: [/* up to 100 items */],
recordings: [/* up to 100 items */],
notifications: [/* up to 100 items */]
},
nextPageToken: 'bhdwdqwjs298e39e479ddkeuw==329'
}
}
```
#### `getDeleteUserDataStatus`
* Polls the status of a deletion job.
* Params: [GetDeleteUserDataStatusRequest](/docs/api-reference/sdk/models/data-models#getdeleteuserdatastatusrequest-node)
* Returns: [GetDeleteUserDataStatusResponse](/docs/api-reference/sdk/models/data-models#getdeleteuserdatastatusresponse-node)
```ts theme={null}
await sdk.api.gdpr.getDeleteUserDataStatus({ jobId: 'job-id-from-delete-call' });
```
**Response**
```ts theme={null}
{
result: {
status: 'success',
message: 'Data fetched successfully.',
data: {
isDeleteCompleted: true,
tasksLeft: 0,
lastTaskCompletedTime: 1748972106739
}
}
}
```
### Workspace
**Namespace:** `sdk.api.workspace`
#### `createWorkspace`
* Creates a new Velt workspace.
* Params: [CreateWorkspaceRequest](/docs/api-reference/sdk/models/data-models#createworkspacerequest-node)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse-node)
```ts theme={null}
await sdk.api.workspace.createWorkspace({
ownerEmail: 'owner@example.com',
workspaceName: 'My Workspace',
name: 'John Doe',
});
```
**Response**
```ts theme={null}
{ result: { status: 'success', message: 'Workspace created successfully.', data: {} } }
```
#### `getWorkspace`
* Retrieves details for the current workspace.
* Params: empty object `{}`
* Returns: [GetWorkspaceResponse](/docs/api-reference/sdk/models/data-models#getworkspaceresponse-node)
```ts theme={null}
await sdk.api.workspace.getWorkspace({});
```
**Response**
```ts theme={null}
{
result: {
status: 'success',
message: 'Workspace retrieved successfully.',
data: {
id: 'workspace_abc123',
name: 'My Workspace',
owner: { email: 'owner@example.com', id: 'owner_id_123', name: 'John Doe', avatar: '' },
authToken: 'eyJhbGciOiJSUzI1NiIs...',
apiKeyList: {
velt_api_key_1: { apiKeyName: 'John Doe Test API Key', id: 'velt_api_key_1', type: 'testing' }
}
}
}
}
```
#### `createApiKey`
* Creates a new API key for the workspace.
* Params: [CreateApiKeyRequest](/docs/api-reference/sdk/models/data-models#createapikeyrequest-node)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse-node)
```ts theme={null}
await sdk.api.workspace.createApiKey({
ownerEmail: 'owner@example.com',
type: 'production',
createAuthToken: true,
apiKeyName: 'Production Key',
allowedDomains: ['example.com', '*.example.com'],
});
```
**Response**
```ts theme={null}
{
result: {
status: 'success',
message: 'API key created successfully.',
data: { apiKey: 'velt_api_key_2', authToken: 'eyJhbGciOi...' }
}
}
```
#### `updateApiKey`
* Renames an existing API key.
* Params: [UpdateApiKeyRequest](/docs/api-reference/sdk/models/data-models#updateapikeyrequest-node)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse-node)
```ts theme={null}
await sdk.api.workspace.updateApiKey({ apiKey: 'velt_api_key_1', apiKeyName: 'Renamed Key' });
```
**Response**
```ts theme={null}
{ result: { status: 'success', message: 'API key updated successfully.', data: {} } }
```
#### `getApiKeys`
* Lists all API keys with optional pagination.
* Params: [GetApiKeysRequest](/docs/api-reference/sdk/models/data-models#getapikeysrequest-node)
* Returns: [GetApiKeysResponse](/docs/api-reference/sdk/models/data-models#getapikeysresponse-node)
```ts theme={null}
await sdk.api.workspace.getApiKeys({ pageSize: 50, pageToken: 'next-page-token' });
```
**Response**
```ts theme={null}
{
result: {
status: 'success',
message: 'API keys retrieved successfully.',
data: [
{ id: 'velt_api_key_1', apiKeyName: 'Production Key', type: 'production' },
{ id: 'velt_api_key_2', apiKeyName: 'Testing Key', type: 'testing' }
],
nextPageToken: 'eyJsYXN0SWQiOiJ2ZWx0X2FwaV9rZXlfMiJ9'
}
}
```
#### `getApiKeyMetadata`
* Gets metadata for the current API key.
* Now posts to `/v2/workspace/apikeyconfig/get` (previously `/v2/workspace/apikeymetadata/get`); the method name and signature (`GetApiKeyMetadataRequest`, which is `{}`) are unchanged — no caller changes required.
* Params: empty object `{}`
* Returns: [GetApiKeyMetadataResponse](/docs/api-reference/sdk/models/data-models#getapikeymetadataresponse-node)
```ts theme={null}
await sdk.api.workspace.getApiKeyMetadata({});
```
**Response**
```ts theme={null}
{
result: {
status: 'success',
message: 'API key metadata retrieved successfully.',
data: {
defaultDocumentAccessType: 'public',
planInfo: { type: 'sdk test' },
ownerEmail: 'owner@example.com'
}
}
}
```
#### `resetAuthToken`
* Rotates the auth token for an API key.
* Params: [ResetAuthTokenRequest](/docs/api-reference/sdk/models/data-models#resetauthtokenrequest-node)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse-node)
```ts theme={null}
await sdk.api.workspace.resetAuthToken({ apiKey: 'velt_api_key_1' });
```
**Response**
```ts theme={null}
{
result: {
status: 'success',
message: 'Auth token reset successfully.',
data: { authToken: 'eyJhbGciOi...' }
}
}
```
#### `getAuthTokens`
* Lists auth tokens for an API key.
* Params: [GetAuthTokensRequest](/docs/api-reference/sdk/models/data-models#getauthtokensrequest-node)
* Returns: [GetAuthTokensResponse](/docs/api-reference/sdk/models/data-models#getauthtokensresponse-node)
```ts theme={null}
await sdk.api.workspace.getAuthTokens({ apiKey: 'velt_api_key_1' });
```
**Response**
```ts theme={null}
{
result: {
status: 'success',
message: 'Auth tokens retrieved successfully.',
data: {
apiKey: 'velt_api_key_1',
authTokens: [
{ token: 'eyJhbGciOiJSUzI1NiIs...', name: 'Default Auth Token', domains: [] }
]
}
}
}
```
#### `addDomains`
* Adds allowed domains to the workspace allow-list.
* Params: [AddDomainsRequest](/docs/api-reference/sdk/models/data-models#adddomainsrequest-node)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse-node)
```ts theme={null}
await sdk.api.workspace.addDomains({ domains: ['example.com', '*.firebase.com'] });
```
**Response**
```ts theme={null}
{ result: { status: 'success', message: 'Domains added successfully.', data: {} } }
```
#### `deleteDomains`
* Removes allowed domains.
* Params: [DeleteDomainsRequest](/docs/api-reference/sdk/models/data-models#deletedomainsrequest-node)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse-node)
```ts theme={null}
await sdk.api.workspace.deleteDomains({ domains: ['example.com'] });
```
**Response**
```ts theme={null}
{ result: { status: 'success', message: 'Domains deleted successfully.', data: {} } }
```
#### `getDomains`
* Lists allowed domains.
* Params: empty object `{}`
* Returns: [GetDomainsResponse](/docs/api-reference/sdk/models/data-models#getdomainsresponse-node)
```ts theme={null}
await sdk.api.workspace.getDomains({});
```
**Response**
```ts theme={null}
{
result: {
status: 'success',
message: 'Allowed domains retrieved successfully.',
data: { allowedDomains: ['localhost', '127.0.0.1', 'example.com'] }
}
}
```
#### `getEmailStatus`
* Checks email verification status for an owner.
* Params: [GetEmailStatusRequest](/docs/api-reference/sdk/models/data-models#getemailstatusrequest-node)
* Returns: [GetEmailStatusResponse](/docs/api-reference/sdk/models/data-models#getemailstatusresponse-node)
```ts theme={null}
await sdk.api.workspace.getEmailStatus({ ownerEmail: 'owner@example.com' });
```
**Response**
```ts theme={null}
{
result: {
status: 'success',
message: 'Email verified and workspace reactivated',
data: { verified: true }
}
}
```
#### `sendLoginLink`
* Sends a passwordless login link to a user.
* Params: [SendLoginLinkRequest](/docs/api-reference/sdk/models/data-models#sendloginlinkrequest-node)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse-node)
```ts theme={null}
await sdk.api.workspace.sendLoginLink({
email: 'user@example.com',
continueUrl: 'https://app.example.com/dashboard',
});
```
**Response**
```ts theme={null}
{ result: { status: 'success', message: 'Login link sent.', data: {} } }
```
#### `getEmailConfig`
* Retrieves email service configuration.
* Params: empty object `{}`
* Returns: [GetEmailConfigResponse](/docs/api-reference/sdk/models/data-models#getemailconfigresponse-node)
```ts theme={null}
await sdk.api.workspace.getEmailConfig({});
```
**Response**
```ts theme={null}
{
result: {
status: 'success',
message: 'Email configuration retrieved successfully.',
data: {
useEmailService: false,
emailServiceConfig: { type: 'default', apiKey: '', fromEmail: '', fromCompany: '', commentTemplateId: '', tagTemplateId: '' }
}
}
}
```
#### `updateEmailConfig`
* Updates email service configuration.
* Params: [UpdateEmailConfigRequest](/docs/api-reference/sdk/models/data-models#updateemailconfigrequest-node)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse-node)
```ts theme={null}
await sdk.api.workspace.updateEmailConfig({
useEmailService: true,
emailServiceConfig: { type: 'sendgrid', apiKey: 'sg-key', fromEmail: 'noreply@example.com' },
});
```
**Response**
```ts theme={null}
{ result: { status: 'success', message: 'Email config updated successfully.', data: {} } }
```
#### `getWebhookConfig`
* Retrieves webhook configuration.
* Params: empty object `{}`
* Returns: [GetWebhookConfigResponse](/docs/api-reference/sdk/models/data-models#getwebhookconfigresponse-node)
```ts theme={null}
await sdk.api.workspace.getWebhookConfig({});
```
**Response**
```ts theme={null}
{
result: {
status: 'success',
message: 'Webhook configuration retrieved successfully.',
data: {
useWebhookService: false,
webhookServiceConfig: { authToken: '', rawNotificationUrl: '', processedNotificationUrl: '' }
}
}
}
```
#### `updateWebhookConfig`
* Updates webhook configuration.
* Params: [UpdateWebhookConfigRequest](/docs/api-reference/sdk/models/data-models#updatewebhookconfigrequest-node)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse-node)
```ts theme={null}
await sdk.api.workspace.updateWebhookConfig({
useWebhookService: true,
webhookServiceConfig: {
authToken: 'webhook-secret',
rawNotificationUrl: 'https://example.com/webhook/raw',
processedNotificationUrl: 'https://example.com/webhook/processed',
},
});
```
**Response**
```ts theme={null}
{ result: { status: 'success', message: 'Webhook config updated successfully.', data: {} } }
```
#### `getRequestedDomains`
* List requested additional domains.
* Params: [GetRequestedDomainsRequest](/docs/api-reference/sdk/models/data-models#getrequesteddomainsrequest-node)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse-node)
```ts theme={null}
await sdk.api.workspace.getRequestedDomains({});
```
**Response**
```ts theme={null}
{ result: { status: 'success', message: 'Requested domains retrieved successfully.', data: [] } }
```
#### `acceptRejectAdditionalUrlRequest`
* Accept/reject an additional-URL request.
* Params: [AcceptRejectAdditionalUrlRequest](/docs/api-reference/sdk/models/data-models#acceptrejectadditionalurlrequest-node)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse-node)
```ts theme={null}
await sdk.api.workspace.acceptRejectAdditionalUrlRequest({ action: 'accept', id: 'req-1', clientDocId: 'doc-1' });
```
**Response**
```ts theme={null}
{ result: { status: 'success', message: 'Additional URL request updated successfully.', data: {} } }
```
#### `createDomainRequest`
* Create a domain request.
* Params: [CreateDomainRequest](/docs/api-reference/sdk/models/data-models#createdomainrequest-node)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse-node)
```ts theme={null}
await sdk.api.workspace.createDomainRequest({ domain: 'https://example.com', clientDocumentId: 'doc-1', organizationId: 'org-123' });
```
**Response**
```ts theme={null}
{ result: { status: 'success', message: 'Domain request created successfully.', data: {} } }
```
#### `copyApiKey`
* Copy configuration from one API key to another.
* Params: [CopyApiKeyRequest](/docs/api-reference/sdk/models/data-models#copyapikeyrequest-node)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse-node)
```ts theme={null}
await sdk.api.workspace.copyApiKey({ sourceApiKey: 'velt_api_key_1', targetApiKey: 'velt_api_key_2' });
```
**Response**
```ts theme={null}
{ result: { status: 'success', message: 'API key configuration copied successfully.', data: {} } }
```
#### `updateApiKeyConfig`
* Update API key config (private comments, JWT, AI model keys, etc.).
* Params: [UpdateApiKeyConfigRequest](/docs/api-reference/sdk/models/data-models#updateapikeyconfigrequest-node)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse-node)
```ts theme={null}
await sdk.api.workspace.updateApiKeyConfig({ requireJwtToken: true, defaultDocumentAccessType: 'organizationPrivate' });
```
**Response**
```ts theme={null}
{ result: { status: 'success', message: 'API key config updated successfully.', data: {} } }
```
#### `getNotificationConfig`
* Get workspace notification service config.
* Params: [GetWorkspaceNotificationConfigRequest](/docs/api-reference/sdk/models/data-models#getworkspacenotificationconfigrequest-node)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse-node)
```ts theme={null}
await sdk.api.workspace.getNotificationConfig({});
```
**Response**
```ts theme={null}
{ result: { status: 'success', message: 'Notification config retrieved successfully.', data: {} } }
```
#### `updateNotificationConfig`
* Update notification service config.
* Params: [UpdateWorkspaceNotificationConfigRequest](/docs/api-reference/sdk/models/data-models#updateworkspacenotificationconfigrequest-node)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse-node)
```ts theme={null}
await sdk.api.workspace.updateNotificationConfig({ useNotificationService: true });
```
**Response**
```ts theme={null}
{ result: { status: 'success', message: 'Notification config updated successfully.', data: {} } }
```
#### `getPermissionProviderConfig`
* Get permission-provider config.
* Params: [GetPermissionProviderConfigRequest](/docs/api-reference/sdk/models/data-models#getpermissionproviderconfigrequest-node)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse-node)
```ts theme={null}
await sdk.api.workspace.getPermissionProviderConfig({});
```
**Response**
```ts theme={null}
{ result: { status: 'success', message: 'Permission provider config retrieved successfully.', data: {} } }
```
#### `updatePermissionProviderConfig`
* Update permission-provider config.
* Params: [UpdatePermissionProviderConfigRequest](/docs/api-reference/sdk/models/data-models#updatepermissionproviderconfigrequest-node)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse-node)
```ts theme={null}
await sdk.api.workspace.updatePermissionProviderConfig({ usePermissionProvider: true });
```
**Response**
```ts theme={null}
{ result: { status: 'success', message: 'Permission provider config updated successfully.', data: {} } }
```
#### `getActivityConfig`
* Get activity service config.
* Params: [GetActivityConfigRequest](/docs/api-reference/sdk/models/data-models#getactivityconfigrequest-node)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse-node)
```ts theme={null}
await sdk.api.workspace.getActivityConfig({});
```
**Response**
```ts theme={null}
{ result: { status: 'success', message: 'Activity config retrieved successfully.', data: {} } }
```
#### `updateActivityConfig`
* Update activity service config.
* Params: [UpdateActivityConfigRequest](/docs/api-reference/sdk/models/data-models#updateactivityconfigrequest-node)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse-node)
```ts theme={null}
await sdk.api.workspace.updateActivityConfig({ activityServiceConfig: { isEnabled: true } });
```
**Response**
```ts theme={null}
{ result: { status: 'success', message: 'Activity config updated successfully.', data: {} } }
```
#### `ensureWorkspaceAuthToken`
* Ensure a workspace auth token exists.
* Params: [EnsureWorkspaceAuthTokenRequest](/docs/api-reference/sdk/models/data-models#ensureworkspaceauthtokenrequest-node)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse-node)
```ts theme={null}
await sdk.api.workspace.ensureWorkspaceAuthToken({});
```
**Response**
```ts theme={null}
{ result: { status: 'success', message: 'Workspace auth token ensured successfully.', data: { authToken: 'eyJhbGciOi...' } } }
```
#### `getAdvancedWebhookConfig`
* Get advanced webhook config.
* Params: [GetAdvancedWebhookConfigRequest](/docs/api-reference/sdk/models/data-models#getadvancedwebhookconfigrequest-node)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse-node)
```ts theme={null}
await sdk.api.workspace.getAdvancedWebhookConfig({});
```
**Response**
```ts theme={null}
{ result: { status: 'success', message: 'Advanced webhook config retrieved successfully.', data: {} } }
```
#### `updateAdvancedWebhookConfig`
* Update advanced webhook config.
* Params: [UpdateAdvancedWebhookConfigRequest](/docs/api-reference/sdk/models/data-models#updateadvancedwebhookconfigrequest-node)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse-node)
```ts theme={null}
await sdk.api.workspace.updateAdvancedWebhookConfig({ isEnabled: true });
```
**Response**
```ts theme={null}
{ result: { status: 'success', message: 'Advanced webhook config updated successfully.', data: {} } }
```
#### `getAdvancedWebhookEndpoints`
* List advanced webhook endpoints (paged).
* Params: [GetAdvancedWebhookEndpointsRequest](/docs/api-reference/sdk/models/data-models#getadvancedwebhookendpointsrequest-node)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse-node)
```ts theme={null}
await sdk.api.workspace.getAdvancedWebhookEndpoints({});
```
**Response**
```ts theme={null}
{
result: {
status: 'success',
message: 'Advanced webhook endpoints retrieved successfully.',
data: [{ id: 'endpoint-1', url: 'https://example.com/webhooks/velt' }],
nextPageToken: 'pageToken'
}
}
```
#### `createAdvancedWebhookEndpoint`
* Create an advanced webhook endpoint.
* Params: [CreateAdvancedWebhookEndpointRequest](/docs/api-reference/sdk/models/data-models#createadvancedwebhookendpointrequest-node)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse-node)
```ts theme={null}
await sdk.api.workspace.createAdvancedWebhookEndpoint({ url: 'https://example.com/webhooks/velt', filterTypes: ['comment.added', 'comment.resolved'] });
```
**Response**
```ts theme={null}
{ result: { status: 'success', message: 'Advanced webhook endpoint created successfully.', data: { id: 'endpoint-1' } } }
```
#### `updateAdvancedWebhookEndpoint`
* Update an advanced webhook endpoint.
* Params: [UpdateAdvancedWebhookEndpointRequest](/docs/api-reference/sdk/models/data-models#updateadvancedwebhookendpointrequest-node)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse-node)
```ts theme={null}
await sdk.api.workspace.updateAdvancedWebhookEndpoint({ endpointId: 'endpoint-1', url: 'https://example.com/webhooks/velt-v2' });
```
**Response**
```ts theme={null}
{ result: { status: 'success', message: 'Advanced webhook endpoint updated successfully.', data: {} } }
```
#### `deleteAdvancedWebhookEndpoint`
* Delete an advanced webhook endpoint.
* Params: [DeleteAdvancedWebhookEndpointRequest](/docs/api-reference/sdk/models/data-models#deleteadvancedwebhookendpointrequest-node)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse-node)
```ts theme={null}
await sdk.api.workspace.deleteAdvancedWebhookEndpoint({ endpointId: 'endpoint-1' });
```
**Response**
```ts theme={null}
{ result: { status: 'success', message: 'Advanced webhook endpoint deleted successfully.', data: {} } }
```
#### `getAdvancedWebhookEndpointSecret`
* Get an endpoint's signing secret.
* Params: [GetAdvancedWebhookEndpointSecretRequest](/docs/api-reference/sdk/models/data-models#getadvancedwebhookendpointsecretrequest-node)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse-node)
```ts theme={null}
await sdk.api.workspace.getAdvancedWebhookEndpointSecret({ endpointId: 'endpoint-1' });
```
**Response**
```ts theme={null}
{ result: { status: 'success', message: 'Endpoint secret retrieved successfully.', data: { secret: 'whsec_...' } } }
```
> [!NOTE]
>
> Custom agent config supports the `rest-api` context-gathering strategy and the `mcp-tools` execution strategy. Secret-bearing REST API and MCP auth fields are encrypted at rest and redacted on read paths. Create and update-version payloads reject server-managed fields such as `managedBy`, `metadata.type`, `metadata.category`, `metadata.internal`, and `metadata.apiKey`; strategies that require instructions (`ai`, `service+ai`, `stagehand-agent`) reject empty `instructions`.
### Approval Workflows
**Namespace:** `sdk.api.approval`
A new service for defining approval/review workflows (graphs of agent, human, webhook, and notification nodes) and dispatching/resolving their executions and steps. 14 methods (routes live under `/v2/workflow/*`). Every type is `Approval`-prefixed. `ApprovalService` is also exported directly from `@veltdev/node`.
#### Routing and loops
Routing is expressed entirely as edges. Each edge carries a semantic `on` role — `'approve'`, `'reject'`, `'custom'` (with a `when` predicate), or `'exhausted'` — and endpoints may be a bare node ID or an object targeting a node or a parallel group.
Loops are edges too: an `on: 'reject'` back-edge carrying a `loop` object sends work back for rework with an iteration cap.
```ts theme={null}
edges: [
{ from: 'draft', to: 'review', on: 'approve' },
// Send rejected work back to 'draft', at most 3 times.
{ from: 'review', to: 'draft', on: 'reject', loop: { maxIterations: 3 } },
// Fan out from a node into a parallel group on a custom predicate.
{
from: { kind: 'node', nodeId: 'review' },
to: { kind: 'group', groupId: 'legal-and-brand' },
on: 'custom',
when: "output.decision == 'escalate'",
},
]
```
#### Notification nodes
A `notification` node sends a formatted email or Slack message built from upstream step output.
```ts theme={null}
nodes: [
{
nodeId: 'notify-ops',
type: 'notification',
config: {
channel: 'slack',
slackTarget: 'C0123456', // channel ID or an incoming-webhook URL
bodyTemplate: 'Review completed for {{document.title}}',
format: 'slack-blocks',
},
},
]
```
`recipients` is required when `channel` is `'email'`; `slackTarget` is required when it is `'slack'`. `format` accepts `'text'`, `'html'`, or `'slack-blocks'` — the last is valid only for Slack.
#### Triggers
A trigger starts an execution. Each trigger drives **at most one** mechanism — `inboundWebhook`, `schedule`, and `appTrigger` are mutually exclusive, and the API rejects a trigger that combines them.
```ts theme={null}
triggers: [
// Run on a cron schedule, in a named IANA timezone.
{
triggerId: 'weekly-audit',
schedule: { cron: '0 9 * * 1', timezone: 'America/New_York', enabled: true },
},
// Start from a connected GitHub App or Vercel Integration.
{
triggerId: 'deploy-gate',
appTrigger: {
provider: 'github',
installationRef: '41234567',
repoFilter: ['acme/web', 'acme/api'],
allowedEvents: ['workflow_run'],
// Fire only when ALL payload filters match.
payloadFilters: [
{ path: 'workflow_run.name', in: ['deploy'] },
{ path: 'workflow_run.conclusion', in: ['success'] },
],
},
},
]
```
An `appTrigger` carries no secret — the connected app is authenticated at the app-level webhook. `payloadFilters` resolve dot-paths against the provider's raw webhook body, so you can gate on a specific workflow name plus its conclusion.
#### `createDefinition`
* Create a workflow definition (nodes, edges, groups, triggers).
* Params: [ApprovalCreateDefinitionRequest](/docs/api-reference/sdk/models/data-models#approvalcreatedefinitionrequest-node)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse-node)
```ts theme={null}
await sdk.api.approval.createDefinition({
definitionId: 'doc-publish-review',
name: 'Document Publish Review',
scope: { level: 'organization', organizationId: 'org-123' },
nodes: [
{ nodeId: 'review', type: 'human', config: { reviewers: [{ userId: 'user-1', mandatory: true }], commentBody: 'Please review before publishing.' } },
{ nodeId: 'rework', type: 'agent', config: { agentId: '__mock__', urlPath: 'documentUrl' } },
],
edges: [{ from: 'review', to: 'rework', on: 'reject' }],
});
```
#### `updateDefinition`
* Update a definition (create shape + optimistic `ifVersion`).
* Params: [ApprovalUpdateDefinitionRequest](/docs/api-reference/sdk/models/data-models#approvalupdatedefinitionrequest-node)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse-node)
```ts theme={null}
await sdk.api.approval.updateDefinition({
definitionId: 'doc-publish-review',
name: 'Document Publish Review v2',
nodes: [
{ nodeId: 'review', type: 'human', config: { reviewers: [{ userId: 'user-1', mandatory: true }], commentBody: 'Please review before publishing.' } },
{ nodeId: 'rework', type: 'agent', config: { agentId: '__mock__', urlPath: 'documentUrl' } },
],
edges: [{ from: 'review', to: 'rework', on: 'reject' }],
ifVersion: 1,
});
```
#### `deleteDefinition`
* Delete a definition.
* Params: [ApprovalDeleteDefinitionRequest](/docs/api-reference/sdk/models/data-models#approvaldeletedefinitionrequest-node)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse-node)
```ts theme={null}
await sdk.api.approval.deleteDefinition({ definitionId: 'doc-publish-review' });
// Hard-delete the definition document and its version snapshots.
await sdk.api.approval.deleteDefinition({ definitionId: 'doc-publish-review', purge: true });
```
By default a delete leaves a tombstone. `purge: true` removes the definition and its version snapshots outright. Both paths free the definition ID for re-creation, and the response echoes `purged` so you can tell which ran.
#### `getDefinition`
* Get a single definition.
* Params: [ApprovalGetDefinitionRequest](/docs/api-reference/sdk/models/data-models#approvalgetdefinitionrequest-node)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse-node)
```ts theme={null}
await sdk.api.approval.getDefinition({ definitionId: 'doc-publish-review' });
```
#### `listDefinitions`
* List definitions (paged).
* Params: [ApprovalListDefinitionsRequest](/docs/api-reference/sdk/models/data-models#approvallistdefinitionsrequest-node)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse-node)
```ts theme={null}
await sdk.api.approval.listDefinitions({});
```
#### `dispatchExecution`
* Dispatch (start) an execution of a definition.
* Params: [ApprovalDispatchExecutionRequest](/docs/api-reference/sdk/models/data-models#approvaldispatchexecutionrequest-node)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse-node)
```ts theme={null}
const exec = await sdk.api.approval.dispatchExecution({ definitionId: 'doc-publish-review', organizationId: 'org-123', documentId: 'doc-1' });
```
#### `cancelExecution`
* Cancel a running execution.
* Params: [ApprovalCancelExecutionRequest](/docs/api-reference/sdk/models/data-models#approvalcancelexecutionrequest-node)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse-node)
```ts theme={null}
await sdk.api.approval.cancelExecution({ executionId: 'exec-1' });
```
#### `getExecution`
* Get a single execution.
* Params: [ApprovalGetExecutionRequest](/docs/api-reference/sdk/models/data-models#approvalgetexecutionrequest-node)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse-node)
```ts theme={null}
await sdk.api.approval.getExecution({ executionId: 'exec-1' });
```
#### `getExecutionEvents`
* Get a page of an execution's lifecycle events.
* Params: [ApprovalGetExecutionEventsRequest](/docs/api-reference/sdk/models/data-models#approvalgetexecutioneventsrequest-node)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse-node)
```ts theme={null}
await sdk.api.approval.getExecutionEvents({ executionId: 'exec-1' });
```
#### `listExecutions`
* List executions.
* Params: [ApprovalListExecutionsRequest](/docs/api-reference/sdk/models/data-models#approvallistexecutionsrequest-node)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse-node)
```ts theme={null}
await sdk.api.approval.listExecutions({});
```
#### `cancelStep`
* Admin step-level cancel.
* Params: [ApprovalCancelStepRequest](/docs/api-reference/sdk/models/data-models#approvalcancelsteprequest-node)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse-node)
```ts theme={null}
await sdk.api.approval.cancelStep({ executionId: 'exec-1', stepId: 'review', actorId: 'user-1' });
```
#### `resolveStep`
* Admin force-resolve a hung step.
* Params: [ApprovalResolveStepRequest](/docs/api-reference/sdk/models/data-models#approvalresolvesteprequest-node)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse-node)
```ts theme={null}
await sdk.api.approval.resolveStep({ executionId: 'exec-1', stepId: 'review', action: 'force-approve', actorId: 'user-1' });
```
#### `recordAgentResolution`
* Record one resolution against a blocking-agent step's aggregator.
* Params: [ApprovalRecordAgentResolutionRequest](/docs/api-reference/sdk/models/data-models#approvalrecordagentresolutionrequest-node)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse-node)
```ts theme={null}
await sdk.api.approval.recordAgentResolution({ executionId: 'exec-1', stepId: 'review', responseId: 'resp-1', resolution: 'resolved', actorId: 'user-1' });
```
#### `recordReviewerDecision`
* Record one reviewer's decision against a human step's aggregator.
* Params: [ApprovalRecordReviewerDecisionRequest](/docs/api-reference/sdk/models/data-models#approvalrecordreviewerdecisionrequest-node)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse-node)
```ts theme={null}
await sdk.api.approval.recordReviewerDecision({ executionId: 'exec-1', stepId: 'review', reviewerId: 'user-1', decision: 'approve' });
```
#### Node & Graph Types
These node/graph/config interfaces are referenced by the request types above. They are not standalone data-model entries.
```ts theme={null}
type JsonAst = Record;
interface ApprovalScope { level: 'apiKey' | 'organization' | 'document'; organizationId?: string; documentId?: string; }
interface ApprovalAgentResolutionPolicy { kind: 'allResolved' | 'minResolved'; minCount?: number; } // minCount req. when 'minResolved' (1..500)
interface ApprovalAgentNodeConfig { agentId: string; urlPath: string; /* 1..500 */ crossPageExecute?: boolean; maxUrlsToProcess?: number; /* positive int, max 500 */ userContextMapping?: Record; pollIntervalMs?: number; /* 5000..60000 */ promptOverride?: string; /* max 8000 */ inputMapping?: Record; requireNonEmptyOutput?: boolean; agentMaxRuntimeMs?: number; /* positive int, max 24h */ blocking?: boolean; resolutionPolicy?: ApprovalAgentResolutionPolicy; /* required when blocking */ }
interface ApprovalHumanReviewer { userId: string; mandatory: boolean; }
interface ApprovalHumanNodeConfig { reviewerIds?: string[]; /* mutually exclusive with reviewers; 1..50 */ reviewers?: ApprovalHumanReviewer[]; /* unique userIds; >=1 mandatory; 1..50 */ reviewerEmails?: string[]; /* max 50 */ commentBody?: string; /* max 8000 */ } // reject path is an outgoing on:'reject' edge
interface ApprovalWebhookNodeConfig { url: string; /* https, allowed host, max 2000 */ method?: 'GET' | 'POST'; mode?: 'sync' | 'async'; authMode?: 'hmac' | 'token' | 'none'; authTokenHeader?: string; /* required when authMode === 'token'; max 500 */ timeoutMs?: number; /* 1000..60000 */ expectedStatusCodes?: number[]; /* each 100..599; max 20 */ bodyTemplate?: 'envelope' | 'pass-through' | 'none'; /* 'none' requires method GET */ requestHeaders?: Record; /* reserved/x-velt-* headers rejected; values max 2000 */ }
interface ApprovalAgentNode { nodeId: string; type: 'agent'; config: ApprovalAgentNodeConfig; slaMs?: number; requireNonEmptyOutput?: boolean; name?: string; /* 1..200 */ description?: string; /* max 2000 */ }
interface ApprovalHumanNode { nodeId: string; type: 'human'; config: ApprovalHumanNodeConfig; slaMs?: number; requireNonEmptyOutput?: boolean; name?: string; /* 1..200 */ description?: string; /* max 2000 */ }
interface ApprovalWebhookNode { nodeId: string; type: 'webhook'; config: ApprovalWebhookNodeConfig; slaMs?: number; requireNonEmptyOutput?: boolean; name?: string; /* 1..200 */ description?: string; /* max 2000 */ }
type ApprovalNode = ApprovalAgentNode | ApprovalHumanNode | ApprovalWebhookNode;
type ApprovalEdgeEndpoint = string | { kind: 'node'; nodeId: string } | { kind: 'group'; groupId: string };
interface ApprovalEdge { from: ApprovalEdgeEndpoint; to: ApprovalEdgeEndpoint; on?: 'approve' | 'reject' | 'always' | 'exhausted' | 'custom'; /* default 'always' */ when?: string; /* JSON-AST; only valid when on==='custom' */ loop?: { maxIterations: number /* 1..20 */ }; /* only on an on:'reject' back-edge */ }
type ApprovalQuorumPolicy = 'waitAll' | 'cancelOnQuorum' | 'joinOnQuorum';
interface ApprovalGroup { groupId: string; /* 1..64 */ memberNodeIds: string[]; /* 1..500 */ expectedSteps: number; /* 1..500 */ quorum: number; /* 1..500 */ onQuorumMet?: ApprovalQuorumPolicy; requiredNodeIds?: string[]; /* max 500 */ }
interface ApprovalCompiledForwardEdge { from: string; to: string; role: 'approve' | 'reject' | 'always' | 'exhausted' | 'custom'; when: JsonAst | null; fromGroupId?: string; toGroupId?: string; }
interface ApprovalCompiledLoop { loopId: string; entryNodeId: string; bodyNodeIds: string[]; maxIterations: number; onExhausted: { routeToNodeId: string } | null; }
interface ApprovalCompiledGraph { forwardEdges: ApprovalCompiledForwardEdge[]; loops: ApprovalCompiledLoop[]; } // read-only on DefinitionView responses
interface ApprovalInboundWebhookTrigger { authMode: 'hmac' | 'bearer'; secret: string; /* 16..512 */ idempotencyHeader?: string; /* 1..128 */ idempotencyBodyPath?: string; /* 1..256 */ payloadMapping?: 'pass-through' | 'wrap'; }
interface ApprovalTrigger { triggerId: string; /* 1..128 */ eventName?: string; /* max 128 */ filters?: Record; inboundWebhook?: ApprovalInboundWebhookTrigger; }
interface ApprovalWebhookConfig { url: string; secret: string; eventTypes?: string[]; } // url https/max2000; secret 16..512; eventTypes each 1..128, max 50
```
## Error Handling
The SDK exports five typed error classes:
| Class | Extends | When thrown |
| - | - | - |
| `VeltSDKError` | `Error` | Base class for all SDK errors |
| `VeltDatabaseError` | `VeltSDKError` | Database connection or query failures |
| `VeltValidationError` | `VeltSDKError` | Missing or invalid request parameters |
| `VeltTokenError` | `VeltSDKError` | Token generation failures |
| `VeltApiError` | `VeltSDKError` | Network or parse failures while calling the REST API. The SDK returns API-level errors as `{ error }` on the response instead of throwing them (see [Response Envelope](/docs/backend-sdks/node#response-envelope)) |
```ts theme={null}
import { VeltSDK, VeltDatabaseError, VeltApiError } from '@veltdev/node';
try {
const result = await sdk.api.organizations.getOrganizations({ organizationIds: ['org-123'] });
} catch (err) {
if (err instanceof VeltApiError) {
console.error('API call failed:', err.message);
} else if (err instanceof VeltDatabaseError) {
console.error('Database error:', err.message);
} else {
throw err;
}
}
```
Common self-hosting error codes returned in the response `errorCode` field:
* `INVALID_INPUT` — Request data is malformed or missing required fields
* `INTERNAL_ERROR` — Server-side error during processing
* `NOT_FOUND` — Requested resource was not found
## Data Models
Key interfaces and serializer helpers exported from `@veltdev/node`. All symbols are available at the package top level:
```ts theme={null}
import {
PartialCommentAnnotation, partialCommentAnnotationFromDict, partialCommentAnnotationToDict,
PartialTargetTextRange, partialTargetTextRangeFromDict, partialTargetTextRangeToDict,
PartialComment, partialCommentFromDict, partialCommentToDict,
BaseMetadata, baseMetadataFromDict, baseMetadataToDict,
} from '@veltdev/node';
```
> [!NOTE]
>
> `PartialUser` and `PartialAttachment` referenced in the interfaces below are minimal pass-through shapes. `PartialUser` is `{ userId: string }` (any additional fields the frontend sends are preserved but not strongly typed). Full user/attachment shapes are documented in the central [Data Models reference](/docs/api-reference/sdk/models/data-models#partialuser).
### PartialCommentAnnotation
Represents a single comment annotation thread. Used as the payload shape when reading or writing annotation data in self-hosting event handlers.
```ts theme={null}
interface PartialCommentAnnotation {
annotationId: string;
metadata?: BaseMetadata;
comments?: Record;
from?: PartialUser; // Typed in v1.0.2; previously pass-through
assignedTo?: PartialUser; // Typed in v1.0.2; previously pass-through
targetTextRange?: PartialTargetTextRange; // Typed in v1.0.2; previously pass-through
resolvedByUserId?: string | null; // Three-state — see resolvedByUserId Semantics below
context?: { textEditorConfig?: { text?: string } }; // TipTap anchor text from client 6.0.17+, stored unchanged
[key: string]: unknown; // Unknown keys are preserved on round-trip
}
```
| Field | Type | Notes |
| - | - | - |
| `annotationId` | `string` | Required. Stable identifier for the annotation thread. |
| `metadata` | `BaseMetadata` | Optional context (document, org, API key). |
| `comments` | `Record` | Keyed by `commentId` string. |
| `from` | `PartialUser` | User who created the annotation. |
| `assignedTo` | `PartialUser` | User currently assigned to the annotation. |
| `targetTextRange` | `PartialTargetTextRange` | Text selection the annotation is anchored to. |
| `resolvedByUserId` | `string \| null` | Three-state field — see below. |
| `context` | `object` | Typed since 2.0.2. Velt client 6.0.17+ sends the TipTap anchor text as `context.textEditorConfig.text`; the SDK stores and returns the object unchanged. |
| `[key]` | `unknown` | Extra keys pass through serialization unchanged. |
**Serializers:**
```ts theme={null}
declare function partialCommentAnnotationFromDict(data: Record): PartialCommentAnnotation;
declare function partialCommentAnnotationToDict(annotation: PartialCommentAnnotation): Record;
```
### PartialTargetTextRange
The text selection an annotation is anchored to. New interface in v1.0.2.
```ts theme={null}
interface PartialTargetTextRange {
text: string;
}
```
| Field | Type | Notes |
| - | - | - |
| `text` | `string` | Required. The selected text content the annotation references. |
**Serializers:**
```ts theme={null}
declare function partialTargetTextRangeFromDict(data: Record): PartialTargetTextRange;
declare function partialTargetTextRangeToDict(range: PartialTargetTextRange): Record;
```
### resolvedByUserId Semantics
`resolvedByUserId` on `PartialCommentAnnotation` is a three-state field. TypeScript has no sentinel value, so the three states map to property presence and value:
| State | Representation | Meaning |
| - | - | - |
| **Absent** | Property not set on the object | No resolution information — do not write to the database |
| **Explicit `null`** | `resolvedByUserId: null` | Annotation was un-resolved (cleared) |
| **String** | `resolvedByUserId: "user-123"` | Resolved by the user with this ID |
Use `Object.hasOwn` (or `'resolvedByUserId' in annotation`) to distinguish absent from explicit `null`:
```ts theme={null}
const annotation = partialCommentAnnotationFromDict(payload);
if (!Object.hasOwn(annotation, 'resolvedByUserId')) {
// Field absent — skip; do not overwrite existing resolution state
} else if (annotation.resolvedByUserId === null) {
// Explicit null — un-resolve the annotation
} else {
// String — mark resolved by annotation.resolvedByUserId
}
```
### PartialComment
A single comment within an annotation thread. Round-trip serializers preserve unknown keys, so custom fields added by your application are not dropped.
```ts theme={null}
interface PartialComment {
commentId: string | number;
commentHtml?: string;
commentText?: string;
attachments?: Record;
from?: PartialUser;
to?: PartialUser[];
taggedUserContacts?: PartialTaggedUserContacts[];
[key: string]: unknown; // Pass-through for unknown keys
}
```
| Field | Type | Notes |
| - | - | - |
| `commentId` | `string \| number` | Required. Unique within the annotation. |
| `commentHtml` | `string` | Raw HTML body of the comment. |
| `commentText` | `string` | Plain-text body, used for search and notifications. |
| `attachments` | `Record` | Keyed by attachment ID. |
| `from` | `PartialUser` | Author of the comment. |
| `to` | `PartialUser[]` | Explicit recipients (direct-mention replies). |
| `taggedUserContacts` | `PartialTaggedUserContacts[]` | Users @-mentioned in the comment body. |
| `[key]` | `unknown` | Extra keys pass through serialization unchanged. |
**Serializers (new in v1.0.2):**
```ts theme={null}
declare function partialCommentFromDict(data: Record): PartialComment;
declare function partialCommentToDict(comment: PartialComment): Record;
```
### BaseMetadata
Contextual identifiers attached to annotations and events. Provides both Velt-internal IDs and your application's client-facing IDs for the same resources.
```ts theme={null}
interface BaseMetadata {
apiKey?: string;
documentId?: string;
clientDocumentId?: string;
organizationId?: string;
clientOrganizationId?: string;
folderId?: string;
veltFolderId?: string;
documentMetadata?: Record;
sdkVersion?: string | null; // New in v1.0.2
}
```
| Field | Type | Notes |
| - | - | - |
| `apiKey` | `string` | Velt project API key. |
| `documentId` | `string` | Velt-internal document identifier. |
| `clientDocumentId` | `string` | Your application's document identifier. |
| `organizationId` | `string` | Velt-internal organization identifier. |
| `clientOrganizationId` | `string` | Your application's organization identifier. |
| `folderId` | `string` | Your application's folder identifier. |
| `veltFolderId` | `string` | Velt-internal folder identifier. |
| `documentMetadata` | `Record` | Arbitrary key-value metadata attached to the document. |
| `sdkVersion` | `string \| null` | SDK version string. `null` means version is known to be absent. New in v1.0.2. |
**Serializers (exposed on public surface in v1.0.2):**
```ts theme={null}
declare function baseMetadataFromDict(data: Record): BaseMetadata;
declare function baseMetadataToDict(meta: BaseMetadata): Record;
```
## Distribution
The package ships both CommonJS (CJS) and ES Module (ESM) bundles with rolled-up `.d.ts` type definitions, making it compatible with all modern Node.js project setups.
```ts theme={null}
// ESM
import { VeltSDK } from '@veltdev/node';
// CommonJS
const { VeltSDK } = require('@veltdev/node');
```
# Python SDK for self-hosting and REST API calls
Source: https://velt.dev/docs/backend-sdks/python
Integrate the Velt Python SDK to self-host backend data with MongoDB or PostgreSQL and S3, or call Velt's REST APIs directly without managing a database.
## Overview
The [Velt Python SDK](https://pypi.org/project/velt-py) exposes two independent backends:
| Backend | Namespace | Use case |
| - | - | - |
| Self-hosting | `sdk.selfHosting.*` | Store Velt data in your own MongoDB or PostgreSQL, plus AWS S3 for attachments |
| REST API | `sdk.api.*` | Call Velt's REST APIs directly — no database required |
**Self-hosting backend** (`sdk.selfHosting.*`) simplifies backend implementation by **90%**. Instead of writing custom database queries and storage logic, you:
1. Pass your DB and storage configs to the SDK
2. Pass the raw request object directly to SDK methods
3. Return the resulting response object straight to the client
**REST API backend** (`sdk.api.*`) provides parity with [Velt's REST APIs](/docs/api-reference/rest-apis/v2/organizations/get-organizations-v2). 19 services, typed `@dataclass` request objects, and raw Velt API responses. No database or AWS configuration needed.
## Installation
Install the extra for the database you self-host on. The core package carries no database driver.
```bash theme={null}
pip install velt-py # REST API backend only
pip install 'velt-py[mongodb]' # + self-hosting on MongoDB
pip install 'velt-py[postgres]' # + self-hosting on PostgreSQL
```
A `database` config whose driver is not installed fails at `initialize()` with the exact command to run, for example `MongoDB support requires: pip install "velt-py[mongodb]"`.
> [!WARNING]
>
> **Upgrading from 0.1.x:** versions before 0.2.0 installed `pymongo` with `pip install velt-py`. From 0.2.0, change `velt-py` to `velt-py[mongodb]` in your requirements. Environments upgraded in place keep working; rebuilt environments need the extra. `mongoengine` and `blinker` are no longer installed either; declare them yourself if your application uses them.
### Requirements
* Python 3.8+
* Django 4.2.26+ (only if using the self-hosting backend)
* For self-hosting, one of:
* MongoDB 6+ (Percona Server or MongoDB Atlas) via `velt-py[mongodb]`
* PostgreSQL 14+ via `velt-py[postgres]`
* `requests` for REST API calls (installed automatically)
* Optional `velt-py[auth]` extra (PyJWT>=2.8.0, cryptography>=42.0.0) — required only for the built-in JWT/JWKS verifier path of [`verifyToken`](#resolver-token-verification). Install with `pip install 'velt-py[auth]'`. Core install (`pip install velt-py`), the custom-callback verify path, and all non-auth features need no new dependency.
## Quick Start
### Initialize the SDK
> [tab] Self-hosting
>
> Self-hosting initialization (MongoDB or PostgreSQL, plus optional AWS S3):
>
> ```python theme={null}
> from velt_py import VeltSDK
>
> # Initialize with database and AWS config
> config = {
> 'database': {
> # MongoDB (default type)
> 'connection_string': 'mongodb+srv://user:pass@cluster.mongodb.net/velt-db',
>
> # PostgreSQL: set the type and use a PostgreSQL connection string instead
> # 'type': 'postgresql',
> # 'connection_string': 'postgresql://user:pass@host:5432/velt',
> },
> # Optional: AWS S3 config for attachments
> 'aws': {
> 'bucket_name': 'your-bucket',
> 'region': 'us-east-1',
> 'access_key_id': 'YOUR_ACCESS_KEY',
> 'secret_access_key': 'YOUR_SECRET_KEY'
> },
> # Optional: Custom collection names
> 'collections': {
> 'comments': 'comment_annotations',
> 'reactions': 'reaction_annotations',
> 'attachments': 'attachments',
> 'users': 'users'
> },
> # Required for sdk.api.* (including token generation)
> 'apiKey': 'YOUR_VELT_API_KEY',
> 'authToken': 'YOUR_VELT_AUTH_TOKEN'
> }
>
> sdk = VeltSDK.initialize(config)
> ```
> [tab] REST API
>
> REST API-only initialization (no database needed):
>
> ```python theme={null}
> from velt_py import VeltSDK
>
> # Minimal config for REST API backend only
> config = {
> 'apiKey': 'YOUR_VELT_API_KEY',
> 'authToken': 'YOUR_VELT_AUTH_TOKEN'
> }
>
> sdk = VeltSDK.initialize(config)
>
> # All sdk.api.* services are now available
> result = sdk.api.organizations.getOrganizations(...)
> ```
>
> The `database` section is optional when using only `sdk.api.*`. Set `VELT_API_KEY` and `VELT_AUTH_TOKEN` environment variables as an alternative to passing credentials in the config dict.
## Configuration
### Environment Variables
The SDK reads the following environment variables automatically. These can be used instead of (or in addition to) config dict keys.
| Variable | Config key equivalent | Purpose |
| - | - | - |
| `VELT_API_KEY` | `apiKey` | Velt API key for authenticating REST API calls |
| `VELT_AUTH_TOKEN` | `authToken` | Velt auth token for authenticating REST API calls |
| `VELT_WORKSPACE_ID` | — | Default workspace ID for workspace-scoped operations |
| `VELT_WORKSPACE_AUTH_TOKEN` | — | Auth token scoped to a specific workspace |
### Self-Hosting Configuration
> [tab] Database
>
> Configure the database that stores comments, reactions, and user data. `type` selects the backend: `mongodb` (default) or `postgresql`. Every `sdk.selfHosting.*` method behaves the same on both.
>
> ```python MongoDB theme={null}
> config = {
> 'database': {
> # Option 1: Connection string (recommended for MongoDB Atlas)
> 'connection_string': 'mongodb+srv://user:pass@cluster.mongodb.net/velt-db',
>
> # Option 2: Individual components (for local MongoDB or custom setup)
> # 'host': 'localhost:27017',
> # 'username': 'your_username',
> # 'password': 'your_password',
> # 'auth_database': 'admin',
> # 'database_name': 'velt-db'
> }
> }
> ```
>
> ```python PostgreSQL theme={null}
> config = {
> 'database': {
> 'type': 'postgresql',
> # Option 1: Connection string (URI or libpq key/value form)
> 'connection_string': 'postgresql://user:pass@host:5432/velt',
>
> # Option 2: Individual components
> # 'host': 'host:5432',
> # 'username': 'your_username',
> # 'password': 'your_password',
> # 'database_name': 'velt',
>
> # Optional (defaults shown)
> # 'schema': 'public',
> # 'sslmode': 'prefer', # use 'verify-full' with 'sslrootcert' for remote databases
> # 'sslrootcert': None,
> # 'connect_timeout': 10,
> # 'application_name': 'velt-py/',
> # 'pool_min_size': 1,
> # 'pool_max_size': 5,
> # 'pool_timeout': 10,
> # 'manage_schema': True,
> # 'connection_options': {}, # any extra libpq parameter
> }
> }
> ```
>
> `database_name` overrides the database named in `connection_string` on both backends.
>
> **How PostgreSQL storage works**
>
> * One table per collection (`comment_annotations`, `reaction_annotations`, `recorder_annotations`, `notifications`, `activities`, `attachments`, `users`) with a single JSONB `data` column that holds the document, plus expression indexes on the fields the SDK queries. The `collections` option renames these tables.
> * On first connection the SDK creates the schema, tables, and indexes (`manage_schema: True`). The role needs `CREATE` on the schema. Concurrent application starts coordinate through an advisory lock, so they do not race.
> * For locked-down roles set `manage_schema: False` and apply the DDL yourself. Generate it for your exact config and hand it to a migration role:
>
> ```python theme={null}
> from velt_py.config import Config
> from velt_py.database.connection import postgres_schema_sql
>
> print(postgres_schema_sql(Config({'database': {'type': 'postgresql', 'connection_string': 'postgresql://...'}})))
> ```
>
> * `schema` is the PostgreSQL schema that holds the tables. It is unrelated to the `user_schema` option, which maps user fields.
> * The default `sslmode: prefer` encrypts when the server offers TLS but never verifies the certificate. For any database that is not on the same host, set `'sslmode': 'verify-full'` with `'sslrootcert': '/path/to/ca.pem'`.
> * Multi-process servers (gunicorn, uWSGI) open one pool per worker. Under uWSGI enable threads (`--enable-threads`).
> * The SDK does not migrate data between MongoDB and PostgreSQL.
> [tab] AWS (Attachments)
>
> Configure AWS S3 for storing file attachments.
>
> ```python theme={null}
> config = {
> 'aws': {
> 'bucket_name': 'your-bucket-name',
> 'region': 'us-east-1',
> 'access_key_id': 'YOUR_AWS_ACCESS_KEY',
> 'secret_access_key': 'YOUR_AWS_SECRET_KEY'
> }
> }
> ```
> [tab] Collections
>
> Customize collection names for storing Velt data. On PostgreSQL these are the table names.
>
> ```python theme={null}
> config = {
> 'collections': {
> 'comments': 'comment_annotations', # Default: 'comment_annotations'
> 'reactions': 'reaction_annotations', # Default: 'reaction_annotations'
> 'attachments': 'attachments', # Default: 'attachments'
> 'users': 'users' # Default: 'users'
> }
> }
> ```
> [tab] User Schema
>
> Map your user schema fields to Velt's expected fields if your database uses different field names.
>
> ```python theme={null}
> config = {
> 'user_schema': {
> 'userId': 'userId', # Your field name for user ID
> 'name': 'name', # Your field name for display name
> 'photoUrl': 'photoUrl', # Your field name for avatar URL
> 'email': 'email', # Your field name for email
> 'color': 'color', # Your field name for user color
> 'textColor': 'textColor', # Your field name for text color
> 'isAdmin': 'isAdmin', # Your field name for admin flag
> 'initial': 'initial' # Your field name for user initial
> }
> }
> ```
> [tab] Resolver Auth
>
> Optional `resolver_auth` block enabling [`sdk.selfHosting.verifyToken`](#resolver-token-verification). The built-in JWT verifier requires `pip install 'velt-py[auth]'`; the custom `verify` callback needs no new dependency.
>
> ```python theme={null}
> config = {
> 'resolver_auth': {
> # Built-in JWT verifier (HS256 example):
> 'jwt': {
> 'secret': 'your-hmac-secret', # HS* — or for RS*/ES*:
> # 'public_key': '-----BEGIN PUBLIC KEY-----...',
> # 'jwks_url': 'https://your-idp/.well-known/jwks.json',
> 'algorithms': ['HS256'], # REQUIRED allowlist
> 'issuer': 'https://your-idp', # optional, enforced when set
> 'audience': 'velt', # optional, enforced when set
> 'leeway': 30, # optional clock skew (seconds)
> # 'require': ['exp'], # optional: reject tokens missing these claims
> },
> # OR a custom escape hatch (takes priority over `jwt`):
> # 'verify': lambda token, headers: my_decode(token), # return claims dict or None
> }
> }
> ```
>
> See [Resolver Token Verification](#resolver-token-verification) for full detail.
> [tab] Complete Example
>
> Full configuration with database, AWS, collections, and user schema. For PostgreSQL, replace the `database` block with `{'type': 'postgresql', 'connection_string': 'postgresql://user:pass@host:5432/velt'}`.
>
> ```python theme={null}
> from velt_py import VeltSDK
>
> config = {
> 'database': {
> 'connection_string': 'mongodb+srv://user:pass@cluster.mongodb.net/velt-db',
> },
> 'aws': {
> 'bucket_name': 'your-bucket-name',
> 'region': 'us-east-1',
> 'access_key_id': 'YOUR_AWS_ACCESS_KEY',
> 'secret_access_key': 'YOUR_AWS_SECRET_KEY'
> },
> 'collections': {
> 'comments': 'comment_annotations',
> 'reactions': 'reaction_annotations',
> 'attachments': 'attachments',
> 'users': 'users'
> },
> 'user_schema': {
> 'userId': 'userId',
> 'name': 'name',
> 'photoUrl': 'photoUrl',
> 'email': 'email',
> 'color': 'color',
> 'textColor': 'textColor',
> 'isAdmin': 'isAdmin',
> 'initial': 'initial'
> },
> 'apiKey': 'YOUR_VELT_API_KEY',
> 'authToken': 'YOUR_VELT_AUTH_TOKEN'
> }
>
> sdk = VeltSDK.initialize(config)
> ```
## Self-Hosting Backend
The SDK provides methods that accept the raw request from the frontend and return the properly formatted response.
All self-hosting service classes — the `BaseService` base class plus seven resolver services — are importable from `velt_py.services.self_hosting`. As of **v0.1.12**, `RecorderService`, `NotificationService`, and `ActivityService` are also exported — previously they were wired into `SelfHostingBackend` but missing from the package's `__all__`.
```python theme={null}
from velt_py.services.self_hosting import (
BaseService,
CommentService,
ReactionService,
AttachmentService,
RecorderService, # newly exported in v0.1.12
NotificationService, # newly exported in v0.1.12
ActivityService, # newly exported in v0.1.12
UserService,
)
```
### Comments
#### `getComments`
* Fetches comments from your database for a document.
* Params: [GetCommentResolverRequest](/docs/api-reference/sdk/models/data-models#getcommentresolverrequest)
* Returns: [VeltSelfHostingResponse](/docs/api-reference/sdk/models/data-models#veltselfhostingresponse)
```python theme={null}
from velt_py import GetCommentResolverRequest
def get_comments(request):
data = request.json
comment_request = GetCommentResolverRequest.from_dict(data)
result = sdk.selfHosting.comments.getComments(comment_request)
return result
```
**Response**
```python theme={null}
{
'success': True,
'statusCode': 200,
'data': { 'comments': [ ... ] }
}
```
#### `saveComments`
* Saves new or updated comments to your database.
* Params: [SaveCommentResolverRequest](/docs/api-reference/sdk/models/data-models#savecommentresolverrequest)
* Returns: [VeltSelfHostingResponse](/docs/api-reference/sdk/models/data-models#veltselfhostingresponse)
```python theme={null}
from velt_py import SaveCommentResolverRequest
def save_comments(request):
data = request.json
save_request = SaveCommentResolverRequest.from_dict(data)
result = sdk.selfHosting.comments.saveComments(save_request)
return result
```
**Response**
```python theme={null}
{ 'success': True, 'statusCode': 200, 'data': { ... } }
```
> As of **v0.1.14**, when used as a save-resolver handler the inbound `event` may be a `ResolverActions` OR a `CommentResolverSaveEvent` member (or a raw string for forward-compat), and the request may carry `targetComment` (request context only — never persisted). See the [`SaveCommentResolverRequest`](#savecommentresolverrequest) entry under Data Models for these additions.
#### `deleteComment`
* Deletes a comment from your database.
* Params: [DeleteCommentResolverRequest](/docs/api-reference/sdk/models/data-models#deletecommentresolverrequest)
* Returns: [VeltSelfHostingResponse](/docs/api-reference/sdk/models/data-models#veltselfhostingresponse)
```python theme={null}
from velt_py import DeleteCommentResolverRequest
def delete_comment(request):
data = request.json
delete_request = DeleteCommentResolverRequest.from_dict(data)
result = sdk.selfHosting.comments.deleteComment(delete_request)
return result
```
**Response**
```python theme={null}
{ 'success': True, 'statusCode': 200, 'data': { ... } }
```
### Reactions
#### `getReactions`
* Fetches reactions from your database for a document.
* Params: [GetReactionResolverRequest](/docs/api-reference/sdk/models/data-models#getreactionresolverrequest)
* Returns: [VeltSelfHostingResponse](/docs/api-reference/sdk/models/data-models#veltselfhostingresponse)
```python theme={null}
from velt_py import GetReactionResolverRequest
def get_reactions(request):
data = request.json
reaction_request = GetReactionResolverRequest.from_dict(data)
result = sdk.selfHosting.reactions.getReactions(reaction_request)
return result
```
**Response**
```python theme={null}
{
'success': True,
'statusCode': 200,
'data': { 'reactions': [ ... ] }
}
```
#### `saveReactions`
* Saves new or updated reactions to your database.
* Params: [SaveReactionResolverRequest](/docs/api-reference/sdk/models/data-models#savereactionresolverrequest)
* Returns: [VeltSelfHostingResponse](/docs/api-reference/sdk/models/data-models#veltselfhostingresponse)
```python theme={null}
from velt_py import SaveReactionResolverRequest
def save_reactions(request):
data = request.json
save_request = SaveReactionResolverRequest.from_dict(data)
result = sdk.selfHosting.reactions.saveReactions(save_request)
return result
```
**Response**
```python theme={null}
{ 'success': True, 'statusCode': 200, 'data': { ... } }
```
#### `deleteReaction`
* Deletes a reaction from your database.
* Params: [DeleteReactionResolverRequest](/docs/api-reference/sdk/models/data-models#deletereactionresolverrequest)
* Returns: [VeltSelfHostingResponse](/docs/api-reference/sdk/models/data-models#veltselfhostingresponse)
```python theme={null}
from velt_py import DeleteReactionResolverRequest
def delete_reaction(request):
data = request.json
delete_request = DeleteReactionResolverRequest.from_dict(data)
result = sdk.selfHosting.reactions.deleteReaction(delete_request)
return result
```
**Response**
```python theme={null}
{ 'success': True, 'statusCode': 200, 'data': { ... } }
```
### Users
#### `getUsers`
* Fetches users from your database.
* Params: [GetUserResolverRequest](/docs/api-reference/sdk/models/data-models#getuserresolverrequest)
* Returns: [VeltSelfHostingResponse](/docs/api-reference/sdk/models/data-models#veltselfhostingresponse)
```python theme={null}
from velt_py import GetUserResolverRequest
def get_users(request):
data = request.json
user_request = GetUserResolverRequest.from_dict(data)
result = sdk.selfHosting.users.getUsers(user_request)
return result
```
**Response**
```python theme={null}
{
'success': True,
'statusCode': 200,
'data': { 'users': [ { 'userId': 'user-1', 'name': 'John Doe', ... } ] }
}
```
#### `resolveUserIdsByEmail`
* Resolves a list of email addresses to their user IDs. Backs the frontend's anonymous-user data provider.
* Params: `ResolveUserIdsByEmailRequest` (from `velt_py.models.user`)
* Returns: [VeltSelfHostingResponse](/docs/api-reference/sdk/models/data-models#veltselfhostingresponse)
```python theme={null}
from velt_py.models.user import ResolveUserIdsByEmailRequest
def resolve_user_ids_by_email(request):
data = request.json
resolve_request = ResolveUserIdsByEmailRequest.from_dict(data)
result = sdk.selfHosting.users.resolveUserIdsByEmail(resolve_request)
return result
```
The SDK honors custom `user_schema` field mappings. It de-duplicates repeated addresses and drops blank or `None` entries.
**Response**
`data` is a map of email to user ID. Addresses that do not match a user are simply absent from the map:
```python theme={null}
{
'success': True,
'statusCode': 200,
'data': { 'alice@example.com': 'user-1', 'bob@example.com': 'user-2' }
}
```
### Attachments
#### `saveAttachment`
* Uploads an attachment file to S3 and saves the metadata.
* Params: [SaveAttachmentResolverRequest](/docs/api-reference/sdk/models/data-models#saveattachmentresolverrequest)
* Returns: [VeltSelfHostingResponse](/docs/api-reference/sdk/models/data-models#veltselfhostingresponse)
> [tab] Django
>
> ```python theme={null}
> import json
> from django.http import JsonResponse
> from django.views.decorators.csrf import csrf_exempt
> from django.views.decorators.http import require_http_methods
> from velt_py import SaveAttachmentResolverRequest, DeleteAttachmentResolverRequest
> from .velt_sdk import get_velt_sdk
>
> @csrf_exempt
> @require_http_methods(["POST"])
> def save_attachment(request):
> try:
> file = request.FILES.get('file')
> request_json_str = request.POST.get('request')
>
> if not file or not request_json_str:
> return JsonResponse({
> 'success': False,
> 'error': 'File and request JSON are required',
> 'errorCode': 'INVALID_INPUT',
> 'statusCode': 400
> }, status=400)
>
> request_data = json.loads(request_json_str)
> save_request = SaveAttachmentResolverRequest.from_dict(request_data)
>
> sdk = get_velt_sdk()
> result = sdk.selfHosting.attachments.saveAttachment(
> save_request,
> file_data=file.read(),
> file_name=file.name,
> mime_type=file.content_type
> )
> return JsonResponse(result, status=result.get('statusCode', 200))
> except Exception as e:
> return JsonResponse({
> 'success': False,
> 'error': str(e),
> 'errorCode': 'INTERNAL_ERROR',
> 'statusCode': 500
> }, status=500)
> ```
> [tab] Flask
>
> ```python theme={null}
> import json
> from flask import request, jsonify
> from velt_py import SaveAttachmentResolverRequest
>
> @app.route('/api/velt/attachments/save', methods=['POST'])
> def save_attachment():
> try:
> file = request.files.get('file')
> request_json = request.form.get('request')
>
> if not file or not request_json:
> return jsonify({
> 'success': False,
> 'error': 'File and request JSON are required',
> 'errorCode': 'INVALID_INPUT',
> 'statusCode': 400
> }), 400
>
> request_data = json.loads(request_json)
> save_request = SaveAttachmentResolverRequest.from_dict(request_data)
>
> result = sdk.selfHosting.attachments.saveAttachment(
> save_request,
> file_data=file.read(),
> file_name=file.filename,
> mime_type=file.content_type
> )
> return jsonify(result), result.get('statusCode', 200)
> except Exception as e:
> return jsonify({'success': False, 'error': str(e), 'errorCode': 'INTERNAL_ERROR', 'statusCode': 500}), 500
> ```
> [tab] FastAPI
>
> ```python theme={null}
> import json
> from fastapi import Request, UploadFile, File, Form
> from fastapi.responses import JSONResponse
> from velt_py import SaveAttachmentResolverRequest
>
> @app.post('/api/velt/attachments/save')
> async def save_attachment(file: UploadFile = File(...), request: str = Form(...)):
> try:
> request_data = json.loads(request)
> save_request = SaveAttachmentResolverRequest.from_dict(request_data)
>
> file_bytes = await file.read()
> result = sdk.selfHosting.attachments.saveAttachment(
> save_request,
> file_data=file_bytes,
> file_name=file.filename,
> mime_type=file.content_type
> )
> return JSONResponse(content=result, status_code=result.get('statusCode', 200))
> except Exception as e:
> return JSONResponse(content={'success': False, 'error': str(e), 'errorCode': 'INTERNAL_ERROR', 'statusCode': 500}, status_code=500)
> ```
**Response**
```python theme={null}
{ 'success': True, 'statusCode': 200, 'data': { ... } }
```
#### `deleteAttachment`
* Deletes an attachment file from S3 and removes its metadata.
* Params: [DeleteAttachmentResolverRequest](/docs/api-reference/sdk/models/data-models#deleteattachmentresolverrequest)
* Returns: [VeltSelfHostingResponse](/docs/api-reference/sdk/models/data-models#veltselfhostingresponse)
> [tab] Django
>
> ```python theme={null}
> import json
> from django.http import JsonResponse
> from django.views.decorators.csrf import csrf_exempt
> from django.views.decorators.http import require_http_methods
> from velt_py import DeleteAttachmentResolverRequest
> from .velt_sdk import get_velt_sdk
>
> @csrf_exempt
> @require_http_methods(["POST"])
> def delete_attachment(request):
> try:
> data = json.loads(request.body)
> delete_request = DeleteAttachmentResolverRequest.from_dict(data)
> sdk = get_velt_sdk()
> result = sdk.selfHosting.attachments.deleteAttachment(delete_request)
> return JsonResponse(result, status=result.get('statusCode', 200))
> except Exception as e:
> return JsonResponse({
> 'success': False,
> 'error': str(e),
> 'errorCode': 'INTERNAL_ERROR',
> 'statusCode': 500
> }, status=500)
> ```
> [tab] Flask
>
> ```python theme={null}
> from flask import request, jsonify
> from velt_py import DeleteAttachmentResolverRequest
>
> @app.route('/api/velt/attachments/delete', methods=['POST'])
> def delete_attachment():
> try:
> data = request.json
> delete_request = DeleteAttachmentResolverRequest.from_dict(data)
> result = sdk.selfHosting.attachments.deleteAttachment(delete_request)
> return jsonify(result), result.get('statusCode', 200)
> except Exception as e:
> return jsonify({'success': False, 'error': str(e), 'errorCode': 'INTERNAL_ERROR', 'statusCode': 500}), 500
> ```
> [tab] FastAPI
>
> ```python theme={null}
> from fastapi import Request
> from fastapi.responses import JSONResponse
> from velt_py import DeleteAttachmentResolverRequest
>
> @app.post('/api/velt/attachments/delete')
> async def delete_attachment(request: Request):
> try:
> data = await request.json()
> delete_request = DeleteAttachmentResolverRequest.from_dict(data)
> result = sdk.selfHosting.attachments.deleteAttachment(delete_request)
> return JSONResponse(content=result, status_code=result.get('statusCode', 200))
> except Exception as e:
> return JSONResponse(content={'success': False, 'error': str(e), 'errorCode': 'INTERNAL_ERROR', 'statusCode': 500}, status_code=500)
> ```
**Response**
```python theme={null}
{ 'success': True, 'statusCode': 200, 'data': { ... } }
```
### Resolver Token Verification
`sdk.selfHosting.verifyToken(headers=None, token=None, **overrides) -> VerifyTokenResult` authenticates the credential the Velt frontend forwards to your resolver endpoints. New in **v0.1.14**. It is **opt-in** via the `resolver_auth` config block, **framework-agnostic**, and **fail-closed** — it returns a structured [`VerifyTokenResult`](#verifytokenresult) and never raises for a verification outcome. It is **authentication only**: it never consults `apiKey`, `organizationId`, or the resolver database; resolver services keep their own scoping. `result.claims` is informational — assert tenant claims against the resolver payload's `organizationId` yourself if you need tenant isolation.
The built-in JWT/JWKS verifier requires the optional extra: `pip install 'velt-py[auth]'`. The custom-callback (`verify`) path needs no new dependency. Configure `resolver_auth` in the [Resolver Auth config tab](#self-hosting-configuration).
* Params:
* `headers` — Incoming request headers; the token is extracted from the configured header.
* `token` — A raw JWT string, passed directly instead of `headers`.
* `**overrides` — One-off `jwt` / `verify` / `header` / `scheme` that merge over the configured `resolver_auth` without changing global config.
* Returns: [`VerifyTokenResult`](#verifytokenresult) — see the Data Models entry for fields.
```python theme={null}
# In your resolver handler:
result = sdk.selfHosting.verifyToken(headers=request.headers) # or token=''
if not result.verified:
return HttpResponse(status=401) # result.errorCode tells you why
# result.claims holds the decoded payload
sdk.selfHosting.comments.saveComments(SaveCommentResolverRequest.from_dict(data))
```
**Error codes** (`result.errorCode`)
| Code | When |
| - | - |
| `MISSING_TOKEN` | No token found in header / not passed, empty, or wrong scheme. |
| `EXPIRED` | Token `exp` is in the past. |
| `INVALID_SIGNATURE` | Signature did not verify against the resolved key. |
| `CLAIM_MISMATCH` | `issuer`, `audience`, or a `require`d claim failed the check. |
| `ALGORITHM_NOT_ALLOWED` | Token `alg` is not in the configured allowlist. |
| `KEY_RESOLUTION_FAILED` | JWKS fetch / `public_key` / `secret` could not yield a usable key. |
| `VERIFICATION_FAILED` | Generic verification failure not covered above. |
| `NOT_CONFIGURED` | `resolver_auth` is not configured. |
| `DEPENDENCY_MISSING` | Built-in verifier used without the `velt-py[auth]` extra installed. |
**Token extraction**
Extracted from the configured header (default `Authorization`, case-insensitive), stripping the configured scheme prefix (default `Bearer`); or pass `token=''`. Missing, empty, or wrong-scheme credentials → `MISSING_TOKEN`.
**Built-in JWT path — key resolution**
* `jwt.secret` → symmetric HS256/384/512. A PEM string in `secret` is rejected to prevent PEM-as-HMAC forgery.
* `jwt.public_key` → static RSA/EC key for RS\* / ES\*.
* `jwt.jwks_url` → fetched over HTTPS, cached in-process by `(url, kid)`. A fetch failure, non-2xx response, or unresolvable `kid` → `KEY_RESOLUTION_FAILED` without raising.
**Security properties**
* **Fail-closed** — never `verified=True` unless a token was present and fully verified.
* **Algorithm pinning** — the allowlist is always required and passed to PyJWT; `alg=none` is rejected unconditionally even if listed; mixed symmetric + asymmetric allowlists are rejected (HS/RS confusion).
* **HTTPS-only JWKS** — `jwks_url` must be `https://`; a redirect downgrade https→http is rejected; 3xx responses are rejected; cache is scoped by `(url, kid)`, not `kid` alone.
* **No credential leakage** — the token, secret, and claims never appear in error strings or logs.
* **Authentication only** — never consults `apiKey`, `organizationId`, or the resolver database.
**Per-call overrides**
`**overrides` kwargs merge over the configured `resolver_auth`, letting you supply a one-off `jwt`, `verify`, `header`, or `scheme` without mutating global config.
**When `resolver_auth` is not configured**
`verifyToken` returns `verified=False` with `errorCode='NOT_CONFIGURED'`. It does not raise and does not silently pass.
**`ResolverAuthService`**
Newly exported in `velt_py.services.self_hosting.__all__` — the DB-free service backing `verifyToken`. Direct use is optional.
### Framework Examples
> [tab] Django
>
> **SDK Initialization (velt_sdk.py)**
>
> ```python theme={null}
> from django.conf import settings
> from velt_py import VeltSDK
>
> _velt_sdk = None
>
> def get_velt_sdk():
> global _velt_sdk
> if _velt_sdk is None:
> _velt_sdk = VeltSDK.initialize(settings.VELT_SDK_CONFIG)
> return _velt_sdk
> ```
>
> **API Endpoints (views.py)**
>
> ```python theme={null}
> import json
> from django.http import JsonResponse
> from django.views.decorators.csrf import csrf_exempt
> from django.views.decorators.http import require_http_methods
> from velt_py import GetCommentResolverRequest, SaveCommentResolverRequest, DeleteCommentResolverRequest
> from .velt_sdk import get_velt_sdk
>
> @csrf_exempt
> @require_http_methods(["POST"])
> def get_comments(request):
> try:
> data = json.loads(request.body)
> comment_request = GetCommentResolverRequest.from_dict(data)
> sdk = get_velt_sdk()
> result = sdk.selfHosting.comments.getComments(comment_request)
> return JsonResponse(result, status=result.get('statusCode', 200))
> except Exception as e:
> return JsonResponse({
> 'success': False,
> 'error': str(e),
> 'errorCode': 'INTERNAL_ERROR',
> 'statusCode': 500
> }, status=500)
> ```
>
> **Configuration (settings.py)**
>
> ```python theme={null}
> import os
>
> VELT_SDK_CONFIG = {
> 'database': {
> 'connection_string': os.environ.get('VELT_MONGODB_CONNECTION_STRING'),
> },
> 'aws': {
> 'bucket_name': os.environ.get('AWS_S3_BUCKET'),
> 'region': os.environ.get('AWS_REGION', 'us-east-1'),
> 'access_key_id': os.environ.get('AWS_ACCESS_KEY_ID'),
> 'secret_access_key': os.environ.get('AWS_SECRET_ACCESS_KEY'),
> },
> 'apiKey': os.environ.get('VELT_API_KEY'),
> 'authToken': os.environ.get('VELT_AUTH_TOKEN')
> }
> ```
> [tab] Flask
>
> ```python theme={null}
> from flask import Flask, request, jsonify
> from velt_py import VeltSDK, GetCommentResolverRequest, SaveCommentResolverRequest, DeleteCommentResolverRequest
>
> app = Flask(__name__)
>
> sdk = VeltSDK.initialize({
> 'database': { 'connection_string': 'mongodb+srv://...' }
> })
>
> @app.route('/api/velt/comments/get', methods=['POST'])
> def get_comments():
> data = request.json
> comment_request = GetCommentResolverRequest.from_dict(data)
> result = sdk.selfHosting.comments.getComments(comment_request)
> return jsonify(result), result.get('statusCode', 200)
> ```
> [tab] FastAPI
>
> ```python theme={null}
> from fastapi import FastAPI, Request
> from fastapi.responses import JSONResponse
> from velt_py import VeltSDK, GetCommentResolverRequest
>
> app = FastAPI()
>
> sdk = VeltSDK.initialize({
> 'database': { 'connection_string': 'mongodb+srv://...' }
> })
>
> @app.post('/api/velt/comments/get')
> async def get_comments(request: Request):
> data = await request.json()
> comment_request = GetCommentResolverRequest.from_dict(data)
> result = sdk.selfHosting.comments.getComments(comment_request)
> return JSONResponse(content=result, status_code=result.get('statusCode', 200))
> ```
## REST API Backend
The `sdk.api.*` namespace gives you parity with [Velt's REST APIs](/docs/api-reference/rest-apis/v2/organizations/get-organizations-v2) across 19 services, including token generation with [`sdk.api.accessControl.generateToken`](#generatetoken). Each method takes a typed `@dataclass` request object and returns the raw Velt API response.
You only need `apiKey` and `authToken` — no database or AWS config.
```python theme={null}
from velt_py import VeltSDK
sdk = VeltSDK.initialize({
'apiKey': 'YOUR_VELT_API_KEY',
'authToken': 'YOUR_VELT_AUTH_TOKEN'
})
# All 19 services are accessible under sdk.api.*
# e.g. sdk.api.organizations, sdk.api.documents, sdk.api.workspace,
# sdk.api.workflow ...
```
Every method returns a dict with either a `result` key (success) or an `error` key (failure). See [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse).
### Organizations
#### `addOrganizations`
* Creates one or more organizations.
* Params: [AddOrganizationsRequest](/docs/api-reference/sdk/models/data-models#addorganizationsrequest)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse)
```python theme={null}
from velt_py.models.organization import AddOrganizationsRequest
result = sdk.api.organizations.addOrganizations(
AddOrganizationsRequest(
organizations=[{'organizationId': 'yourOrganizationId', 'organizationName': 'Your Organization Name'}]
)
)
```
**Response**
```python theme={null}
{
'result': {
'status': 'success',
'message': 'Organization(s) added successfully.',
'data': {
'yourOrganizationId': {
'success': True,
'id': '02cf91e5e7a5f4c0b600c84cf248384b',
'message': 'Added Successfully'
}
}
}
}
```
#### `getOrganizations`
* Retrieves organizations by ID, with optional pagination.
* Params: [GetOrganizationsRequest](/docs/api-reference/sdk/models/data-models#getorganizationsrequest)
* Returns: [GetOrganizationsResponse](/docs/api-reference/sdk/models/data-models#getorganizationsresponse)
```python theme={null}
from velt_py.models.organization import GetOrganizationsRequest
result = sdk.api.organizations.getOrganizations(
GetOrganizationsRequest(
organizationIds=['yourOrganizationId'],
pageSize=1000,
pageToken='pageToken'
)
)
```
**Response**
```python theme={null}
{
'result': {
'status': 'success',
'message': 'Organization(s) retrieved successfully.',
'data': [
{
'id': 'yourOrganizationId',
'organizationName': 'Your Organization Name',
'disabled': False
# other metadata fields may be included here
}
# ... more organizations if multiple were retrieved
],
'nextPageToken': 'pageToken'
}
}
```
#### `updateOrganizations`
* Updates properties of one or more organizations.
* Params: [UpdateOrganizationsRequest](/docs/api-reference/sdk/models/data-models#updateorganizationsrequest)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse)
```python theme={null}
from velt_py.models.organization import UpdateOrganizationsRequest
result = sdk.api.organizations.updateOrganizations(
UpdateOrganizationsRequest(
organizations=[{'organizationId': 'yourOrganizationId', 'organizationName': 'Updated Name'}]
)
)
```
**Response**
```python theme={null}
{
'result': {
'status': 'success',
'message': 'Organization(s) updated successfully.',
'data': {
'yourOrganizationId': {
'success': True,
'id': '02cf91e5e7a5f4c0b600c84cf248384b',
'message': 'Updated Successfully'
}
}
}
}
```
#### `deleteOrganizations`
* Deletes one or more organizations.
* Params: [DeleteOrganizationsRequest](/docs/api-reference/sdk/models/data-models#deleteorganizationsrequest)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse)
```python theme={null}
from velt_py.models.organization import DeleteOrganizationsRequest
result = sdk.api.organizations.deleteOrganizations(
DeleteOrganizationsRequest(organizationIds=['yourOrganizationId1', 'yourOrganizationId2'])
)
```
**Response**
```python theme={null}
{
'result': {
'status': 'success',
'message': 'Organization(s) deleted successfully.',
'data': {
'yourOrganizationId1': {
'success': True,
'id': '02cf91e5e7a5f4c0b600c84cf248384b',
'message': 'Deleted Successfully'
},
'yourOrganizationId2': {
'success': False,
'id': '02cf91e5e7a5f4c0b600c84cf248384b',
'message': 'Organization does not exist'
}
}
}
}
```
#### `updateOrganizationDisableState`
* Enables or disables access to one or more organizations.
* Params: [UpdateOrganizationDisableStateRequest](/docs/api-reference/sdk/models/data-models#updateorganizationdisablestaterequest)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse)
```python theme={null}
from velt_py.models.organization import UpdateOrganizationDisableStateRequest
result = sdk.api.organizations.updateOrganizationDisableState(
UpdateOrganizationDisableStateRequest(
organizationIds=['yourOrganizationId1', 'yourOrganizationId2'],
disabled=True
)
)
```
**Response**
```python theme={null}
{
'result': {
'status': 'success',
'message': 'Updated disable state for Organization(s) successfully.',
'data': {
'yourOrganizationId1': {
'success': True,
'id': '02cf91e5e7a5f4c0b600c84cf248384b',
'message': 'Updated disable state for organization Successfully'
},
'yourOrganizationId2': {
'success': False,
'id': '44e0132f4c6b0d453f18df42d2263b4e',
'message': 'Organization does not exist'
}
}
}
}
```
### Folders
#### `addFolder`
* Creates one or more folders inside an organization.
* Params: [AddFolderRequest](/docs/api-reference/sdk/models/data-models#addfolderrequest)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse)
```python theme={null}
from velt_py.models.folder import AddFolderRequest
result = sdk.api.folders.addFolder(
AddFolderRequest(
organizationId='yourOrganizationId',
folders=[{
'folderId': 'yourFolderId',
'folderName': 'yourFolderName',
'parentFolderId': 'yourParentFolderId'
}]
)
)
```
**Response**
```python theme={null}
{
'result': {
'status': 'success',
'message': 'Folder created successfully.',
'data': {
'yourFolderId': {
'success': True,
'id': 'yourFolderId',
'message': 'Folder added.'
}
}
}
}
```
#### `getFolders`
* Retrieves folders within an organization.
* Params: [GetFoldersRequest](/docs/api-reference/sdk/models/data-models#getfoldersrequest)
* Returns: [GetFoldersResponse](/docs/api-reference/sdk/models/data-models#getfoldersresponse)
```python theme={null}
from velt_py.models.folder import GetFoldersRequest
result = sdk.api.folders.getFolders(
GetFoldersRequest(organizationId='yourOrganizationId', folderId='yourFolderId')
)
```
**Response**
```python theme={null}
{
'result': {
'status': 'success',
'message': 'Folders retrieved successfully.',
'data': [
{
'folderId': 'folderId1',
'folderName': 'Folder 1',
'organizationId': 'yourOrganizationId',
'parentFolderId': 'root',
'createdAt': 1738695077691,
'lastUpdated': 1738695077691,
'subFolders': [
{
'folderId': 'childFolderId1',
'folderName': 'Child Folder 1',
'parentFolderId': 'folderId1',
'createdAt': 1738695615706,
'lastUpdated': 1738698727591
}
]
}
]
}
}
```
#### `updateFolder`
* Updates properties of one or more folders.
* Params: [UpdateFolderRequest](/docs/api-reference/sdk/models/data-models#updatefolderrequest)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse)
```python theme={null}
from velt_py.models.folder import UpdateFolderRequest
result = sdk.api.folders.updateFolder(
UpdateFolderRequest(
organizationId='yourOrganizationId',
folders=[{'folderId': 'yourFolderId', 'folderName': 'yourFolderName', 'parentFolderId': 'yourParentFolderId'}]
)
)
```
**Response**
```python theme={null}
{
'result': {
'status': 'success',
'message': 'Folder Updated successfully.',
'data': {
'yourFolderId': {
'success': True,
'id': 'yourFolderId',
'message': 'Folder Updated.'
}
}
}
}
```
#### `deleteFolder`
* Deletes a folder.
* Params: [DeleteFolderRequest](/docs/api-reference/sdk/models/data-models#deletefolderrequest)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse)
```python theme={null}
from velt_py.models.folder import DeleteFolderRequest
result = sdk.api.folders.deleteFolder(
DeleteFolderRequest(organizationId='yourOrganizationId', folderId='yourFolderId')
)
```
**Response**
```python theme={null}
{
'result': {
'status': 'success',
'message': 'Folder deleted successfully.',
'data': { 'yourFolderId': {'success': True} }
}
}
```
#### `updateFolderAccess`
* Updates the access type of one or more folders.
* Params: [UpdateFolderAccessRequest](/docs/api-reference/sdk/models/data-models#updatefolderaccessrequest)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse)
```python theme={null}
from velt_py.models.folder import UpdateFolderAccessRequest
result = sdk.api.folders.updateFolderAccess(
UpdateFolderAccessRequest(
organizationId='yourOrganizationId',
folderIds=['yourFolderId'],
accessType='organizationPrivate'
)
)
```
**Response**
```python theme={null}
{
'result': {
'status': 'success',
'message': 'Updated access for folders successfully.',
'data': {
'yourFolderId': {
'success': True,
'accessType': 'organizationPrivate',
'message': 'Folder access type updated.'
}
}
}
}
```
### Documents
#### `addDocuments`
* Creates one or more documents inside an organization.
* Params: [AddDocumentsRequest](/docs/api-reference/sdk/models/data-models#adddocumentsrequest)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse)
```python theme={null}
from velt_py.models.document import AddDocumentsRequest
result = sdk.api.documents.addDocuments(
AddDocumentsRequest(
organizationId='yourOrganizationId',
documents=[{'documentId': 'yourDocumentId', 'documentName': 'yourDocumentName'}],
createOrganization=True,
folderId='yourFolderId',
createFolder=True
)
)
```
**Response**
```python theme={null}
{
'result': {
'status': 'success',
'message': 'Document(s) added successfully.',
'data': {
'yourDocumentId': {
'success': True,
'id': '8121657101517513',
'message': 'Added Successfully'
}
}
}
}
```
#### `getDocuments`
* Retrieves documents within an organization.
* Params: [GetDocumentsRequest](/docs/api-reference/sdk/models/data-models#getdocumentsrequest)
* Returns: [GetDocumentsResponse](/docs/api-reference/sdk/models/data-models#getdocumentsresponse)
```python theme={null}
from velt_py.models.document import GetDocumentsRequest
result = sdk.api.documents.getDocuments(
GetDocumentsRequest(
organizationId='yourOrganizationId',
documentIds=['yourDocumentId'],
folderId='yourFolderId'
)
)
```
**Response**
```python theme={null}
{
'result': {
'status': 'success',
'message': 'Document(s) retrieved successfully.',
'data': [
{
'documentName': 'yourDocumentName',
'disabled': False,
'accessType': 'public',
'id': 'yourDocumentId'
}
],
'pageToken': 'nextPageToken'
}
}
```
#### `updateDocuments`
* Updates properties of one or more documents.
* Params: [UpdateDocumentsRequest](/docs/api-reference/sdk/models/data-models#updatedocumentsrequest)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse)
```python theme={null}
from velt_py.models.document import UpdateDocumentsRequest
result = sdk.api.documents.updateDocuments(
UpdateDocumentsRequest(
organizationId='yourOrganizationId',
documents=[{'documentId': 'yourDocumentId', 'documentName': 'Updated Name'}]
)
)
```
**Response**
```python theme={null}
{
'result': {
'status': 'success',
'message': 'Document(s) updated successfully.',
'data': {
'yourDocumentId': {
'success': True,
'id': '8121657101517513',
'message': 'Updated Successfully'
}
}
}
}
```
#### `deleteDocuments`
* Deletes one or more documents.
* Params: [DeleteDocumentsRequest](/docs/api-reference/sdk/models/data-models#deletedocumentsrequest)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse)
```python theme={null}
from velt_py.models.document import DeleteDocumentsRequest
result = sdk.api.documents.deleteDocuments(
DeleteDocumentsRequest(
organizationId='yourOrganizationId',
documentIds=['yourDocumentId1', 'yourDocumentId2']
)
)
```
**Response**
```python theme={null}
{
'result': {
'status': 'success',
'message': 'Document(s) deleted successfully.',
'data': {
'yourDocumentId1': {
'success': True,
'id': '6737987049068973',
'message': 'Deleted Successfully'
},
'yourDocumentId2': {
'success': True,
'id': '2131443384150904',
'message': 'Document does not exist'
}
}
}
}
```
#### `moveDocuments`
* Moves documents into a target folder.
* Params: [MoveDocumentsRequest](/docs/api-reference/sdk/models/data-models#movedocumentsrequest)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse)
```python theme={null}
from velt_py.models.document import MoveDocumentsRequest
result = sdk.api.documents.moveDocuments(
MoveDocumentsRequest(
organizationId='yourOrganizationId',
documentIds=['yourDocumentId1', 'yourDocumentId2'],
folderId='target-folder-id'
)
)
```
**Response**
```python theme={null}
{
'result': {
'status': 'success',
'message': 'Documents moved successfully.'
}
}
```
#### `updateDocumentAccess`
* Updates the access type of one or more documents.
* Params: [UpdateDocumentAccessRequest](/docs/api-reference/sdk/models/data-models#updatedocumentaccessrequest)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse)
```python theme={null}
from velt_py.models.document import UpdateDocumentAccessRequest
result = sdk.api.documents.updateDocumentAccess(
UpdateDocumentAccessRequest(
organizationId='yourOrganizationId',
documentIds=['yourDocumentId'],
accessType='organizationPrivate'
)
)
```
**Response**
```python theme={null}
{
'result': {
'status': 'success',
'message': 'Updated access for documents successfully.',
'data': {
'yourDocumentId': {
'success': True,
'accessType': 'organizationPrivate',
'message': 'Document access type updated.'
}
}
}
}
```
#### `updateDocumentDisableState`
* Enables or disables access to one or more documents.
* Params: [UpdateDocumentDisableStateRequest](/docs/api-reference/sdk/models/data-models#updatedocumentdisablestaterequest)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse)
```python theme={null}
from velt_py.models.document import UpdateDocumentDisableStateRequest
result = sdk.api.documents.updateDocumentDisableState(
UpdateDocumentDisableStateRequest(
organizationId='yourOrganizationId',
documentIds=['yourDocumentId'],
disabled=True
)
)
```
**Response**
```python theme={null}
{
'result': {
'status': 'success',
'message': 'Updated disable state for documents successfully.',
'data': {
'yourDocumentId': {
'success': True,
'disabled': True,
'message': 'Document disabled state updated.'
}
}
}
}
```
#### `migrateDocuments`
* Starts a job to migrate a document to a new document ID.
* Params: [MigrateDocumentsRequest](/docs/api-reference/sdk/models/data-models#migratedocumentsrequest)
* Returns: [MigrateDocumentsResponse](/docs/api-reference/sdk/models/data-models#migratedocumentsresponse)
```python theme={null}
from velt_py.models.document import MigrateDocumentsRequest
result = sdk.api.documents.migrateDocuments(
MigrateDocumentsRequest(
organizationId='yourOrganizationId',
documentId='old-doc-id',
newDocumentId='new-doc-id'
)
)
```
**Response**
```python theme={null}
{
'result': {
'status': 'success',
'message': 'Document migration started successfully.',
'data': { 'migrationId': 'yourMigrationId' }
}
}
```
> Note: This call is asynchronous. Poll status via `migrateDocumentsStatus`.
#### `migrateDocumentsStatus`
* Polls the status of a document migration job.
* Params: [MigrateDocumentsStatusRequest](/docs/api-reference/sdk/models/data-models#migratedocumentsstatusrequest)
* Returns: [MigrateDocumentsStatusResponse](/docs/api-reference/sdk/models/data-models#migratedocumentsstatusresponse)
```python theme={null}
from velt_py.models.document import MigrateDocumentsStatusRequest
result = sdk.api.documents.migrateDocumentsStatus(
MigrateDocumentsStatusRequest(
organizationId='yourOrganizationId',
migrationId='yourMigrationId'
)
)
```
**Response**
```python theme={null}
{
'result': {
'status': 'success',
'message': 'Migration status retrieved successfully.',
'data': {
'migrationId': 'yourMigrationId',
'status': 'completed'
}
}
}
```
#### `getDocumentsCount`
* Gets the document count for an organization. Optionally exclude folder docs, scope to a folder, or narrow with metadata `filters`.
* Params: `GetDocumentsCountRequest` (from `velt_py.models.document`)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse)
```python theme={null}
from velt_py.models.document import GetDocumentsCountRequest
result = sdk.api.documents.getDocumentsCount(
GetDocumentsCountRequest(
organizationId='org-123',
excludeFolderDocs=True,
folderId='folder-1'
)
)
# Narrow the count with metadata filters (same shape as getDocuments; max 10).
result = sdk.api.documents.getDocumentsCount(
GetDocumentsCountRequest(
organizationId='org-123',
filters=[
{'key': 'projectType', 'operator': '==', 'value': 'design'},
{'key': 'category', 'operator': 'in', 'value': ['a', 'b']},
]
)
)
```
`filters` cannot be combined with `excludeFolderDocs` — the API rejects the combination. When filters are supplied the response data also carries `filtersApplied`; a `False` value means the filtered aggregate could not be computed and `count` is an unfiltered fallback.
### Users
#### `addUsers`
* Adds one or more users to an organization.
* Params: [AddUsersRequest](/docs/api-reference/sdk/models/data-models#addusersrequest)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse)
```python theme={null}
from velt_py.models.user_api import AddUsersRequest
result = sdk.api.users.addUsers(
AddUsersRequest(
organizationId='yourOrganizationId',
users=[{'userId': 'yourUserId1', 'name': 'John Doe', 'email': 'john@example.com', 'accessRole': 'editor'}],
createOrganization=True
)
)
```
**Response**
```python theme={null}
{
'result': {
'status': 'success',
'message': 'User(s) processed successfully.',
'data': {
'yourUserId1': {
'success': True,
'id': '4c250058149d6c9fb8c894c9ef29c790',
'message': 'User added.'
}
}
}
}
```
#### `getUsers`
* Retrieves users in an organization or document.
* Params: [GetUsersRequest](/docs/api-reference/sdk/models/data-models#getusersrequest)
* Returns: [GetUsersResponse](/docs/api-reference/sdk/models/data-models#getusersresponse)
* Now also supports optional `includeInvolvedDocuments` and `searchKey` (free-text search) filters.
```python theme={null}
from velt_py.models.user_api import GetUsersRequest
result = sdk.api.users.getUsers(
GetUsersRequest(
organizationId='yourOrganizationId',
userIds=['yourUserId'],
documentId='yourDocumentId',
pageSize=100,
allDocuments=True,
groupByDocumentId=True,
includeInvolvedDocuments=True,
searchKey='john'
)
)
```
**Response**
```python theme={null}
{
'result': {
'status': 'success',
'message': 'User(s) retrieved successfully.',
'data': [
{'email': 'userEmail@domain.com', 'name': 'userName', 'userId': 'yourUserId'}
],
'nextPageToken': 'pageToken'
}
}
```
#### `updateUsers`
* Updates metadata for one or more users.
* Params: [UpdateUsersRequest](/docs/api-reference/sdk/models/data-models#updateusersrequest)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse)
```python theme={null}
from velt_py.models.user_api import UpdateUsersRequest
result = sdk.api.users.updateUsers(
UpdateUsersRequest(
organizationId='yourOrganizationId',
users=[{'userId': 'yourUserId1', 'name': 'Jane Doe', 'accessRole': 'viewer'}]
)
)
```
**Response**
```python theme={null}
{
'result': {
'status': 'success',
'message': 'User(s) processed successfully.',
'data': {
'yourUserId1': {
'success': True,
'id': '7d87015b055a168b098cf05b870e40ff',
'message': 'User updated.'
}
}
}
}
```
#### `deleteUsers`
* Removes users from an organization.
* Params: [DeleteUsersRequest](/docs/api-reference/sdk/models/data-models#deleteusersrequest)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse)
```python theme={null}
from velt_py.models.user_api import DeleteUsersRequest
result = sdk.api.users.deleteUsers(
DeleteUsersRequest(
organizationId='yourOrganizationId',
userIds=['yourUserId1', 'yourUserId2']
)
)
```
**Response**
```python theme={null}
{
'result': {
'status': 'success',
'message': 'User(s) deleted successfully.',
'data': {
'yourUserId1': {
'success': True,
'message': 'User removed.'
}
}
}
}
```
#### `getUsersCount`
* Gets the user count for an organization. Optionally scope to a document, a user, or all documents.
* Params: `GetUsersCountRequest` (from `velt_py.models.user_api`)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse)
```python theme={null}
from velt_py.models.user_api import GetUsersCountRequest
result = sdk.api.users.getUsersCount(
GetUsersCountRequest(organizationId='org-123', allDocuments=True, userId='user-1')
)
```
#### `getDocUsers`
* Gets document-level users. Optionally filter by user IDs (max 20; max 5 with `includeInvolvedDocuments`), include involved documents, and paginate.
* Params: `GetDocUsersRequest` (from `velt_py.models.user_api`)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse)
```python theme={null}
from velt_py.models.user_api import GetDocUsersRequest
result = sdk.api.users.getDocUsers(
GetDocUsersRequest(organizationId='org-123', userIds=['user-1'], includeInvolvedDocuments=True, pageSize=100)
)
```
#### `addUserInvite`
* Creates a user invitation (organization, document, or folder).
* Params: `AddUserInviteRequest` (from `velt_py.models.user_api`)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse)
```python theme={null}
from velt_py.models.user_api import AddUserInviteRequest
result = sdk.api.users.addUserInvite(
AddUserInviteRequest(email='invitee@example.com', organizationId='org-123', type='org_user')
)
```
#### `respondToInvite`
* Responds to a user invitation (accept, reject, or withdraw).
* Params: `RespondUserInviteRequest` (from `velt_py.models.user_api`)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse)
```python theme={null}
from velt_py.models.user_api import RespondUserInviteRequest
result = sdk.api.users.respondToInvite(
RespondUserInviteRequest(
email='invitee@example.com', organizationId='org-123', status='ACCEPTED', type='org_user',
user={'userId': 'user-1', 'name': 'Invitee'}, authToken='invited-user-auth-token'
)
)
```
#### `getInvitedUsers`
* Gets invited users for an organization (paginated).
* Params: `GetInvitedUsersRequest` (from `velt_py.models.user_api`)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse)
```python theme={null}
from velt_py.models.user_api import GetInvitedUsersRequest
invited = sdk.api.users.getInvitedUsers(
GetInvitedUsersRequest(organizationId='org-123')
)
```
#### `getUserInvitations`
* Gets invitations for a specific user email (paginated).
* Params: `GetUserInvitationsRequest` (from `velt_py.models.user_api`)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse)
```python theme={null}
from velt_py.models.user_api import GetUserInvitationsRequest
invitations = sdk.api.users.getUserInvitations(
GetUserInvitationsRequest(organizationId='org-123', email='invitee@example.com')
)
```
#### `getInvitedPendingUsersCount`
* Gets the count of pending invited users.
* Params: `GetInvitedPendingUsersCountRequest` (from `velt_py.models.user_api`)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse)
```python theme={null}
from velt_py.models.user_api import GetInvitedPendingUsersCountRequest
pending = sdk.api.users.getInvitedPendingUsersCount(
GetInvitedPendingUsersCountRequest(organizationId='org-123', type='org_user')
)
```
### User Groups
#### `addUserGroups`
* Creates one or more user groups inside an organization.
* Params: [AddUserGroupsRequest](/docs/api-reference/sdk/models/data-models#addusergroupsrequest)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse)
```python theme={null}
from velt_py.models.user_group import AddUserGroupsRequest
result = sdk.api.userGroups.addUserGroups(
AddUserGroupsRequest(
organizationId='yourOrganizationId',
organizationUserGroups=[{'groupId': 'yourGroupId', 'groupName': 'Engineering'}],
createOrganization=True
)
)
```
**Response**
```python theme={null}
{
'result': {
'status': 'success',
'message': 'Organization User Groups added successfully.',
'data': {
'yourGroupId': {
'success': True,
'id': '77ab6767b022ad0323ba39c24f12cc95',
'message': 'Organization user group added.'
}
}
}
}
```
#### `addUsersToGroup`
* Adds users to an existing group.
* Params: [AddUsersToGroupRequest](/docs/api-reference/sdk/models/data-models#adduserstogrouprequest)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse)
```python theme={null}
from velt_py.models.user_group import AddUsersToGroupRequest
result = sdk.api.userGroups.addUsersToGroup(
AddUsersToGroupRequest(
organizationId='yourOrganizationId',
organizationUserGroupId='yourGroupId',
userIds=['yourUserId1', 'yourUserId2']
)
)
```
**Response**
```python theme={null}
{
'result': {
'status': 'success',
'message': 'Added organization users to group successfully.',
'data': {
'yourUserId1': {
'success': True,
'organizationUserGroupId': 'yourGroupId',
'message': 'User added to organization user group.'
}
}
}
}
```
#### `deleteUsersFromGroup`
* Removes users from a group, or empties the group entirely when `deleteAll` is `True`.
* Params: [DeleteUsersFromGroupRequest](/docs/api-reference/sdk/models/data-models#deleteusersfromgrouprequest)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse)
```python theme={null}
from velt_py.models.user_group import DeleteUsersFromGroupRequest
result = sdk.api.userGroups.deleteUsersFromGroup(
DeleteUsersFromGroupRequest(
organizationId='yourOrganizationId',
organizationUserGroupId='yourGroupId',
userIds=['yourUserId1'],
deleteAll=False
)
)
```
**Response**
```python theme={null}
{
'result': {
'status': 'success',
'message': 'Deleted users from group successfully.',
'data': {
'yourUserId1': {
'success': True,
'organizationUserGroupId': 'yourGroupId',
'message': 'User deleted from organization user group.'
}
}
}
}
```
### Notifications
> [!NOTE]
>
> **Filtering unknown fields**: `updateNotifications` accepts an optional `filter_unknown_fields: bool = False` keyword (backed by `velt_py.models.field_allowlists`). When `True`, unknown/custom top-level keys are dropped before the request is sent, while open-typed fields (`context`, `metadata`, `entityData`, user objects) pass through whole. Filtering is fail-open: if it errors, the original payload is sent, so a write is never blocked. `addNotifications` is not affected — its top-level fields are already fixed. On `updateNotifications`, `isRead` / `isArchived` are not accepted by `/v2/notifications/update` (the backend strips them anyway), so with the flag on they are dropped client-side.
#### `addNotifications`
* Sends a notification to one or more users on a document.
* Params: [AddNotificationsRequest](/docs/api-reference/sdk/models/data-models#addnotificationsrequest)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse)
```python theme={null}
from velt_py.models.notification_api import AddNotificationsRequest
result = sdk.api.notifications.addNotifications(
AddNotificationsRequest(
organizationId='yourOrganizationId',
documentId='yourDocumentId',
actionUser={'userId': 'user-1', 'name': 'John Doe', 'email': 'john@example.com'},
displayHeadlineMessageTemplate='{actionUser} commented on your document',
displayBodyMessage='Check out the new comment',
notifyUsers=[{'userId': 'user-2', 'name': 'Jane Doe'}],
createOrganization=True,
createDocument=True
)
)
```
**Response**
```python theme={null}
{
'result': {
'status': 'success',
'message': 'Notification added successfully.',
'data': {
'success': True,
'message': 'Notification added successfully.'
}
}
}
```
#### `getNotifications`
* Retrieves notifications for a user or document.
* Params: [GetNotificationsRequest](/docs/api-reference/sdk/models/data-models#getnotificationsrequest)
* Returns: [GetNotificationsResponse](/docs/api-reference/sdk/models/data-models#getnotificationsresponse)
* Velt filters results by comment visibility: a notification for a private comment is returned only to users who can see that comment.
```python theme={null}
from velt_py.models.notification_api import GetNotificationsRequest
result = sdk.api.notifications.getNotifications(
GetNotificationsRequest(
organizationId='yourOrganizationId',
userId='user-2',
pageSize=10,
order='desc'
)
)
```
**Response**
```python theme={null}
{
'result': {
'status': 'success',
'message': 'Notification(s) retrieved successfully.',
'data': [
{
'id': 'notificationId',
'notificationSource': 'custom',
'notificationSourceData': {},
'actionUser': {'email': 'user@example.com', 'name': 'User Name', 'userId': 'yourUserId'},
'displayBodyMessage': 'This is body message (Secondary message)',
'displayHeadlineMessageTemplate': 'Template with {actionUser}, {recipientUser}, {customVar}',
'displayHeadlineMessageTemplateData': {
'actionUser': {'email': 'user@example.com', 'name': 'User Name', 'userId': 'yourUserId'},
'recipientUser': {'email': 'recipient@example.com', 'name': 'Recipient Name', 'userId': 'recipientUserId'}
},
'metadata': {'apiKey': '...', 'documentId': '...', 'organizationId': '...'},
'notifyUsers': {'yourNotifyUserId': True},
'notifyUsersByUserId': {'yourNotifyUserById': True},
'timestamp': 1722409519944
}
],
'pageToken': 'nextPageToken'
}
}
```
#### `updateNotifications`
* Updates fields on existing notifications (e.g., mark as read).
* Params: [UpdateNotificationsRequest](/docs/api-reference/sdk/models/data-models#updatenotificationsrequest)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse)
* Accepts the optional `filter_unknown_fields=True` keyword (see the note above).
```python theme={null}
from velt_py.models.notification_api import UpdateNotificationsRequest
result = sdk.api.notifications.updateNotifications(
UpdateNotificationsRequest(
organizationId='yourOrganizationId',
notifications={'5471488637912692': {'isRead': True}}
)
)
```
**Response**
```python theme={null}
{
'result': {
'status': 'success',
'message': 'Notification(s) updated successfully.',
'data': {
'5471488637912692': {
'success': True,
'message': 'Notification updated.'
}
}
}
}
```
#### `deleteNotifications`
* Deletes one or more notifications.
* Params: [DeleteNotificationsRequest](/docs/api-reference/sdk/models/data-models#deletenotificationsrequest)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse)
```python theme={null}
from velt_py.models.notification_api import DeleteNotificationsRequest
result = sdk.api.notifications.deleteNotifications(
DeleteNotificationsRequest(
organizationId='yourOrganizationId',
notificationIds=['8955243231506071']
)
)
```
**Response**
```python theme={null}
{
'result': {
'status': 'success',
'message': 'Notification(s) deleted successfully.',
'data': {
'8955243231506071': {
'success': True,
'message': 'Notification deleted.'
}
}
}
}
```
#### `getNotificationConfig`
* Gets notification preferences (inbox/email/slack channels) for a user.
* `userId` is required when `getOrganizationConfig=True`; the API rejects the call with `INVALID_ARGUMENT` if it is missing. For a user-level read, `userId` is optional.
* Params: [GetNotificationConfigRequest](/docs/api-reference/sdk/models/data-models#getnotificationconfigrequest)
* Returns: [GetNotificationConfigResponse](/docs/api-reference/sdk/models/data-models#getnotificationconfigresponse)
```python theme={null}
from velt_py.models.notification_api import GetNotificationConfigRequest
result = sdk.api.notifications.getNotificationConfig(
GetNotificationConfigRequest(
organizationId='org1',
userId='USER_ID1'
)
)
```
**Response**
```python theme={null}
{
'result': {
'status': 'success',
'message': 'User config fetched successfully.',
'data': [
{
'config': {'inbox': 'ALL', 'email': 'ALL'},
'metadata': {
'organizationId': 'org1',
'apiKey': 'API_KEY',
'documentId': 'doc1',
'userId': 'USER_ID1'
}
}
]
}
}
```
#### `setNotificationConfig`
* Sets notification preferences for one or more users.
* Params: [SetNotificationConfigRequest](/docs/api-reference/sdk/models/data-models#setnotificationconfigrequest)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse)
```python theme={null}
from velt_py.models.notification_api import SetNotificationConfigRequest
result = sdk.api.notifications.setNotificationConfig(
SetNotificationConfigRequest(
organizationId='org1',
userIds=['USER_ID1'],
config={'inbox': 'ALL', 'email': 'MINE'}
)
)
```
**Response**
```python theme={null}
{
'result': {
'status': 'success',
'message': 'User config set successfully.',
'data': {
'USER_ID1': {
'success': True,
'userId': 'USER_ID1',
'documentId': 'doc1',
'message': 'User config set successfully.'
}
}
}
}
```
### Comment Annotations
> [!NOTE]
>
> **Filtering unknown fields**: The add/update methods below accept an optional `filter_unknown_fields: bool = False` keyword (backed by `velt_py.models.field_allowlists`). When `True`, request entity collections are filtered to only the fields the Velt API accepts, dropping unknown/custom top-level keys before the request is sent. Open-typed fields (`context`, `metadata`, `entityData`, user objects) pass through whole — their nested contents are never filtered. Filtering is fail-open: if it errors, the original payload is sent, so a write is never blocked.
#### `addCommentAnnotations`
* Creates one or more comment annotations on a document.
* Params: [AddCommentAnnotationsRequest](/docs/api-reference/sdk/models/data-models#addcommentannotationsrequest)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse)
* Accepts the optional `filter_unknown_fields=True` keyword (see the note above).
```python theme={null}
from velt_py.models.comment_annotation_api import AddCommentAnnotationsRequest
result = sdk.api.commentAnnotations.addCommentAnnotations(
AddCommentAnnotationsRequest(
organizationId='yourOrganizationId',
documentId='yourDocumentId',
commentAnnotations=[{
'location': {'id': 'yourLocationId', 'locationName': 'yourLocationName'},
'commentData': [{
'commentText': 'Sample Comment',
'commentHtml': 'Sample Comment
',
'from': {'userId': 'yourUserId', 'name': 'yourUserName', 'email': 'yourUserEmail'}
}]
}]
)
)
```
**Response**
```python theme={null}
{
'result': {
'status': 'success',
'message': 'Comment Annotation(s) added successfully.',
'data': {
'-O0mpUziLcBwzREvZKs6': {
'success': True,
'annotationId': '-O0mpUziLcBwzREvZKs6',
'commentIds': [126535],
'message': 'Added Successfully'
}
}
}
}
```
#### `getCommentAnnotations`
* Retrieves comment annotations on a document.
* Params: [GetCommentAnnotationsRequest](/docs/api-reference/sdk/models/data-models#getcommentannotationsrequest)
* Returns: [GetCommentAnnotationsResponse](/docs/api-reference/sdk/models/data-models#getcommentannotationsresponse)
```python theme={null}
from velt_py.models.comment_annotation_api import GetCommentAnnotationsRequest
result = sdk.api.commentAnnotations.getCommentAnnotations(
GetCommentAnnotationsRequest(
organizationId='yourOrganizationId',
documentId='yourDocumentId',
statusIds=['OPEN'],
pageSize=10
)
)
# Scope a listing to agent-authored annotations. Supply at most one agent filter
# per request: agentId, executionId, agentType, agentSource, agentSuggestions,
# or agentComments.
result = sdk.api.commentAnnotations.getCommentAnnotations(
GetCommentAnnotationsRequest(
organizationId='yourOrganizationId',
documentId='yourDocumentId',
agentSuggestions=True
)
)
```
> [!NOTE]
>
> Agent filtering is annotation-scoped and requires advanced queries to be enabled on your workspace. When they are not enabled, the API fails closed rather than returning unfiltered results.
**Response**
```python theme={null}
{
'result': {
'status': 'success',
'message': 'Annotation(s) fetched successfully.',
'data': [
{
'annotationId': 'yourAnnotationId',
'annotationNumber': 2,
'type': 'comment',
'createdAt': 1777973713421,
'lastUpdated': 1777978714209,
'hasDraftComments': False,
'context': {'access': {'default': 'velt'}, 'accessFields': ['default:velt']},
'visibilityConfig': {'type': 'public'},
'metadata': {'apiKey': '...', 'organizationId': '...', 'documentId': '...'},
'from': {'userId': 'user123', 'name': 'John Doe', 'email': 'john.doe@example.com'},
'comments': [
{
'commentId': 123456,
'commentText': 'This is a sample comment text.',
'commentHtml': 'This is a sample comment text.
',
'createdAt': 1777973714914,
'lastUpdated': '2026-05-05T09:35:15.048Z',
'reactionAnnotationIds': ['reactionAnnotationId1'],
'from': {'userId': 'user123', 'name': 'John Doe'}
}
],
'status': {'id': 'OPEN', 'name': 'Open', 'type': 'default'}
}
],
'nextPageToken': 'pageToken'
}
}
```
#### `getCommentAnnotationsCount`
* Counts total and unread annotations across one or more documents.
* `documentIds` is required (1 to 25 IDs). The API rejects the call with `INVALID_ARGUMENT` when it is omitted.
* Params: [GetCommentAnnotationsCountRequest](/docs/api-reference/sdk/models/data-models#getcommentannotationscountrequest)
* Returns: [GetCommentAnnotationsCountResponse](/docs/api-reference/sdk/models/data-models#getcommentannotationscountresponse)
```python theme={null}
from velt_py.models.comment_annotation_api import GetCommentAnnotationsCountRequest
result = sdk.api.commentAnnotations.getCommentAnnotationsCount(
GetCommentAnnotationsCountRequest(
organizationId='ORG_ID',
documentIds=['DOC_1', 'DOC_2'],
userId='1.1',
statusIds=['OPEN', 'IN_PROGRESS']
)
)
```
**Response**
```python theme={null}
{
'result': {
'status': 'success',
'message': 'Comment count retrieved successfully.',
'data': {
'DOC_1': {'total': 4, 'unread': 2},
'DOC_2': {'total': 2, 'unread': 0}
}
}
}
```
#### `updateCommentAnnotations`
* Updates annotation fields (e.g., change status).
* Params: [UpdateCommentAnnotationsRequest](/docs/api-reference/sdk/models/data-models#updatecommentannotationsrequest)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse)
* Accepts the optional `filter_unknown_fields=True` keyword (see the note above).
```python theme={null}
from velt_py.models.comment_annotation_api import UpdateCommentAnnotationsRequest
result = sdk.api.commentAnnotations.updateCommentAnnotations(
UpdateCommentAnnotationsRequest(
organizationId='yourOrganizationId',
documentId='yourDocumentId',
annotationIds=['yourAnnotationId1'],
updatedData={'status': {'id': 'inprogress', 'name': 'In Progress', 'type': 'ongoing'}}
)
)
```
**Response**
```python theme={null}
{
'result': {
'status': 'success',
'message': 'Annotations updated successfully.',
'data': {
'yourAnnotationId1': {
'success': True,
'id': 'yourAnnotationId1',
'message': 'Annotations updated successfully'
}
}
}
}
```
#### `deleteCommentAnnotations`
* Deletes one or more comment annotations.
* Params: [DeleteCommentAnnotationsRequest](/docs/api-reference/sdk/models/data-models#deletecommentannotationsrequest)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse)
```python theme={null}
from velt_py.models.comment_annotation_api import DeleteCommentAnnotationsRequest
result = sdk.api.commentAnnotations.deleteCommentAnnotations(
DeleteCommentAnnotationsRequest(
organizationId='yourOrganizationId',
documentId='yourDocumentId',
annotationIds=['yourAnnotationId1', 'yourAnnotationId2']
)
)
# Agent filters combine, so you can scope a sweep precisely — for example
# "this agent's still-pending suggestions on these pages", which leaves a
# concurrent crawl's freshly-created annotations untouched.
result = sdk.api.commentAnnotations.deleteCommentAnnotations(
DeleteCommentAnnotationsRequest(
organizationId='yourOrganizationId',
documentId='yourDocumentId',
agentId='agent-7',
agentSuggestions=True,
agentUrls=['https://app.example.com/page-1', 'https://app.example.com/page-2']
)
)
```
`agentUrls` matches annotations scoped to **any** of the supplied pages.
> [!WARNING]
>
> Agent filters require advanced queries to be enabled on your workspace. When they are not enabled — or when none of the supplied `agentUrls` resolve — the API fails closed and deletes nothing, rather than widening to a document-wide delete.
**Response**
```python theme={null}
{
'result': {
'status': 'success',
'message': 'Annotations deleted successfully.',
'data': {
'yourAnnotationId1': {
'success': True,
'id': 'yourAnnotationId',
'message': 'Deleted Successfully'
},
'yourAnnotationId2': {
'success': False,
'id': 'yourAnnotationId2',
'message': 'Annotation not found.'
}
}
}
}
```
#### `addComments`
* Adds reply comments to an existing annotation.
* Params: [AddCommentsRequest](/docs/api-reference/sdk/models/data-models#addcommentsrequest)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse)
* Accepts the optional `filter_unknown_fields=True` keyword (see the note above).
```python theme={null}
from velt_py.models.comment_annotation_api import AddCommentsRequest
result = sdk.api.commentAnnotations.addComments(
AddCommentsRequest(
organizationId='yourOrganizationId',
documentId='yourDocumentId',
annotationId='yourAnnotationId',
commentData=[{
'commentText': 'I agree, let me fix this',
'from': {'userId': 'user-2', 'name': 'Jane Doe'}
}]
)
)
```
**Response**
```python theme={null}
{
'result': {
'status': 'success',
'message': 'Comment(s) added successfully.',
'data': [778115]
}
}
```
#### `getComments`
* Retrieves individual comments inside an annotation.
* Params: [GetCommentsRequest](/docs/api-reference/sdk/models/data-models#getcommentsrequest)
* Returns: [GetCommentsResponse](/docs/api-reference/sdk/models/data-models#getcommentsresponse)
```python theme={null}
from velt_py.models.comment_annotation_api import GetCommentsRequest
result = sdk.api.commentAnnotations.getComments(
GetCommentsRequest(
organizationId='yourOrganizationId',
documentId='yourDocumentId',
annotationId='yourAnnotationId',
userIds=['yourUserId']
)
)
```
**Response**
```python theme={null}
{
'result': {
'status': 'success',
'message': 'Comments retrieved successfully.',
'data': [
{
'commentId': 123456,
'type': 'text',
'commentText': 'This is a sample comment text.',
'commentHtml': 'This is a sample comment text.
',
'createdAt': 1777973714914,
'lastUpdated': '2026-05-05T09:35:15.048Z',
'reactionAnnotationIds': ['reactionAnnotationId1'],
'from': {'userId': 'user123', 'name': 'John Doe', 'email': 'john.doe@example.com'}
}
]
}
}
```
#### `updateComments`
* Updates fields on individual comments inside an annotation.
* Params: [UpdateCommentsRequest](/docs/api-reference/sdk/models/data-models#updatecommentsrequest)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse)
* Accepts the optional `filter_unknown_fields=True` keyword (see the note above).
```python theme={null}
from velt_py.models.comment_annotation_api import UpdateCommentsRequest
result = sdk.api.commentAnnotations.updateComments(
UpdateCommentsRequest(
organizationId='yourOrganizationId',
documentId='yourDocumentId',
annotationId='yourAnnotationId',
commentIds=[607395],
updatedData={'commentText': 'Updated text', 'commentHtml': 'Updated text
'}
)
)
```
**Response**
```python theme={null}
{
'result': {
'status': 'success',
'message': 'Comment updated successfully.',
'data': {
'607395': {
'success': True,
'id': 607395,
'message': 'Updated successfully'
}
}
}
}
```
#### `deleteComments`
* Deletes one or more comments from an annotation, or all comments if `commentIds` is omitted.
* Params: [DeleteCommentsRequest](/docs/api-reference/sdk/models/data-models#deletecommentsrequest)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse)
```python theme={null}
from velt_py.models.comment_annotation_api import DeleteCommentsRequest
result = sdk.api.commentAnnotations.deleteComments(
DeleteCommentsRequest(
organizationId='yourOrganizationId',
documentId='yourDocumentId',
annotationId='yourAnnotationId',
commentIds=[153783, 607395]
)
)
```
**Response**
```python theme={null}
{
'result': {
'status': 'success',
'message': 'Comments(s) deleted successfully.',
'data': {
'153783': {
'success': True,
'id': 153783,
'message': 'Deleted successfully'
},
'607395': {
'success': False,
'id': 607395,
'message': 'Not found'
}
}
}
}
```
### Activities
> [!NOTE]
>
> **Filtering unknown fields**: The add/update methods below accept an optional `filter_unknown_fields: bool = False` keyword (backed by `velt_py.models.field_allowlists`). When `True`, request entity collections are filtered to only the fields the Velt API accepts, dropping unknown/custom top-level keys before the request is sent. Open-typed fields (`context`, `metadata`, `entityData`, user objects) pass through whole — their nested contents are never filtered. Filtering is fail-open: if it errors, the original payload is sent, so a write is never blocked.
```python theme={null}
result = sdk.api.activities.addActivities(
AddActivitiesRequest(
organizationId='org-123', documentId='doc-456',
activities=[{'featureType': 'comment', 'actionType': 'comment.add', 'actionUser': {'userId': 'user-1'}, 'internalTrackingId': 'abc-123'}]
),
filter_unknown_fields=True,
)
# The 'internalTrackingId' key is removed before the request is sent.
```
#### `addActivities`
* Logs one or more activity events.
* For `featureType` `'custom'`, `targetEntityId` is required; the other feature types accept it as optional.
* Params: [AddActivitiesRequest](/docs/api-reference/sdk/models/data-models#addactivitiesrequest)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse)
* Accepts the optional `filter_unknown_fields=True` keyword (see the note above).
```python theme={null}
from velt_py.models.activity_api import AddActivitiesRequest
result = sdk.api.activities.addActivities(
AddActivitiesRequest(
organizationId='org-123',
documentId='doc-456',
activities=[{
'featureType': 'comment',
'actionType': 'comment.add',
'actionUser': {'userId': 'user-1', 'name': 'User Name', 'email': 'user@example.com'},
'displayMessageTemplate': '{{user}} added a comment'
}]
)
)
```
**Response**
```python theme={null}
{
'result': {
'status': 'success',
'message': 'Activity(s) added successfully.',
'data': {
'success': True,
'message': 'Activity(s) added successfully.'
}
}
}
```
#### `getActivities`
* Retrieves activities with optional filters and pagination.
* Params: [GetActivitiesRequest](/docs/api-reference/sdk/models/data-models#getactivitiesrequest)
* Returns: [GetActivitiesResponse](/docs/api-reference/sdk/models/data-models#getactivitiesresponse)
```python theme={null}
from velt_py.models.activity_api import GetActivitiesRequest
result = sdk.api.activities.getActivities(
GetActivitiesRequest(
organizationId='org-123',
documentId='doc-456',
featureTypes=['comment'],
order='desc',
pageSize=50
)
)
```
**Response**
```python theme={null}
{
'result': {
'status': 'success',
'message': 'Activity(s) retrieved successfully.',
'data': [
{
'id': 'activity-001',
'featureType': 'comment',
'actionType': 'comment.add',
'actionUser': {'userId': 'user-1', 'email': 'user@example.com', 'name': 'User Name'},
'targetEntityId': 'annotation-789',
'displayMessageTemplate': '{{user}} added a comment',
'displayMessageTemplateData': {'user': {'userId': 'user-1', 'name': 'User Name'}},
'metadata': {'apiKey': 'yourApiKey', 'documentId': 'doc-456', 'organizationId': 'org-123'},
'timestamp': 1722409519944
}
],
'pageToken': 'nextPageToken'
}
}
```
#### `updateActivities`
* Updates fields on existing activities.
* Params: [UpdateActivitiesRequest](/docs/api-reference/sdk/models/data-models#updateactivitiesrequest)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse)
* Accepts the optional `filter_unknown_fields=True` keyword (see the note above).
```python theme={null}
from velt_py.models.activity_api import UpdateActivitiesRequest
result = sdk.api.activities.updateActivities(
UpdateActivitiesRequest(
organizationId='org-123',
activities=[{
'id': 'activity-001',
'displayMessageTemplate': '{{user}} updated the comment'
}]
)
)
```
**Response**
```python theme={null}
{
'result': {
'status': 'success',
'message': 'Activity(s) updated successfully.',
'data': {
'activity-001': {
'success': True,
'message': 'Activity updated.'
}
}
}
}
```
#### `deleteActivities`
* Deletes activities by document, target entity, or specific IDs.
* Params: [DeleteActivitiesRequest](/docs/api-reference/sdk/models/data-models#deleteactivitiesrequest)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse)
```python theme={null}
from velt_py.models.activity_api import DeleteActivitiesRequest
result = sdk.api.activities.deleteActivities(
DeleteActivitiesRequest(
organizationId='org-123',
activityIds=['activity-001', 'activity-002']
)
)
```
**Response**
```python theme={null}
{
'result': {
'status': 'success',
'message': 'Activity(s) deleted successfully.',
'data': {
'activity-001': {
'success': True,
'message': 'Activity deleted.'
}
}
}
}
```
### Access Control
#### `addPermissions`
* Grants resource-level permissions to a user.
* Params: [AddPermissionsRequest](/docs/api-reference/sdk/models/data-models#addpermissionsrequest)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse)
```python theme={null}
from velt_py.models.access_control import AddPermissionsRequest
result = sdk.api.accessControl.addPermissions(
AddPermissionsRequest(
user={'userId': 'some-user-id'},
permissions={'resources': [
{'type': 'organization', 'id': 'YOUR_ORGANIZATION_ID', 'accessRole': 'editor'},
{'type': 'document', 'id': 'YOUR_DOCUMENT_ID', 'organizationId': 'YOUR_ORGANIZATION_ID', 'accessRole': 'viewer', 'expiresAt': 1728902400}
]}
)
)
```
**Response**
```python theme={null}
{
'result': {
'status': 'success',
'message': 'Permissions added successfully.'
}
}
```
#### `getPermissions`
* Retrieves permissions for one or more users.
* Pass at least one of `folderIds` or `documentIds`; the API rejects a call with neither. By default the API also errors when the organization or any supplied ID does not exist; set `skipResourceExistenceValidation=True` to skip that check.
* Params: [GetPermissionsRequest](/docs/api-reference/sdk/models/data-models#getpermissionsrequest)
* Returns: [GetPermissionsResponse](/docs/api-reference/sdk/models/data-models#getpermissionsresponse)
```python theme={null}
from velt_py.models.access_control import GetPermissionsRequest
result = sdk.api.accessControl.getPermissions(
GetPermissionsRequest(
organizationId='org1',
userIds=['1.1'],
documentIds=['document1']
)
)
```
**Response**
```python theme={null}
{
'result': {
'status': 'success',
'message': 'User permissions retrieved successfully.',
'data': {
'1.1': {
'folders': {
'folder2': {'accessRole': 'editor', 'accessType': 'restricted'}
},
'documents': {
'document1': {'accessRole': 'viewer', 'accessType': 'restricted'}
},
'organization': {
'org1': {'accessRole': 'editor'}
}
}
}
}
}
```
#### `removePermissions`
* Revokes resource-level permissions from a user.
* Params: [RemovePermissionsRequest](/docs/api-reference/sdk/models/data-models#removepermissionsrequest)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse)
```python theme={null}
from velt_py.models.access_control import RemovePermissionsRequest
result = sdk.api.accessControl.removePermissions(
RemovePermissionsRequest(
userId='USER_ID',
permissions={'resources': [
{'type': 'organization', 'id': 'ORGANIZATION_ID'},
{'type': 'document', 'id': 'DOCUMENT_ID', 'organizationId': 'ORGANIZATION_ID'}
]}
)
)
```
**Response**
```python theme={null}
{
'result': {
'status': 'success',
'message': 'Permissions removed successfully.'
}
}
```
#### `generateSignature`
* Generates a signed payload for Velt's Permission Provider flow.
* Params: [GenerateSignatureRequest](/docs/api-reference/sdk/models/data-models#generatesignaturerequest)
* Returns: [GenerateSignatureResponse](/docs/api-reference/sdk/models/data-models#generatesignatureresponse)
```python theme={null}
from velt_py.models.access_control import GenerateSignatureRequest
result = sdk.api.accessControl.generateSignature(
GenerateSignatureRequest(
permissions=[{
'userId': 'user123',
'resourceId': 'document456',
'type': 'document',
'hasAccess': True,
'accessRole': 'viewer',
'expiresAt': 1759745729823
}]
)
)
```
**Response**
```python theme={null}
{
'result': {
'status': 'success',
'message': 'Signature generated successfully.',
'data': { 'signature': 'a1b2c3d4e5f6...' }
}
}
```
#### `generateToken`
* Generates a Velt JWT token bound to a user and a set of resource permissions.
* Calls `POST /v2/auth/generate_token`, the endpoint documented in the [Generate Token REST API](/docs/api-reference/rest-apis/v2/auth/generate-token) and used by the [JWT guide](/docs/security/jwt-tokens).
* Expects: `GenerateTokenRequest { userId, userProperties: { name, email, isAdmin }, permissions: { resources: [...] } }`.
* Returns the raw Velt API response: `{ result: { status, message, data: { token } } }`.
* Params: [GenerateTokenRequest](/docs/api-reference/sdk/models/data-models#generatetokenrequest)
* Returns: [GenerateTokenResponse](/docs/api-reference/sdk/models/data-models#generatetokenresponse)
```python theme={null}
from velt_py.models.access_control import GenerateTokenRequest
result = sdk.api.accessControl.generateToken(
GenerateTokenRequest(
userId='user123',
userProperties={'isAdmin': False, 'name': 'John Doe', 'email': 'john@example.com'},
permissions={'resources': [
{'type': 'organization', 'id': 'org_123', 'accessRole': 'viewer'},
{'type': 'document', 'id': 'doc_456', 'organizationId': 'org_123', 'accessRole': 'editor', 'expiresAt': 1640995200}
]}
)
)
```
**Response**
```python theme={null}
{
'result': {
'status': 'success',
'message': 'Token generated successfully.',
'data': { 'token': 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...' }
}
}
```
### CRDT
#### `addCrdtData`
* Stores CRDT data (text, map, array, or xml) for an editor on a document.
* Params: [AddCrdtDataRequest](/docs/api-reference/sdk/models/data-models#addcrdtdatarequest)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse)
```python theme={null}
from velt_py.models.crdt import AddCrdtDataRequest
result = sdk.api.crdt.addCrdtData(
AddCrdtDataRequest(
organizationId='yourOrganizationId',
documentId='yourDocumentId',
editorId='my-collab-note',
data='Hello, collaborative world!',
type='text'
)
)
```
**Response**
```python theme={null}
{
'result': {
'status': 'success',
'message': 'CRDT data added successfully.'
}
}
```
#### `getCrdtData`
* Retrieves CRDT data for one or all editors on a document.
* Params: [GetCrdtDataRequest](/docs/api-reference/sdk/models/data-models#getcrdtdatarequest)
* Returns: [GetCrdtDataResponse](/docs/api-reference/sdk/models/data-models#getcrdtdataresponse)
```python theme={null}
from velt_py.models.crdt import GetCrdtDataRequest
result = sdk.api.crdt.getCrdtData(
GetCrdtDataRequest(
organizationId='yourOrganizationId',
documentId='yourDocumentId',
editorId='my-collab-note'
)
)
```
**Response**
```python theme={null}
{
'result': {
'status': 'success',
'message': 'CRDT data retrieved successfully.',
'data': [
{
'data': 'Hello, collaborative world!',
'id': 'my-collab-note',
'lastUpdate': '2025-01-20T10:30:00.000Z',
'lastUpdatedBy': 'user-123',
'sessionId': 'session-abc-456'
}
]
}
}
```
#### `updateCrdtData`
* Updates existing CRDT data for an editor.
* Params: [UpdateCrdtDataRequest](/docs/api-reference/sdk/models/data-models#updatecrdtdatarequest)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse)
```python theme={null}
from velt_py.models.crdt import UpdateCrdtDataRequest
result = sdk.api.crdt.updateCrdtData(
UpdateCrdtDataRequest(
organizationId='yourOrganizationId',
documentId='yourDocumentId',
editorId='my-collab-note',
data='Updated collaborative content!',
type='text'
)
)
```
**Response**
```python theme={null}
{
'result': {
'status': 'success',
'message': 'CRDT data updated successfully.'
}
}
```
#### `deleteCrdtData`
* Deletes CRDT editor data. Optionally target specific `editorIds`; omit to delete all editors for a document.
* Params: `DeleteCrdtDataRequest` (from `velt_py.models.crdt`)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse)
```python theme={null}
from velt_py.models.crdt import DeleteCrdtDataRequest
result = sdk.api.crdt.deleteCrdtData(
DeleteCrdtDataRequest(
organizationId='org-123',
documentId='doc-1',
editorIds=['my-collab-note']
)
)
```
### Presence
#### `addPresence`
* Adds users to a document's presence list.
* Params: [AddPresenceRequest](/docs/api-reference/sdk/models/data-models#addpresencerequest)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse)
```python theme={null}
from velt_py.models.presence import AddPresenceRequest
result = sdk.api.presence.addPresence(
AddPresenceRequest(
organizationId='org-123',
documentId='doc-456',
users=[
{'userId': 'user-1', 'name': 'John Doe', 'email': 'john@example.com', 'status': 'online'},
{'userId': 'user-2', 'name': 'Jane Doe', 'status': 'away'}
]
)
)
```
**Response**
```python theme={null}
{
'result': {
'status': 'success',
'message': 'Presence added successfully.',
'data': { 'success': True }
}
}
```
#### `updatePresence`
* Updates presence status for one or more users on a document.
* Params: [UpdatePresenceRequest](/docs/api-reference/sdk/models/data-models#updatepresencerequest)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse)
```python theme={null}
from velt_py.models.presence import UpdatePresenceRequest
result = sdk.api.presence.updatePresence(
UpdatePresenceRequest(
organizationId='org-123',
documentId='doc-456',
users=[{'userId': 'user-1', 'status': 'away'}]
)
)
```
**Response**
```python theme={null}
{
'result': {
'status': 'success',
'message': 'Presence updated successfully.',
'data': { 'success': True }
}
}
```
#### `deletePresence`
* Removes users from a document's presence list.
* Params: [DeletePresenceRequest](/docs/api-reference/sdk/models/data-models#deletepresencerequest)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse)
```python theme={null}
from velt_py.models.presence import DeletePresenceRequest
result = sdk.api.presence.deletePresence(
DeletePresenceRequest(
organizationId='org-123',
documentId='doc-456',
userIds=['user-1', 'user-2']
)
)
```
**Response**
```python theme={null}
{
'result': {
'status': 'success',
'message': 'Presence deleted successfully.',
'data': { 'success': True }
}
}
```
### Livestate
#### `broadcastEvent`
* Broadcasts an event payload to all clients subscribed to a livestate ID on a document.
* Params: [BroadcastEventRequest](/docs/api-reference/sdk/models/data-models#broadcasteventrequest)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse)
```python theme={null}
from velt_py.models.livestate import BroadcastEventRequest
result = sdk.api.livestate.broadcastEvent(
BroadcastEventRequest(
organizationId='org-123',
documentId='doc-1',
liveStateDataId='my-live-state',
data={'status': 'active', 'message': 'Hello World'},
merge=True
)
)
```
**Response**
```python theme={null}
{
'result': {
'status': 'success',
'message': 'Event broadcasted successfully.',
'data': { 'success': True }
}
}
```
### Recordings
#### `getRecordings`
* Retrieves recording metadata for a document. Pass `documentId` to target the document; omitting it returns an empty list, not the organization's recordings. `recordingIds` filters the fetched page.
* Params: [GetRecordingsRequest](/docs/api-reference/sdk/models/data-models#getrecordingsrequest)
* Returns: [GetRecordingsResponse](/docs/api-reference/sdk/models/data-models#getrecordingsresponse)
```python theme={null}
from velt_py.models.recording import GetRecordingsRequest
result = sdk.api.recordings.getRecordings(
GetRecordingsRequest(
organizationId='org-123',
documentId='doc-456',
recordingIds=['rec-1'],
pageSize=10,
pageToken='encryptedPageToken'
)
)
```
**Response**
```python theme={null}
{
'result': {
'status': 'success',
'message': 'Recorder annotations retrieved successfully.',
'data': [
{
'type': 'recorder',
'recordingType': 'screen',
'mode': 'floating',
'metadata': {
'apiKey': 'YOUR_API_KEY',
'documentId': 'doc-456',
'organizationId': 'org-123'
},
'recordedTime': {'duration': 4204.55, 'display': '00:00:04'},
'displayName': 'Screen Recording 1773814490242.mp4',
'annotationId': 'ypvmVTROaNU1qP4kq7Cc',
'attachments': [
{
'attachmentId': 875113,
'url': 'https://storage.googleapis.com/...',
'mimeType': 'video/mp4',
'name': 'recording_1773814490242.mp4',
'type': 'mp4',
'size': 103551
}
],
'latestVersion': 5
}
],
'pageToken': 'nextPageToken'
}
}
```
### Rewriter
#### `askAi`
* Sends a model, prompt, and text to Velt's AI rewriter and returns the transformed text.
* Params: [AskAiRequest](/docs/api-reference/sdk/models/data-models#askairequest)
* Returns: [AskAiResponse](/docs/api-reference/sdk/models/data-models#askairesponse)
```python theme={null}
from velt_py.models.rewriter import AskAiRequest
result = sdk.api.rewriter.askAi(
AskAiRequest(
model='gpt-4o',
prompt='Fix the grammar and spelling in the following text.',
text='Their going to the store to by some apples.'
)
)
```
**Response**
```python theme={null}
{
'result': {
'success': True,
'text': "They're going to the store to buy some apples."
}
}
```
> Note: This call may take several seconds and has no client-side timeout. Wrap calls in your own timeout if needed.
### GDPR
#### `deleteAllUserData`
* Requests deletion of all data associated with one or more users.
* `organizationIds` scopes the deletion to those organizations. When it is omitted, the API deletes the user's data across every organization. The server truncates more than 30 `userIds` to the first 30.
* Params: [DeleteAllUserDataRequest](/docs/api-reference/sdk/models/data-models#deletealluserdatarequest)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse)
```python theme={null}
from velt_py.models.gdpr import DeleteAllUserDataRequest
result = sdk.api.gdpr.deleteAllUserData(
DeleteAllUserDataRequest(
userIds=['user-1', 'user-2'],
organizationIds=['org-123']
)
)
```
**Response**
```python theme={null}
{
'status': 'success',
'message': 'Data deletion process has been initiated.',
'data': {
'jobId': 'dsQuvPmIynANgPLLEhCm',
'tasksCount': 5
},
'statusCode': 202
}
```
> Note: This call is asynchronous and returns a `jobId`. Poll status via `getDeleteUserDataStatus`.
#### `getAllUserData`
* Exports all data associated with a user, paginated.
* Params: [GetAllUserDataRequest](/docs/api-reference/sdk/models/data-models#getalluserdatarequest)
* Returns: [GetAllUserDataResponse](/docs/api-reference/sdk/models/data-models#getalluserdataresponse)
```python theme={null}
from velt_py.models.gdpr import GetAllUserDataRequest
result = sdk.api.gdpr.getAllUserData(
GetAllUserDataRequest(
organizationId='org-123',
userId='user-1',
pageToken='next-page-token'
)
)
```
**Response**
```python theme={null}
{
'result': {
'status': 'success',
'message': 'Data fetched successfully.',
'data': {
'comments': [], # Up to 100 items per page.
'reactions': [], # Up to 100 items per page.
'recordings': [], # Up to 100 items per page.
'notifications': [] # Up to 100 items per page.
},
'nextPageToken': 'bhdwdqwjs298e39e479ddkeuw==329'
}
}
```
#### `getDeleteUserDataStatus`
* Polls the status of a `deleteAllUserData` job.
* Params: [GetDeleteUserDataStatusRequest](/docs/api-reference/sdk/models/data-models#getdeleteuserdatastatusrequest)
* Returns: [GetDeleteUserDataStatusResponse](/docs/api-reference/sdk/models/data-models#getdeleteuserdatastatusresponse)
```python theme={null}
from velt_py.models.gdpr import GetDeleteUserDataStatusRequest
result = sdk.api.gdpr.getDeleteUserDataStatus(
GetDeleteUserDataStatusRequest(jobId='job-id-from-delete-call')
)
```
**Response**
```python theme={null}
{
'result': {
'status': 'success',
'message': 'Data fetched successfully.',
'data': {
'isDeleteCompleted': True,
'tasksLeft': 0,
'lastTaskCompletedTime': 1748972106739
}
}
}
```
### Workspace
#### `createWorkspace`
* Creates a new workspace.
* Params: [CreateWorkspaceRequest](/docs/api-reference/sdk/models/data-models#createworkspacerequest)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse)
```python theme={null}
from velt_py.models.workspace import CreateWorkspaceRequest
result = sdk.api.workspace.createWorkspace(
CreateWorkspaceRequest(
ownerEmail='owner@example.com',
workspaceName='My Workspace',
name='John Doe'
)
)
```
**Response**
```python theme={null}
{
'result': {
'status': 'success',
'message': 'Workspace created successfully.',
'data': {
'id': 'workspace_abc123',
'name': 'My Workspace',
'owner': {
'email': 'owner@example.com',
'id': 'owner_id_123',
'name': 'John Doe',
'avatar': ''
},
'authToken': 'eyJhbGciOiJSUzI1NiIs...',
'apiKeyList': {
'velt_api_key_1': {
'apiKeyName': 'John Doe Test API Key',
'id': 'velt_api_key_1',
'type': 'testing'
}
}
}
}
}
```
#### `getWorkspace`
* Retrieves details about the current workspace.
* Params: [GetWorkspaceRequest](/docs/api-reference/sdk/models/data-models#getworkspacerequest)
* Returns: [GetWorkspaceResponse](/docs/api-reference/sdk/models/data-models#getworkspaceresponse)
```python theme={null}
from velt_py.models.workspace import GetWorkspaceRequest
result = sdk.api.workspace.getWorkspace(GetWorkspaceRequest())
```
**Response**
```python theme={null}
{
'result': {
'status': 'success',
'message': 'Workspace retrieved successfully.',
'data': {
'id': 'workspace_abc123',
'name': 'My Workspace',
'owner': {
'email': 'owner@example.com',
'id': 'owner_id_123',
'name': 'John Doe',
'avatar': ''
},
'authToken': 'eyJhbGciOiJSUzI1NiIs...',
'apiKeyList': {
'velt_api_key_1': {
'apiKeyName': 'John Doe Test API Key',
'id': 'velt_api_key_1',
'type': 'testing'
}
}
}
}
}
```
#### `createApiKey`
* Creates a new API key in the workspace.
* Params: [CreateApiKeyRequest](/docs/api-reference/sdk/models/data-models#createapikeyrequest)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse)
```python theme={null}
from velt_py.models.workspace import CreateApiKeyRequest
result = sdk.api.workspace.createApiKey(
CreateApiKeyRequest(
ownerEmail='owner@example.com',
type='production',
createAuthToken=True,
apiKeyName='Production Key',
allowedDomains=['example.com', '*.example.com']
)
)
```
**Response**
```python theme={null}
{
'result': {
'status': 'success',
'message': 'API key created successfully.',
'data': { 'apiKey': 'your_new_api_key' }
}
}
```
#### `updateApiKey`
* Updates an existing API key (e.g., rename it).
* Params: [UpdateApiKeyRequest](/docs/api-reference/sdk/models/data-models#updateapikeyrequest)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse)
```python theme={null}
from velt_py.models.workspace import UpdateApiKeyRequest
result = sdk.api.workspace.updateApiKey(
UpdateApiKeyRequest(apiKey='velt_api_key_1', apiKeyName='Renamed Key')
)
```
**Response**
```python theme={null}
{
'result': {
'status': 'success',
'message': 'API key updated successfully.',
'data': None
}
}
```
#### `getApiKeys`
* Lists all API keys in the workspace.
* Params: [GetApiKeysRequest](/docs/api-reference/sdk/models/data-models#getapikeysrequest)
* Returns: [GetApiKeysResponse](/docs/api-reference/sdk/models/data-models#getapikeysresponse)
```python theme={null}
from velt_py.models.workspace import GetApiKeysRequest
result = sdk.api.workspace.getApiKeys(
GetApiKeysRequest(pageSize=50, pageToken='next-page-token')
)
```
**Response**
```python theme={null}
{
'result': {
'status': 'success',
'message': 'API keys retrieved successfully.',
'data': [
{'id': 'velt_api_key_1', 'apiKeyName': 'Production Key', 'type': 'production'},
{'id': 'velt_api_key_2', 'apiKeyName': 'Testing Key', 'type': 'testing'}
],
'nextPageToken': 'eyJsYXN0SWQiOiJ2ZWx0X2FwaV9rZXlfMiJ9'
}
}
```
#### `getApiKeyMetadata`
* Gets metadata for the API key the SDK is authenticated with.
* Params: [GetApiKeyMetadataRequest](/docs/api-reference/sdk/models/data-models#getapikeymetadatarequest)
* Returns: [GetApiKeyMetadataResponse](/docs/api-reference/sdk/models/data-models#getapikeymetadataresponse)
* **Fixed in v0.1.11**: now targets the canonical `/v2/workspace/apikeyconfig/get` endpoint (was `/v2/workspace/apikeymetadata/get`, retained as a legacy backend alias). Method signature is unchanged — no call-site change needed.
```python theme={null}
from velt_py.models.workspace import GetApiKeyMetadataRequest
result = sdk.api.workspace.getApiKeyMetadata(GetApiKeyMetadataRequest())
```
**Response**
```python theme={null}
{
'result': {
'status': 'success',
'message': 'API key metadata retrieved successfully.',
'data': {
'defaultDocumentAccessType': 'public',
'planInfo': {'type': 'sdk test'},
'ownerEmail': 'owner@example.com'
}
}
}
```
#### `resetAuthToken`
* Rotates the auth token associated with an API key.
* Params: [ResetAuthTokenRequest](/docs/api-reference/sdk/models/data-models#resetauthtokenrequest)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse)
```python theme={null}
from velt_py.models.workspace import ResetAuthTokenRequest
result = sdk.api.workspace.resetAuthToken(
ResetAuthTokenRequest(apiKey='velt_api_key_1')
)
```
**Response**
```python theme={null}
{
'result': {
'status': 'success',
'message': 'Auth token reset successfully.',
'data': {
'apiKey': 'velt_api_key_1',
'newAuthToken': {
'token': 'eyJhbGciOiJSUzI1NiIs...',
'name': 'Default Auth Token',
'domains': []
}
}
}
}
```
#### `getAuthTokens`
* Lists auth tokens for an API key.
* Params: [GetAuthTokensRequest](/docs/api-reference/sdk/models/data-models#getauthtokensrequest)
* Returns: [GetAuthTokensResponse](/docs/api-reference/sdk/models/data-models#getauthtokensresponse)
```python theme={null}
from velt_py.models.workspace import GetAuthTokensRequest
result = sdk.api.workspace.getAuthTokens(
GetAuthTokensRequest(apiKey='velt_api_key_1')
)
```
**Response**
```python theme={null}
{
'result': {
'status': 'success',
'message': 'Auth tokens retrieved successfully.',
'data': {
'apiKey': 'velt_api_key_1',
'authTokens': [
{'token': 'eyJhbGciOiJSUzI1NiIs...', 'name': 'Default Auth Token', 'domains': []}
]
}
}
}
```
#### `addDomains`
* Adds allowed domains to the workspace.
* Params: [AddDomainsRequest](/docs/api-reference/sdk/models/data-models#adddomainsrequest)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse)
```python theme={null}
from velt_py.models.workspace import AddDomainsRequest
result = sdk.api.workspace.addDomains(
AddDomainsRequest(domains=['google.com', '*.firebase.com'])
)
```
**Response**
```python theme={null}
{
'result': {
'status': 'success',
'message': 'Domain(s) added successfully to allowed domains.',
'data': {
'domainsAdded': ['google.com', '*.firebase.com']
}
}
}
```
#### `deleteDomains`
* Removes allowed domains from the workspace.
* Params: [DeleteDomainsRequest](/docs/api-reference/sdk/models/data-models#deletedomainsrequest)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse)
```python theme={null}
from velt_py.models.workspace import DeleteDomainsRequest
result = sdk.api.workspace.deleteDomains(
DeleteDomainsRequest(domains=['google.com', '*.firebase.com'])
)
```
**Response**
```python theme={null}
{
'result': {
'status': 'success',
'message': 'Domain(s) removed successfully from allowed domains.',
'data': {
'domainsRemoved': ['google.com', '*.firebase.com']
}
}
}
```
#### `getDomains`
* Lists allowed domains for the workspace.
* Params: [GetDomainsRequest](/docs/api-reference/sdk/models/data-models#getdomainsrequest)
* Returns: [GetDomainsResponse](/docs/api-reference/sdk/models/data-models#getdomainsresponse)
```python theme={null}
from velt_py.models.workspace import GetDomainsRequest
result = sdk.api.workspace.getDomains(GetDomainsRequest())
```
**Response**
```python theme={null}
{
'result': {
'status': 'success',
'message': 'Allowed domains retrieved successfully.',
'data': {
'allowedDomains': ['localhost', '127.0.0.1', 'example.com']
}
}
}
```
#### `getEmailStatus`
* Checks email verification status for a workspace owner.
* Params: [GetEmailStatusRequest](/docs/api-reference/sdk/models/data-models#getemailstatusrequest)
* Returns: [GetEmailStatusResponse](/docs/api-reference/sdk/models/data-models#getemailstatusresponse)
```python theme={null}
from velt_py.models.workspace import GetEmailStatusRequest
result = sdk.api.workspace.getEmailStatus(
GetEmailStatusRequest(ownerEmail='owner@example.com')
)
```
**Response**
```python theme={null}
{
'result': {
'status': 'success',
'message': 'Email verified and workspace reactivated',
'data': { 'verified': True }
}
}
```
#### `sendLoginLink`
* Sends a login link email to a user.
* Params: [SendLoginLinkRequest](/docs/api-reference/sdk/models/data-models#sendloginlinkrequest)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse)
```python theme={null}
from velt_py.models.workspace import SendLoginLinkRequest
result = sdk.api.workspace.sendLoginLink(
SendLoginLinkRequest(email='user@example.com', continueUrl='https://app.example.com/dashboard')
)
```
**Response**
```python theme={null}
{
'result': {
'status': 'success',
'message': 'Login link sent successfully.',
'data': None
}
}
```
#### `getEmailConfig`
* Retrieves the workspace's email service configuration.
* Params: [GetEmailConfigRequest](/docs/api-reference/sdk/models/data-models#getemailconfigrequest)
* Returns: [GetEmailConfigResponse](/docs/api-reference/sdk/models/data-models#getemailconfigresponse)
```python theme={null}
from velt_py.models.workspace import GetEmailConfigRequest
result = sdk.api.workspace.getEmailConfig(GetEmailConfigRequest())
```
**Response**
```python theme={null}
{
'result': {
'status': 'success',
'message': 'Email configuration retrieved successfully.',
'data': {
'useEmailService': False,
'emailServiceConfig': {
'type': 'default',
'apiKey': '',
'fromEmail': '',
'fromCompany': '',
'commentTemplateId': '',
'tagTemplateId': ''
}
}
}
}
```
#### `updateEmailConfig`
* Updates the workspace's email service configuration.
* Params: [UpdateEmailConfigRequest](/docs/api-reference/sdk/models/data-models#updateemailconfigrequest)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse)
```python theme={null}
from velt_py.models.workspace import UpdateEmailConfigRequest
result = sdk.api.workspace.updateEmailConfig(
UpdateEmailConfigRequest(
useEmailService=True,
emailServiceConfig={'type': 'sendgrid', 'apiKey': 'sg-key', 'fromEmail': 'noreply@example.com'}
)
)
```
**Response**
```python theme={null}
{
'result': {
'status': 'success',
'message': 'Email configuration updated successfully.',
'data': None
}
}
```
#### `getWebhookConfig`
* Retrieves the workspace's webhook configuration.
* Params: [GetWebhookConfigRequest](/docs/api-reference/sdk/models/data-models#getwebhookconfigrequest)
* Returns: [GetWebhookConfigResponse](/docs/api-reference/sdk/models/data-models#getwebhookconfigresponse)
```python theme={null}
from velt_py.models.workspace import GetWebhookConfigRequest
result = sdk.api.workspace.getWebhookConfig(GetWebhookConfigRequest())
```
**Response**
```python theme={null}
{
'result': {
'status': 'success',
'message': 'Webhook configuration retrieved successfully.',
'data': {
'useWebhookService': False,
'webhookServiceConfig': {
'authToken': '',
'rawNotificationUrl': '',
'processedNotificationUrl': ''
}
}
}
}
```
#### `updateWebhookConfig`
* Updates the workspace's webhook configuration.
* Params: [UpdateWebhookConfigRequest](/docs/api-reference/sdk/models/data-models#updatewebhookconfigrequest)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse)
```python theme={null}
from velt_py.models.workspace import UpdateWebhookConfigRequest
result = sdk.api.workspace.updateWebhookConfig(
UpdateWebhookConfigRequest(
useWebhookService=True,
webhookServiceConfig={
'authToken': 'webhook-secret',
'rawNotificationUrl': 'https://example.com/webhook/raw',
'processedNotificationUrl': 'https://example.com/webhook/processed'
}
)
)
```
**Response**
```python theme={null}
{
'result': {
'status': 'success',
'message': 'Webhook configuration updated successfully.',
'data': None
}
}
```
#### `getRequestedDomains`
* Gets requested (pending) domains.
* Params: `GetRequestedDomainsRequest` (from `velt_py.models.workspace`)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse)
```python theme={null}
from velt_py.models.workspace import GetRequestedDomainsRequest
result = sdk.api.workspace.getRequestedDomains(GetRequestedDomainsRequest())
```
#### `createDomainRequest`
* Creates a domain access request.
* Params: `CreateDomainRequest` (from `velt_py.models.workspace`)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse)
```python theme={null}
from velt_py.models.workspace import CreateDomainRequest
result = sdk.api.workspace.createDomainRequest(
CreateDomainRequest(domain='https://example.com')
)
```
#### `acceptRejectAdditionalUrlRequest`
* Accepts or rejects an additional-URL request.
* Params: `AcceptRejectAdditionalUrlRequest` (from `velt_py.models.workspace`)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse)
```python theme={null}
from velt_py.models.workspace import AcceptRejectAdditionalUrlRequest
result = sdk.api.workspace.acceptRejectAdditionalUrlRequest(
AcceptRejectAdditionalUrlRequest(action='accept', id='request-1', clientDocId='doc-1')
)
```
#### `copyApiKey`
* Copies configuration from one API key to another (workspace-scoped).
* Params: `CopyApiKeyRequest` (from `velt_py.models.workspace`)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse)
```python theme={null}
from velt_py.models.workspace import CopyApiKeyRequest
result = sdk.api.workspace.copyApiKey(
CopyApiKeyRequest(sourceApiKey='velt_api_key_1', targetApiKey='velt_api_key_2')
)
```
#### `updateApiKeyMetadata`
* Updates API key app configuration (private comments, JWT, default access, AI keys).
* Params: `UpdateApiKeyMetadataRequest` (from `velt_py.models.workspace`)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse)
```python theme={null}
from velt_py.models.workspace import UpdateApiKeyMetadataRequest
result = sdk.api.workspace.updateApiKeyMetadata(
UpdateApiKeyMetadataRequest(defaultDocumentAccessType='organizationPrivate')
)
```
#### `getNotificationConfig`
* Gets the workspace notification service config.
* Params: `GetWorkspaceNotificationConfigRequest` (from `velt_py.models.workspace`)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse)
```python theme={null}
from velt_py.models.workspace import GetWorkspaceNotificationConfigRequest
result = sdk.api.workspace.getNotificationConfig(GetWorkspaceNotificationConfigRequest())
```
#### `updateNotificationConfig`
* Updates the workspace notification service config.
* Params: `UpdateWorkspaceNotificationConfigRequest` (from `velt_py.models.workspace`)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse)
```python theme={null}
from velt_py.models.workspace import UpdateWorkspaceNotificationConfigRequest
result = sdk.api.workspace.updateNotificationConfig(
UpdateWorkspaceNotificationConfigRequest(useNotificationService=True)
)
```
#### `getPermissionProviderConfig`
* Gets the permission provider config.
* Params: `GetPermissionProviderConfigRequest` (from `velt_py.models.workspace`)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse)
```python theme={null}
from velt_py.models.workspace import GetPermissionProviderConfigRequest
result = sdk.api.workspace.getPermissionProviderConfig(GetPermissionProviderConfigRequest())
```
#### `updatePermissionProviderConfig`
* Updates the permission provider config.
* Params: `UpdatePermissionProviderConfigRequest` (from `velt_py.models.workspace`)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse)
```python theme={null}
from velt_py.models.workspace import UpdatePermissionProviderConfigRequest
result = sdk.api.workspace.updatePermissionProviderConfig(
UpdatePermissionProviderConfigRequest(usePermissionProvider=True)
)
```
#### `getActivityConfig`
* Gets the activity logs config.
* Params: `GetActivityConfigRequest` (from `velt_py.models.workspace`)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse)
```python theme={null}
from velt_py.models.workspace import GetActivityConfigRequest
result = sdk.api.workspace.getActivityConfig(GetActivityConfigRequest())
```
#### `updateActivityConfig`
* Updates the activity logs config.
* Params: `UpdateActivityConfigRequest` (from `velt_py.models.workspace`)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse)
```python theme={null}
from velt_py.models.workspace import UpdateActivityConfigRequest
result = sdk.api.workspace.updateActivityConfig(
UpdateActivityConfigRequest(activityServiceConfig={'isEnabled': True})
)
```
#### `getAdvancedWebhookConfig`
* Gets the advanced (Svix) webhook config.
* Params: `GetAdvancedWebhookConfigRequest` (from `velt_py.models.workspace`)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse)
```python theme={null}
from velt_py.models.workspace import GetAdvancedWebhookConfigRequest
result = sdk.api.workspace.getAdvancedWebhookConfig(GetAdvancedWebhookConfigRequest())
```
#### `updateAdvancedWebhookConfig`
* Updates the advanced (Svix) webhook config.
* Params: `UpdateAdvancedWebhookConfigRequest` (from `velt_py.models.workspace`)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse)
```python theme={null}
from velt_py.models.workspace import UpdateAdvancedWebhookConfigRequest
result = sdk.api.workspace.updateAdvancedWebhookConfig(
UpdateAdvancedWebhookConfigRequest(isEnabled=True)
)
```
#### `getAdvancedWebhookEndpoints`
* Lists advanced webhook endpoints.
* Params: `GetAdvancedWebhookEndpointsRequest` (from `velt_py.models.workspace`)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse)
```python theme={null}
from velt_py.models.workspace import GetAdvancedWebhookEndpointsRequest
result = sdk.api.workspace.getAdvancedWebhookEndpoints(GetAdvancedWebhookEndpointsRequest())
```
#### `createAdvancedWebhookEndpoint`
* Creates an advanced webhook endpoint.
* Params: `CreateAdvancedWebhookEndpointRequest` (from `velt_py.models.workspace`)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse)
```python theme={null}
from velt_py.models.workspace import CreateAdvancedWebhookEndpointRequest
result = sdk.api.workspace.createAdvancedWebhookEndpoint(
CreateAdvancedWebhookEndpointRequest(url='https://example.com/webhook')
)
```
#### `updateAdvancedWebhookEndpoint`
* Updates an advanced webhook endpoint.
* Params: `UpdateAdvancedWebhookEndpointRequest` (from `velt_py.models.workspace`)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse)
```python theme={null}
from velt_py.models.workspace import UpdateAdvancedWebhookEndpointRequest
result = sdk.api.workspace.updateAdvancedWebhookEndpoint(
UpdateAdvancedWebhookEndpointRequest(endpointId='endpoint-1', url='https://example.com/webhook/v2')
)
```
#### `deleteAdvancedWebhookEndpoint`
* Deletes an advanced webhook endpoint.
* Params: `DeleteAdvancedWebhookEndpointRequest` (from `velt_py.models.workspace`)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse)
```python theme={null}
from velt_py.models.workspace import DeleteAdvancedWebhookEndpointRequest
result = sdk.api.workspace.deleteAdvancedWebhookEndpoint(
DeleteAdvancedWebhookEndpointRequest(endpointId='endpoint-1')
)
```
#### `getAdvancedWebhookEndpointSecret`
* Gets an advanced webhook endpoint's signing secret.
* Params: `GetAdvancedWebhookEndpointSecretRequest` (from `velt_py.models.workspace`)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse)
```python theme={null}
from velt_py.models.workspace import GetAdvancedWebhookEndpointSecretRequest
result = sdk.api.workspace.getAdvancedWebhookEndpointSecret(
GetAdvancedWebhookEndpointSecretRequest(endpointId='endpoint-1')
)
```
#### `ensureWorkspaceAuthToken`
* Ensures a workspace auth token exists (workspace-scoped).
* Params: `EnsureWorkspaceAuthTokenRequest` (from `velt_py.models.workspace`)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse)
```python theme={null}
from velt_py.models.workspace import EnsureWorkspaceAuthTokenRequest
result = sdk.api.workspace.ensureWorkspaceAuthToken(EnsureWorkspaceAuthTokenRequest())
```
### Workflow
A new service for the Review Workflow Builder / workflow orchestration: definitions, executions, lifecycle events, and step resolution (`/v2/workflow/*`). 14 methods. Request types are imported from `velt_py.models.workflow`.
```python theme={null}
from velt_py.models.workflow import (
CreateWorkflowDefinitionRequest, GetWorkflowDefinitionRequest, ListWorkflowDefinitionsRequest,
DispatchExecutionRequest, GetExecutionRequest, ListExecutionsRequest,
ResolveStepRequest, RecordReviewerDecisionRequest
)
```
#### `createDefinition`
* Creates a workflow definition.
* Params: `CreateWorkflowDefinitionRequest` (from `velt_py.models.workflow`)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse)
* Every `human` node needs at least one outgoing edge with `on: 'reject'`, either a forward reject route or a reject back-edge. Definitions that omit it are rejected.
> [!WARNING]
>
> **`loops` is deprecated.** Loop regions are no longer part of the workflow definition contract. The field is still accepted for backward compatibility but is stripped before the request is sent, and setting it raises a `DeprecationWarning`. Express loops as edges instead — an `on: 'reject'` back-edge carrying a `loop` object:
>
> ```python theme={null}
> edges=[{'from': 'review', 'to': 'draft', 'on': 'reject', 'loop': {'maxIterations': 3}}]
> ```
```python theme={null}
result = sdk.api.workflow.createDefinition(
CreateWorkflowDefinitionRequest(
definitionId='doc-approval', name='Document Approval',
nodes=[
{'nodeId': 'review', 'type': 'human', 'config': {'reviewers': [{'userId': 'reviewer-1', 'mandatory': True}]}},
{'nodeId': 'rework', 'type': 'agent', 'config': {'agentId': '__mock__', 'urlPath': 'documentUrl'}}
],
edges=[{'from': 'review', 'to': 'rework', 'on': 'reject'}]
)
)
```
#### `updateDefinition`
* Updates a workflow definition. Supports optimistic concurrency via `ifVersion`.
* Params: `UpdateWorkflowDefinitionRequest` (from `velt_py.models.workflow`)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse)
```python theme={null}
from velt_py.models.workflow import UpdateWorkflowDefinitionRequest
result = sdk.api.workflow.updateDefinition(
UpdateWorkflowDefinitionRequest(
definitionId='doc-approval',
name='Document Approval v2',
nodes=[
{'nodeId': 'review', 'type': 'human', 'config': {'reviewers': [{'userId': 'reviewer-1', 'mandatory': True}]}},
{'nodeId': 'rework', 'type': 'agent', 'config': {'agentId': '__mock__', 'urlPath': 'documentUrl'}}
],
edges=[{'from': 'review', 'to': 'rework', 'on': 'reject'}],
ifVersion=1
)
)
```
#### `deleteDefinition`
* Deletes a workflow definition.
* Params: `DeleteWorkflowDefinitionRequest` (from `velt_py.models.workflow`)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse)
```python theme={null}
from velt_py.models.workflow import DeleteWorkflowDefinitionRequest
result = sdk.api.workflow.deleteDefinition(
DeleteWorkflowDefinitionRequest(definitionId='doc-approval')
)
```
#### `getDefinition`
* Gets a workflow definition.
* Params: `GetWorkflowDefinitionRequest` (from `velt_py.models.workflow`)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse)
```python theme={null}
result = sdk.api.workflow.getDefinition(GetWorkflowDefinitionRequest(definitionId='doc-approval'))
```
#### `listDefinitions`
* Lists workflow definitions.
* Params: `ListWorkflowDefinitionsRequest` (from `velt_py.models.workflow`)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse)
```python theme={null}
result = sdk.api.workflow.listDefinitions(ListWorkflowDefinitionsRequest(pageSize=20))
```
#### `dispatchExecution`
* Dispatches a workflow execution.
* Params: `DispatchExecutionRequest` (from `velt_py.models.workflow`)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse)
```python theme={null}
result = sdk.api.workflow.dispatchExecution(
DispatchExecutionRequest(definitionId='doc-approval', idempotencyKey='order-12345', triggerContext={'orderId': '12345'})
)
```
#### `cancelExecution`
* Cancels a workflow execution.
* Params: `CancelExecutionRequest` (from `velt_py.models.workflow`)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse)
```python theme={null}
from velt_py.models.workflow import CancelExecutionRequest
result = sdk.api.workflow.cancelExecution(CancelExecutionRequest(executionId='execution-id'))
```
#### `getExecution`
* Gets a workflow execution.
* Params: `GetExecutionRequest` (from `velt_py.models.workflow`)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse)
```python theme={null}
result = sdk.api.workflow.getExecution(GetExecutionRequest(executionId='execution-id'))
```
#### `getExecutionEvents`
* Gets lifecycle events for an execution (paginated).
* Params: `GetExecutionEventsRequest` (from `velt_py.models.workflow`)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse)
```python theme={null}
from velt_py.models.workflow import GetExecutionEventsRequest
result = sdk.api.workflow.getExecutionEvents(
GetExecutionEventsRequest(executionId='execution-id', pageSize=50)
)
```
#### `listExecutions`
* Lists workflow executions.
* Params: `ListExecutionsRequest` (from `velt_py.models.workflow`)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse)
```python theme={null}
result = sdk.api.workflow.listExecutions(
ListExecutionsRequest(definitionId='doc-approval', status='running')
)
```
#### `cancelStep`
* Cancels a step within an execution.
* Params: `CancelStepRequest` (from `velt_py.models.workflow`)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse)
```python theme={null}
from velt_py.models.workflow import CancelStepRequest
result = sdk.api.workflow.cancelStep(
CancelStepRequest(executionId='execution-id', stepId='step-id', actorId='admin-1')
)
```
#### `resolveStep`
* Resolves a step (admin/reviewer override).
* Params: `ResolveStepRequest` (from `velt_py.models.workflow`)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse)
```python theme={null}
result = sdk.api.workflow.resolveStep(
ResolveStepRequest(executionId='execution-id', stepId='step-id', action='force-approve', actorId='admin-1')
)
```
#### `recordAgentResolution`
* Records an agent resolution against a blocking-agent step.
* Params: `RecordAgentResolutionRequest` (from `velt_py.models.workflow`)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse)
```python theme={null}
from velt_py.models.workflow import RecordAgentResolutionRequest
result = sdk.api.workflow.recordAgentResolution(
RecordAgentResolutionRequest(executionId='execution-id', stepId='step-id', responseId='response-1', resolution='resolved', actorId='agent-1')
)
```
#### `recordReviewerDecision`
* Records a reviewer decision against a human step.
* Params: `RecordReviewerDecisionRequest` (from `velt_py.models.workflow`)
* Returns: [VeltApiResponse](/docs/api-reference/sdk/models/data-models#veltapiresponse)
```python theme={null}
result = sdk.api.workflow.recordReviewerDecision(
RecordReviewerDecisionRequest(executionId='execution-id', stepId='step-id', reviewerId='reviewer-1', decision='approve')
)
```
### Data Isolation
Every `sdk.api.*` method requires an `organizationId` in its request payload. Velt's API enforces data isolation server-side — requests without a valid `organizationId` will be rejected.
## Error Handling
The SDK raises typed exceptions for different failure modes. All exceptions extend `VeltSDKError`.
| Exception | When raised |
| - | - |
| `VeltSDKError` | Base class; catch for any SDK-level error |
| `VeltValidationError` | SDK-level validation (e.g., missing required config); `sdk.api.*` methods do not validate request payloads locally |
| `VeltTokenError` | Token generation or authentication failure |
| `VeltApiError` | REST API errors (network failures, unexpected responses) |
```python theme={null}
from velt_py.exceptions import VeltSDKError, VeltApiError
try:
result = sdk.api.organizations.addOrganizations(
AddOrganizationsRequest(organizations=[{'organizationId': 'org-123'}])
)
except VeltApiError as e:
print(f'API error: {e.message}')
except VeltSDKError as e:
print(f'SDK error: {e.message}')
```
Import path: `from velt_py.exceptions import VeltSDKError, VeltValidationError, VeltTokenError, VeltApiError`
Common self-hosting error codes returned in the response `errorCode` field:
* `INVALID_INPUT` — Request data is malformed or missing required fields
* `INTERNAL_ERROR` — Server-side error during processing
* `NOT_FOUND` — Requested resource was not found
## Data Models
Python-SDK-specific dataclasses used by the self-hosting backend. These are not in the shared API reference because they are only relevant to `sdk.selfHosting.*` implementations.
### `PartialCommentAnnotation`
Represents a partial update payload for a comment annotation. Starting in **v0.1.10**, `from`, `assignedTo`, `targetTextRange`, and `resolvedByUserId` are first-class typed fields (previously silent pass-through via `extra_fields`). Starting in **v0.2.2**, `context` is typed too: Velt client 6.0.17+ sends the TipTap anchor text as `context.textEditorConfig.text`, and the SDK stores and returns the object unchanged. Read it as `annotation.context` instead of `annotation.extra_fields['context']`.
```python theme={null}
from velt_py.models import (
PartialCommentAnnotation,
PartialTargetTextRange,
PartialUser,
PartialComment,
BaseMetadata,
)
from velt_py.models.comment import UNSET
@dataclass
class PartialCommentAnnotation:
annotationId: str
metadata: Optional[BaseMetadata] = None
comments: Optional[Dict[str, PartialComment]] = None
from_: Optional[PartialUser] = None # 'from' on the wire; from_ avoids Python keyword.
assignedTo: Optional[PartialUser] = None
targetTextRange: Optional[PartialTargetTextRange] = None
resolvedByUserId: Any = UNSET # Tri-state: UNSET | None | str. See below.
extra_fields: Optional[Dict[str, Any]] = None # Catch-all for customer-configured custom keys.
```
**Field notes**
* `from_` — Python alias for the JSON key `from` (reserved keyword). Serialized as `from` in the Mongo document.
* `assignedTo` — Typed as `PartialUser`. Omit to leave unchanged; the Mongo write skips the field when `None`.
* `targetTextRange` — Typed `PartialTargetTextRange` for the selected text snippet a comment is anchored to.
* `resolvedByUserId` — See [UNSET sentinel](#unset-sentinel) for the difference between absent (`UNSET`) and explicit `None`.
* `extra_fields` — Retained as a catch-all because the frontend contract includes `[key: string]: any` for customer-configured `fieldsToRemove` and `additionalFields`.
### `PartialReactionAnnotation`
Represents a partial update payload for a reaction annotation. Starting in **v0.1.12**, the reaction-author field is `from_` (wire key `from`), replacing the former `user` field — aligning with the velt-sdk contract and `PartialCommentAnnotation`.
```python theme={null}
from velt_py.models.reaction import PartialReactionAnnotation
from velt_py.models.user import PartialUser
@dataclass
class PartialReactionAnnotation:
annotationId: str
metadata: Optional[BaseMetadata] = None
icon: Optional[str] = None
from_: Optional[PartialUser] = None # 'from' on the wire; from_ avoids the Python keyword. Replaces the former 'user' field.
extra_fields: Optional[Dict[str, Any]] = None # Catch-all for customer-configured custom keys.
```
**Field notes**
* `from_` — Python alias for the JSON key `from` (reserved keyword); serialized as `from`. Replaces the former `user` field (renamed in v0.1.12 to match the velt-sdk contract and the comment models). Constructing with `user=` no longer works — use `from_=`.
* Backward-compatible reads: `from_dict()` accepts either the canonical `from` key or the legacy `user` key (`from` wins when both are present) and populates `from_`. `to_dict()` always emits `from`. No data migration is required for reaction documents already stored under `user`.
```python theme={null}
# Legacy document stored under the old `user` key still resolves:
ann = PartialReactionAnnotation.from_dict({'annotationId': 'r-1', 'icon': '+1', 'user': {'userId': 'u-legacy'}})
ann.from_.userId # 'u-legacy'
ann.to_dict()['from'] # {'userId': 'u-legacy'} (re-serialized as `from`)
```
```python theme={null}
# Before (v0.1.11 and earlier):
PartialReactionAnnotation(annotationId='r-1', icon='+1', user=PartialUser(userId='u-1')) # -> {'user': {...}}
# After (v0.1.12):
PartialReactionAnnotation(annotationId='r-1', icon='+1', from_=PartialUser(userId='u-1')) # -> {'from': {...}}
```
### `PartialTargetTextRange`
Anchors a comment to a selected text snippet.
```python theme={null}
from velt_py.models import PartialTargetTextRange
@dataclass
class PartialTargetTextRange:
text: str = '' # The selected text content.
```
### UNSET Sentinel
`UNSET` is a sentinel value exported from `velt_py.models.comment`. It signals that a field was not included in the incoming request payload and should be skipped entirely during the MongoDB write.
```python theme={null}
from velt_py.models.comment import UNSET
# Field absent from payload → UNSET → field is NOT written to Mongo
annotation = PartialCommentAnnotation()
# annotation.resolvedByUserId is UNSET → Mongo $set will not include this field
# Field explicitly set to None → None → field IS written as null to Mongo
annotation = PartialCommentAnnotation(resolvedByUserId=None)
# annotation.resolvedByUserId is None → Mongo $set writes null (frontend unresolve action)
```
| Value | Payload | Mongo write |
| - | - | - |
| `UNSET` | Field absent | Field skipped — no change |
| `None` | Field present, value `null` | Field written as `null` |
### `BaseMetadata`
Base metadata attached to every comment annotation. Starting in **v0.1.10**, `sdkVersion` and `documentMetadata` are fully modeled and preserved in database writes. These fields were previously sent by the frontend on every annotation save but silently dropped.
```python theme={null}
@dataclass
class BaseMetadata:
apiKey: Optional[str] = None
documentId: Optional[str] = None
clientDocumentId: Optional[str] = None
organizationId: Optional[str] = None
clientOrganizationId: Optional[str] = None
folderId: Optional[str] = None
veltFolderId: Optional[str] = None
documentMetadata: Optional[Dict[str, Any]] = None # New in v0.1.10.
sdkVersion: Optional[str] = None # New in v0.1.10.
```
No import change is required — `BaseMetadata` is populated automatically from the incoming request payload. The fix applies transparently to all `saveComments` calls.
### `VerifyTokenResult`
Structured result returned by [`sdk.selfHosting.verifyToken`](#resolver-token-verification). New in **v0.1.14**. Module: `velt_py.models.resolver_auth`; exported from `velt_py` and `velt_py.models`.
```python theme={null}
from velt_py.models import VerifyTokenResult
@dataclass
class VerifyTokenResult:
verified: bool
claims: Optional[Dict] = None
error: Optional[str] = None
errorCode: Optional[str] = None
```
**Field notes**
* `verified` — `True` only when a token was present and fully verified, or a custom callback returned non-`None` claims.
* `claims` — Decoded payload when verified; otherwise `None`.
* `error` — Generic, code-based message; never contains the token or secret.
* `errorCode` — One of: `MISSING_TOKEN`, `EXPIRED`, `INVALID_SIGNATURE`, `CLAIM_MISMATCH`, `ALGORITHM_NOT_ALLOWED`, `KEY_RESOLUTION_FAILED`, `VERIFICATION_FAILED`, `NOT_CONFIGURED`, `DEPENDENCY_MISSING`.
### `CommentResolverSaveEvent`
Enum of comment save-resolver actions the frontend forwards to your save handler. New in **v0.1.14**. A `(str, Enum)` exported from `velt_py` and `velt_py.models`; wire values are byte-identical to the upstream frontend enum.
```python theme={null}
from velt_py import CommentResolverSaveEvent
from velt_py.models import CommentResolverSaveEvent # same class
```
| Member | Wire value |
| - | - |
| `STATUS_CHANGE` | `comment_annotation.status_change` |
| `PRIORITY_CHANGE` | `comment_annotation.priority_change` |
| `ASSIGN` | `comment_annotation.assign` |
| `ACCESS_MODE_CHANGE` | `comment_annotation.access_mode_change` |
| `CUSTOM_LIST_CHANGE` | `comment_annotation.custom_list_change` |
| `APPROVE` | `comment_annotation.approve` |
| `ACCEPT` | `comment.accept` |
| `REJECT` | `comment.reject` |
| `SUGGESTION_ACCEPT` | `comment_annotation.suggestion_accept` |
| `SUGGESTION_REJECT` | `comment_annotation.suggestion_reject` |
| `REACTION_ADD` | `comment.reaction_add` |
| `REACTION_DELETE` | `comment.reaction_delete` |
| `SUBSCRIBE` | `comment_annotation.subscribe` |
| `UNSUBSCRIBE` | `comment_annotation.unsubscribe` |
**Parse order** — `SaveCommentResolverRequest.from_dict` tries `ResolverActions` FIRST (preserving every existing value), then `CommentResolverSaveEvent`, then keeps the raw string for unknown future values.
**Distinctness** — `CommentResolverSaveEvent.REACTION_ADD` (`comment.reaction_add`) is distinct from `ResolverActions.REACTION_ADD` (`reaction.add`, the reaction-resolver action); the parse order routes each correctly.
### `SaveCommentResolverRequest`
The full shared shape is documented in the [API reference](/docs/api-reference/sdk/models/data-models#savecommentresolverrequest). This entry covers only the **v0.1.14** additions — additive; existing payloads parse byte-identically.
```python theme={null}
from velt_py import SaveCommentResolverRequest, CommentResolverSaveEvent
request = SaveCommentResolverRequest.from_dict(data)
if request.targetComment is not None:
print(request.targetComment.commentId) # request context only; not written to your database
sdk.selfHosting.comments.saveComments(request)
```
**Field notes**
* `targetComment: Optional[PartialComment]` — The comment the action occurred on, resolved by the frontend from `commentId`. `from_dict` parses it fail-open (a malformed/partial dict never raises). `to_dict` emits it only when not `None`. `saveComments` NEVER persists it (request context only).
* `event: Optional[Union[ResolverActions, CommentResolverSaveEvent, str]]` — Widened. Every existing `ResolverActions` value still parses to the same member. Parse order: `ResolverActions` first, then [`CommentResolverSaveEvent`](#commentresolversaveevent), then raw string for unknown future values.
## Resources
* [Velt-Py PyPI Package](https://pypi.org/project/velt-py)
* [Partial Self Hosting Documentation](/docs/self-hosting/partial/overview)
# Advanced Setup
Source: https://velt.dev/docs/get-started/advanced
Optional advanced configuration options for Velt SDK
Explore optional advanced configuration options to enhance your Velt implementation with locations, contacts, and initialization state detection.
## Locations
Users logged into the same **Document** ID can see each other's `Presence`, `Cursors`, `Comments` etc.
However, if you want to add another layer of categorization to organize users together, you can use **Location**.
> [!TIP]
>
> If a **Document** is like a house, a **Location** is like a room within the house.
To learn more about `Locations`, check out its dedicated section [here](/docs/key-concepts/overview#locations).
## Contacts
When you reply to a comment, you can `@mention` other teammates that are added to a `User's Contacts List`.
To learn more about creating a `User's Contacts List`, [read here](/docs/key-concepts/overview#contact-list).
## JWT Authentication Tokens
For enhanced security, you can use JWT tokens to authenticate users instead of passing user data directly in the client-side code. This provides an additional layer of security by verifying user identity on the server side.
> [!TIP]
>
> After authentication, retrieve the current user object anytime using [`getCurrentUser()`](/docs/api-reference/sdk/api/api-methods#getcurrentuser) or [`useCurrentUser()`](/docs/api-reference/sdk/api/react-hooks#usecurrentuser).
> [!NOTE]
>
> Access control roles (Editor/Viewer): You can assign a user's role per resource (organization, folder, document) in the token permissions or via backend access APIs. Editors can create/edit collaboration data (e.g., comments); Viewers are read-only. See [Access Control](/docs/key-concepts/overview#access-control), [Generate Token](/docs/api-reference/rest-apis/v2/auth/generate-token), [Add Permissions](/docs/api-reference/rest-apis/v2/auth/add-permissions), and [Add/Update Users](/docs/api-reference/rest-apis/v2/users/add-users).
> [!WARNING]
>
> **Critical JWT Token Requirements:**
>
> * JWT tokens must be generated server-side using your auth token from the Velt Console
> * Never expose JWT tokens or auth tokens in client-side code
> * Tokens expire after 48 hours and need to be refreshed
> * Include the JWT token in the `authToken` field when calling `identify()`
### Step 1: Enable JWT Tokens in Console
First, enable JWT tokens in your Velt Console:
1. Go to [console.velt.dev](https://console.velt.dev/dashboard/config/general)
2. Enable the toggle for `Require JWT Token` (listed at the bottom of the page)
> [!WARNING]
>
> JWT tokens won't work unless you enable this setting in your console.
### Step 2: Generate Auth Token
You need an auth token to generate JWT tokens. You can generate this from the **Auth Token** section in your Velt Console dashboard.

> [!WARNING]
>
> Store auth tokens securely on your server-side environment and never expose them in client-side code.
> [!TIP]
>
> Auth tokens are long-lived and should be rotated periodically for security best practices.
### Step 3: Create Server Endpoint for JWT Token Generation
Create a server endpoint that generates and serves JWT tokens to your client.
See our [generate_token API call](/docs/api-reference/rest-apis/v2/auth/generate-token) for more information.
```js Node.js Server Endpoint expandable lines theme={null}
const express = require('express');
const app = express();
const PORT = 8080;
// Your credentials from Velt Console
const VELT_API_KEY = "YOUR_VELT_API_KEY";
const VELT_AUTH_TOKEN = "your-generated-auth-token-from-console";
async function generateVeltJWTToken(userId, config = {}) {
const url = "https://api.velt.dev/v2/auth/generate_token";
// Note: the request body must be wrapped in a top-level `data` object.
// `organizationId` belongs in `permissions.resources[]`, not in `userProperties`.
const body = {
data: {
userId: userId,
userProperties: {
name: config.name,
email: config.email,
isAdmin: config.isAdmin || false
},
permissions: config.organizationId
? {
resources: [
{ type: "organization", id: config.organizationId }
]
}
: undefined
}
};
try {
const response = await fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
"x-velt-api-key": VELT_API_KEY,
"x-velt-auth-token": VELT_AUTH_TOKEN
},
body: JSON.stringify(body),
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
return data?.result?.data?.token;
} catch (error) {
console.error("Error generating JWT token:", error);
throw error;
}
}
// Endpoint to generate JWT tokens
app.get('/generate-velt-jwt-token', async (req, res) => {
try {
const { userId, organizationId, name, email, isAdmin } = req.query;
const token = await generateVeltJWTToken(userId, {
organizationId,
name,
email,
isAdmin: isAdmin === 'true'
});
res.json({ token });
} catch (error) {
res.status(500).json({ error: 'Failed to generate token' });
}
});
app.listen(PORT, () => {
console.log(`JWT Server listening on port ${PORT}`);
});
```
```python Python Server Endpoint expandable lines theme={null}
from flask import Flask, request, jsonify
import requests
app = Flask(__name__)
# Your credentials from Velt Console
VELT_AUTH_TOKEN = "your-generated-auth-token-from-console"
VELT_API_KEY = "YOUR_VELT_API_KEY"
def generate_velt_jwt_token(user_id, config=None):
url = "https://api.velt.dev/v2/auth/generate_token"
if config is None:
config = {}
# Note: the request body must be wrapped in a top-level `data` object.
# `organizationId` belongs in `permissions.resources[]`, not in `userProperties`.
data_payload = {
"userId": user_id,
"userProperties": {
"name": config.get("name"),
"email": config.get("email"),
"isAdmin": config.get("isAdmin", False)
}
}
if config.get("organizationId"):
data_payload["permissions"] = {
"resources": [
{"type": "organization", "id": config.get("organizationId")}
]
}
body = {"data": data_payload}
try:
response = requests.post(url, json=body, headers={
"Content-Type": "application/json",
"x-velt-api-key": VELT_API_KEY,
"x-velt-auth-token": VELT_AUTH_TOKEN
})
response.raise_for_status()
data = response.json()
return data.get("result", {}).get("data", {}).get("token")
except Exception as error:
print(f"Error generating JWT token: {error}")
raise error
@app.route('/generate-velt-jwt-token', methods=['GET'])
def get_jwt_token():
try:
user_id = request.args.get('userId')
organization_id = request.args.get('organizationId')
name = request.args.get('name')
email = request.args.get('email')
is_admin = request.args.get('isAdmin') == 'true'
token = generate_velt_jwt_token(user_id, {
"organizationId": organization_id,
"name": name,
"email": email,
"isAdmin": is_admin
})
return jsonify({"token": token})
except Exception as error:
return jsonify({"error": "Failed to generate token"}), 500
if __name__ == '__main__':
app.run(port=8080)
```
```ruby Ruby Server Endpoint expandable lines theme={null}
require 'sinatra'
require 'net/http'
require 'json'
# Your credentials from Velt Console
VELT_AUTH_TOKEN = "your-generated-auth-token-from-console"
VELT_API_KEY = "YOUR_VELT_API_KEY"
def generate_velt_jwt_token(user_id, config = {})
url = URI("https://api.velt.dev/v2/auth/generate_token")
# Note: the request body must be wrapped in a top-level `data` object.
# `organizationId` belongs in `permissions.resources[]`, not in `userProperties`.
data_payload = {
userId: user_id,
userProperties: {
name: config[:name],
email: config[:email],
isAdmin: config[:isAdmin] || false
}
}
if config[:organizationId]
data_payload[:permissions] = {
resources: [
{ type: 'organization', id: config[:organizationId] }
]
}
end
body = { data: data_payload }
begin
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
request = Net::HTTP::Post.new(url)
request["Content-Type"] = "application/json"
request["x-velt-api-key"] = VELT_API_KEY
request["x-velt-auth-token"] = VELT_AUTH_TOKEN
request.body = body.to_json
response = http.request(request)
unless response.is_a?(Net::HTTPSuccess)
raise "HTTP error! status: #{response.code}"
end
data = JSON.parse(response.body)
data.dig("result", "data", "token")
rescue => error
puts "Error generating JWT token: #{error}"
raise error
end
end
get '/generate-velt-jwt-token' do
begin
user_id = params['userId']
organization_id = params['organizationId']
name = params['name']
email = params['email']
is_admin = params['isAdmin'] == 'true'
token = generate_velt_jwt_token(user_id, {
organizationId: organization_id,
name: name,
email: email,
isAdmin: is_admin
})
{ token: token }.to_json
rescue => error
status 500
{ error: "Failed to generate token" }.to_json
end
end
```
```php PHP Server Endpoint expandable lines theme={null}
$userId,
"userProperties" => [
"name" => $config["name"] ?? null,
"email" => $config["email"] ?? null,
"isAdmin" => $config["isAdmin"] ?? false
]
];
if (!empty($config["organizationId"])) {
$dataPayload["permissions"] = [
"resources" => [
["type" => "organization", "id" => $config["organizationId"]]
]
];
}
$body = ["data" => $dataPayload];
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'x-velt-api-key: ' . $VELT_API_KEY,
'x-velt-auth-token: ' . $VELT_AUTH_TOKEN
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if (curl_errno($ch) || $httpCode !== 200) {
throw new Exception("HTTP error! status: {$httpCode}");
}
curl_close($ch);
$data = json_decode($response, true);
return $data["result"]["data"]["token"] ?? null;
}
if ($_SERVER['REQUEST_METHOD'] === 'GET' && $_SERVER['REQUEST_URI'] === '/generate-velt-jwt-token') {
try {
$userId = $_GET['userId'] ?? null;
$organizationId = $_GET['organizationId'] ?? null;
$name = $_GET['name'] ?? null;
$email = $_GET['email'] ?? null;
$isAdmin = ($_GET['isAdmin'] ?? 'false') === 'true';
$token = generateVeltJWTToken($userId, [
"organizationId" => $organizationId,
"name" => $name,
"email" => $email,
"isAdmin" => $isAdmin
]);
header('Content-Type: application/json');
echo json_encode(["token" => $token]);
} catch (Exception $error) {
http_response_code(500);
echo json_encode(["error" => "Failed to generate token"]);
}
}
?>
```
## Token Refresh
JWT tokens expire after 48 hours from generation. Handle token expiration by subscribing to the error event and refreshing tokens when needed:
> [!NOTE]
>
> If you configured an **Auth Provider** on `VeltProvider`, token refresh is handled automatically. If you authenticate using the **identify()** method instead, you must listen for `token_expired` and re-authenticate with a fresh token as shown below.
```jsx React Token Refresh theme={null}
import { useVeltEventCallback } from "@veltdev/react";
export default function AuthComponent() {
const errorEvent = useVeltEventCallback('error');
useEffect(() => {
if (errorEvent?.code === "token_expired") {
// Generate new JWT token from your server
fetch("/api/auth/refresh-token")
.then(res => res.json())
.then(data => {
// Re-authenticate with new token
useIdentify(user, { authToken: data.newToken });
});
}
}, [errorEvent]);
return Authentication Component
;
}
```
```js Other Frameworks Token Refresh theme={null}
// Subscribe to error events to handle token expiration
client.on('error').subscribe((error) => {
if (error?.code === "token_expired") {
// Generate new JWT token from your server
fetch("/api/auth/refresh-token")
.then(res => res.json())
.then(data => {
// Re-authenticate with new token
client.identify(user, { authToken: data.newToken });
});
}
});
```
> [!NOTE]
>
> **Security Benefits of JWT Tokens:**
>
> * Server-side validation of user identity
> * Protection against client-side data manipulation
> * Secure user authentication without exposing sensitive data
> * Token expiration for enhanced security
## Error Handling in Authentication
By default, authentication methods like `identify()` and `setVeltAuthProvider()` return `null` when authentication fails. You can configure these methods to throw errors instead by setting `throwError: true` in the options parameter.
> [!NOTE]
>
> When `throwError` is enabled, failed authentication attempts will throw an error that you can catch and handle, providing more control over error handling in your application.
> [tab] React / Next.js
>
> ```jsx theme={null}
> import { useIdentify, useVeltClient } from '@veltdev/react';
>
> export default function AuthComponent({ user }) {
> const { client } = useVeltClient();
>
> // Using Promise-based approach
> const handleAuthWithPromise = () => {
> client.identify(user, {
> throwError: true, // Throws error if authentication fails
> }).then((authenticatedUser) => {
> // User is authenticated
> console.log('Authenticated:', authenticatedUser);
> }).catch((err) => {
> // Handle authentication error
> console.error('Authentication failed:', err);
> });
> };
>
> // Using async/await approach
> const handleAuthWithAsync = async () => {
> try {
> const authenticatedUser = await client.identify(user, {
> throwError: true, // Throws error if authentication fails
> });
> // User is authenticated
> console.log('Authenticated:', authenticatedUser);
> } catch (err) {
> // Handle authentication error
> console.error('Authentication failed:', err);
> }
> };
>
> // Using setVeltAuthProvider
> useEffect(() => {
> if (client) {
> client.setVeltAuthProvider({
> user,
> options: {
> throwError: true, // Throws error if authentication fails
> },
> onError: (err) => {
> // Handle authentication error
> console.error('Auth provider error:', err);
> }
> });
> }
> }, [client]);
>
> return Authentication Component
;
> }
> ```
> [tab] Other Frameworks
>
> ```html theme={null}
>
> ```
> [!NOTE]
>
> * Default value: `false` (returns `null` on authentication failure)
> * Set to `true` to receive errors that can be caught with `.catch()` or `try/catch` blocks
> * Useful for implementing custom error handling and recovery flows
## Velt Client
Access the core Velt client instance to call SDK APIs and subscribe to core events.
* [API reference →](/docs/api-reference/sdk/api/api-methods#get-velt-client)
### Event Subscriptions
| Event | Description | Event Object |
| - | - | - |
| `initUpdate` | Initialization lifecycle updates (documents/locations set/unset, user init) | [InitUpdateEvent](/docs/api-reference/sdk/models/data-models#initupdateevent) |
| `userUpdate` | Fired when the Velt user changes (login, logout, or update) | [UserUpdateEvent](/docs/api-reference/sdk/models/data-models#userupdateevent) |
| `documentInit` | Document initialization status changes | [DocumentInitEvent](/docs/api-reference/sdk/models/data-models#documentinitevent) |
| `error` | Error events (e.g., token_expired) | [ErrorEvent](/docs/api-reference/sdk/models/data-models#errorevent) |
| `veltButtonClick` | Fired when a Velt Button is clicked | [VeltButtonClickEvent](/docs/api-reference/sdk/models/data-models#veltbuttonclickevent) |
| `permissionProvider` | Permission Provider events for access requests, results, and errors | [PermissionProviderEvent](/docs/api-reference/sdk/models/data-models#permissionproviderevent) |
| `dataProvider` | Data Provider events for debugging get, save, and delete operations. Includes [UserResolverEvent](/docs/api-reference/sdk/models/data-models#userresolverevent), [CommentResolverEvent](/docs/api-reference/sdk/models/data-models#commentresolverevent), [AttachmentResolverEvent](/docs/api-reference/sdk/models/data-models#attachmentresolverevent), [ReactionResolverEvent](/docs/api-reference/sdk/models/data-models#reactionresolverevent) | [DataProviderEvent](/docs/api-reference/sdk/models/data-models#dataproviderevent) |
> [tab] React / Next.js
>
> ```jsx theme={null}
> import { useEffect } from 'react';
> import { useVeltClient } from '@veltdev/react';
>
> export default function CoreEventsListener() {
> const { client } = useVeltClient();
>
> useEffect(() => {
> if (!client) return;
>
> // Listen to initialization updates
> const initSub = client.on('initUpdate').subscribe((event) => {
> console.log('Init update:', event);
> });
>
> // Listen to token lifecycle errors (e.g., token_expired)
> const errorSub = client.on('error').subscribe((error) => {
> console.log('Velt error:', error);
> });
>
> return () => {
> initSub?.unsubscribe();
> errorSub?.unsubscribe();
> };
> }, [client]);
>
> return null;
> }
> ```
> [tab] Other Frameworks
>
> ```js theme={null}
> async function loadVelt() {
> await Velt.init('YOUR_VELT_API_KEY');
>
> const initSub = Velt.on('initUpdate').subscribe((event) => {
> console.log('Init update:', event);
> });
>
> const errorSub = Velt.on('error').subscribe((error) => {
> console.log('Velt error:', error);
> });
>
> // When done, unsubscribe
> // initSub?.unsubscribe();
> // errorSub?.unsubscribe();
> }
> ```
> [!NOTE]
>
> * Use the React hook `useVeltClient()` inside components rendered under `VeltProvider`.
> * The client is available after initialization. In HTML/vanilla, call `Velt.init()` first.
> * Always unsubscribe from event subscriptions to avoid memory leaks.
### getVeltInitState()
This returns true when both the Velt User and Document are initialized.
> [tab] React
>
> ```jsx React / Next.js with Hooks theme={null}
> import { useVeltInitState } from '@veltdev/react';
>
> export default function MyComponent() {
> const veltInitState = useVeltInitState();
>
> useEffect(() => {
> console.log('Velt Init State:', veltInitState);
> if (veltInitState) {
> // Velt state is initialized, so user can perform any action here
> }
> }, [veltInitState]);
>
> return (
>
> {/* Your component content */}
>
> );
> }
> ```
>
> ```jsx React / Next.js (Non-hooks) theme={null}
> import { useVeltClient } from '@veltdev/react';
>
> export default function MyComponent() {
> const { client } = useVeltClient();
>
> useEffect(() => {
> if (client) {
> const subscription = client.getVeltInitState().subscribe((veltInitState: boolean | undefined) => {
> console.log('Velt Init State:', veltInitState);
> });
>
> return () => subscription?.unsubscribe();
> }
> }, [client]);
>
> return (
>
> {/* Your component content */}
>
> );
> }
> ```
> [tab] Angular
>
> ```jsx Angular Initialization State theme={null}
> import { Component, OnInit, OnDestroy } from '@angular/core';
> import { initVelt } from '@veltdev/client';
>
> @Component({
> selector: 'app-root',
> template: `
`
> })
> export class AppComponent implements OnInit, OnDestroy {
> client: any;
> subscription: any;
>
> async ngOnInit() {
> this.client = await initVelt('YOUR_VELT_API_KEY');
>
> this.subscription = this.client.getVeltInitState().subscribe((veltInitState: boolean | undefined) => {
> console.log('Velt Init State:', veltInitState);
> });
> }
>
> ngOnDestroy() {
> this.subscription?.unsubscribe();
> }
> }
> ```
> [tab] Vue.js
>
> ```js Vue.js Initialization State theme={null}
> import { initVelt } from '@veltdev/client';
>
> export default {
> name: 'App',
> data() {
> return {
> client: null,
> subscription: null
> }
> },
> async mounted() {
> this.client = await initVelt('YOUR_VELT_API_KEY');
>
> this.subscription = this.client.getVeltInitState().subscribe((veltInitState: boolean | undefined) => {
> console.log('Velt Init State:', veltInitState);
> });
> },
> beforeUnmount() {
> this.subscription?.unsubscribe();
> }
> }
> ```
> [tab] HTML
>
> ```js HTML Initialization State theme={null}
> // Subscribe to initialization state
> let subscription = Velt.getVeltInitState().subscribe((veltInitState: boolean | undefined) => {
> console.log('Velt Init State:', veltInitState);
> });
>
> // To unsubscribe
> subscription?.unsubscribe();
> ```
>
> ```html Complete HTML with Init State theme={null}
>
>
>
>
> My App
>
>
>
>
> My Collaborative App
>
>
>
>
> ```
### fetchDebugInfo()
* Use this method to retrieve a one-time snapshot of essential debugging information about your Velt integration. This includes details like SDK version, API key, user, organizationId, documentId, folderId, version, and locations.
* You can also access this diagnostic information through [Velt’s Chrome DevTools extension](https://chromewebstore.google.com/detail/velt-devtools/nfldoicbagllmegffdapcnohakpamlnl).
* Params: None
* Returns: `Promise<`[`VeltDebugInfo`](/docs/api-reference/sdk/models/data-models#veltdebuginfo)`>`
> [tab] React / Next.js
>
> ```jsx theme={null}
> const { client } = useVeltClient();
>
> const handleFetchDebugInfo = async () => {
> const debugInfo = await client.fetchDebugInfo();
> console.log('Debug Info:', debugInfo);
> console.log('SDK Version:', debugInfo.veltVersion);
> console.log('API Key:', debugInfo.apiKey);
> console.log('Server State:', debugInfo.serverMap);
> console.log('Client State:', debugInfo.clientMap);
> };
> ```
> [tab] Other Frameworks
>
> ```javascript theme={null}
> const debugInfo = await Velt.fetchDebugInfo();
> console.log('Debug Info:', debugInfo);
> console.log('SDK Version:', debugInfo.veltVersion);
> console.log('API Key:', debugInfo.apiKey);
> console.log('Server State:', debugInfo.serverMap);
> console.log('Client State:', debugInfo.clientMap);
> ```
### getDebugInfo()
* Use this method to subscribe to real-time updates of debugging information about your Velt integration. This includes details like SDK version, API key, user, organizationId, documentId, folderId, version, and locations.
* You can also access this diagnostic information through [Velt’s Chrome DevTools extension](https://chromewebstore.google.com/detail/velt-devtools/nfldoicbagllmegffdapcnohakpamlnl).
* Params: None
* Returns: `Observable<`[`VeltDebugInfo`](/docs/api-reference/sdk/models/data-models#veltdebuginfo)`>`
> [tab] React / Next.js
>
> ```jsx theme={null}
> const { client } = useVeltClient();
> const [debugInfo, setDebugInfo] = useState(null);
>
> useEffect(() => {
> if (!client) return;
>
> const subscription = client.getDebugInfo().subscribe((info) => {
> setDebugInfo(info);
> console.log('Debug Info Updated:', info);
> });
>
> return () => subscription.unsubscribe();
> }, [client]);
> ```
> [tab] Other Frameworks
>
> ```javascript theme={null}
> const subscription = Velt.getDebugInfo().subscribe((debugInfo) => {
> console.log('Debug Info Updated:', debugInfo);
> console.log('SDK Version:', debugInfo.veltVersion);
> console.log('API Key:', debugInfo.apiKey);
> console.log('Server State:', debugInfo.serverMap);
> console.log('Client State:', debugInfo.clientMap);
> });
>
> // Unsubscribe when done
> subscription.unsubscribe();
> ```
### disableLogs()
Control the verbosity of Velt SDK console logs. By default, the SDK outputs both informational logs and warnings. Use `disableLogs()` to suppress logs at different levels.
| Call | Effect |
| - | - |
| `disableLogs()` | Turns off warnings only |
| `disableLogs({ suppressAll: true })` | Turns off all logs |
| `disableLogs({ warning: false, suppressAll: true })` | Keeps warnings but turns off all other logs |
> [tab] React / Next.js
>
> ```jsx theme={null}
> const { client } = useVeltClient();
>
> // Turn off warnings only
> client.disableLogs();
>
> // Turn off all logs
> client.disableLogs({ suppressAll: true });
>
> // Keep warnings but turn off all other logs
> client.disableLogs({ warning: false, suppressAll: true });
> ```
> [tab] Other Frameworks
>
> ```js theme={null}
> // Turn off warnings only
> Velt.disableLogs();
>
> // Turn off all logs
> Velt.disableLogs({ suppressAll: true });
>
> // Keep warnings but turn off all other logs
> Velt.disableLogs({ warning: false, suppressAll: true });
> ```
### setUnstyledMode()
Turn off Velt's built-in visual styling when you want to style components entirely with your own CSS (headless use). By default, layout and positioning styles are kept so components remain functional. It applies to Velt styles in the page head and inside shadow roots, including styles injected after the call.
**Params:**
* `value`: `boolean` — `true` removes Velt's visual styling; `false` restores it.
* `config?`: `{ keepFunctionalStyles?: boolean }` — defaults to `true`, which keeps layout and positioning styles. Set to `false` to strip down to browser defaults.
> [tab] React / Next.js
>
> ```jsx theme={null}
> const { client } = useVeltClient();
>
> // Remove Velt's visual styling; keep layout/positioning (default)
> client.setUnstyledMode(true);
>
> // Strip everything down to raw browser defaults
> client.setUnstyledMode(true, { keepFunctionalStyles: false });
>
> // Restore all Velt styling
> client.setUnstyledMode(false);
> ```
> [tab] Other Frameworks
>
> ```js theme={null}
> Velt.setUnstyledMode(true);
> Velt.setUnstyledMode(true, { keepFunctionalStyles: false });
> Velt.setUnstyledMode(false);
> ```
> [!NOTE]
>
> Unstyled mode is reversible at any time. See the [API reference](/docs/api-reference/sdk/api/api-methods#setunstyledmode) for details.
### Set Custom Page Info
Attach your own page info (URL, title, path, etc.) to all newly created data (comments, reactions, recordings, presence, cursors). Opt-in; by default page info is derived from the browser. Useful for apps with client-side routing or custom URL schemes. Only newly created data is affected.
**Params:**
* `pageInfo`: [PageInfo](/docs/api-reference/sdk/models/data-models#pageinfo)
* `options?`: `{ documentId?: string }`
> [tab] React / Next.js
>
> ```jsx theme={null}
> import { useSetPageInfo } from '@veltdev/react';
>
> const { setPageInfo } = useSetPageInfo();
> setPageInfo({ url: 'https://app.example.com/doc/42', title: 'Design Doc' });
>
> // Using API
> client.setPageInfo({ url: 'https://app.example.com/doc/42', title: 'Design Doc' });
> ```
> [tab] Other Frameworks
>
> ```js theme={null}
> Velt.setPageInfo({ url: 'https://app.example.com/doc/42', title: 'Design Doc' });
> ```
### Clear Custom Page Info
Revert to the SDK's automatic browser-derived page info for newly created data.
> [tab] React / Next.js
>
> ```jsx theme={null}
> import { useClearPageInfo } from '@veltdev/react';
>
> const { clearPageInfo } = useClearPageInfo();
> clearPageInfo();
>
> // Using API
> client.clearPageInfo();
> ```
> [tab] Other Frameworks
>
> ```js theme={null}
> Velt.clearPageInfo();
> ```
# Overview
Source: https://velt.dev/docs/get-started/agentic-overview
Use AI coding agents to build with Velt. Understand how the installation plugin, UI customization plugin, MCP installer, skills, CLI, and Velt Docs MCP work together.
Velt gives your AI coding agent the knowledge and tools to set up the SDK, add features, and customize the UI correctly the first time. Pick the path that matches what you're doing:
| Tool | What it does |
| - | - |
| **[Installation Plugin](/docs/get-started/installation-plugin)** | One install for Cursor or Claude Code: skills, rules, `velt-expert` agent, and MCP servers for SDK setup and feature work |
| **[MCP Installer](/docs/get-started/mcp-installer)** | Guided Velt setup that scans your codebase, proposes a plan, and walks through install steps |
| **[UI Customization Plugin](/docs/get-started/ui-customization-plugin)** | Turns a Figma design into verified Velt UI customization (comments + notifications) |
| **[Skills](/docs/get-started/skills)** | Implementation rules and patterns your agent follows when writing Velt code |
| **[CLI](/docs/get-started/cli)** | Terminal scaffolding for Next.js (no AI agent required) |
| **[Velt Docs MCP](/docs/get-started/docs-mcp)** | Live docs search when skills don't cover a question |
## How They Fit Together
```
Set up Velt in your app
├── Installation Plugin → full package (recommended)
│ ├── MCP Installer → guided install plan
│ ├── Skills → correct SDK patterns
│ ├── CLI → optional scaffolding
│ └── Docs MCP → fallback docs search
└── or MCP Installer + Skills / CLI on their own
Customize Velt UI to match your design
└── UI Customization Plugin → Figma → plan → build → verify
(requires Velt already installed and rendering)
```
Start with the **Installation Plugin** to get Velt into your app. When the default UI is working, use the **UI Customization Plugin** to match a Figma design. Each piece also works standalone if you only need part of the stack.
## Choose Your Path
> [card] [Installation Plugin (Recommended)](/docs/get-started/installation-plugin)
>
> Full package for Cursor or Claude Code. Installs skills, rules, MCP servers, and the velt-expert agent persona for SDK setup.
> [card] [MCP Installer](/docs/get-started/mcp-installer)
>
> AI-guided setup with codebase scanning. Works with Claude Code, Cursor, Windsurf, and Claude Desktop.
> [card] [UI Customization Plugin](/docs/get-started/ui-customization-plugin)
>
> Figma → verified Velt UI customization for Cursor or Claude Code. Builds CSS, wireframes, or primitives and checks each surface in a live browser.
> [card] [Agent Skills](/docs/get-started/skills)
>
> Install 282 implementation rules for any AI agent. Works with Claude Code, Cursor, GitHub Copilot, and more.
> [card] [Velt Docs MCP](/docs/get-started/docs-mcp)
>
> Search Velt documentation from Claude, Claude Code, Cursor, or VS Code.
> [card] [CLI](/docs/get-started/cli)
>
> Non-interactive, flag-driven scaffolding for Next.js. No AI agent required.
## When to Use What
| Scenario | Use |
| - | - |
| First time setting up Velt with an AI editor | **Installation Plugin** |
| Already set up, adding a new feature | **Skills** (included in the installation plugin) |
| Matching Velt UI to a Figma design | **UI Customization Plugin** |
| Editor without plugin support | **MCP Installer** + **Skills** separately |
| Terminal-only setup, no AI agent | **CLI** |
| Agent can't find the answer in skills | **Velt Docs MCP** |
## What Each Component Provides
### Installation Plugin
Bundles skills, rules, an agent persona, and MCP servers into a single install for Cursor or Claude Code. Use it to set up and extend the Velt SDK. Includes 2 slash-command skills (`/install-velt`, `/velt-help`), 14 bundled agent-skill packages (282 rules), 6 embedded best-practice rules, 1 agent persona (`velt-expert`), and 2 MCP servers.
### MCP Installer
An MCP server that your AI agent uses to run guided Velt setup. It scans your codebase, detects your auth system and document structure, generates an implementation plan, and executes the plan with your approval. Supports both guided mode and CLI-only mode.
### UI Customization Plugin
A separate Cursor / Claude Code plugin that turns a Figma Loop into working Velt UI customization (comments + notifications). It plans per surface, builds CSS / wireframes / primitives, and verifies each result against the design in a live browser. See [UI Customization Plugin](/docs/get-started/ui-customization-plugin). Requires Velt already installed and rendering in your app.
### Skills
Structured knowledge packages containing prioritized rules with correct and incorrect code patterns, verification checklists, and source pointers. Available for 14 Velt feature areas: Setup, Comments, CRDT, Notifications, Recorder, Single Editor Mode, Self-Hosting Data, Activity Logs, Presence, Cursors, Huddle, REST APIs, Proxy Server, and AI Rewriter.
### CLI
A terminal command (`npx @velt-js/add-velt`) that scaffolds Velt into a Next.js project. Installs dependencies, generates components, and wires `VeltProvider` into your app layout. Supports feature flags for comments, notifications, presence, cursors, and CRDT.
### Velt Docs MCP
An MCP server that searches Velt's documentation. Use it as a fallback when skills don't cover your specific question. Available for Claude, Claude Code, Cursor, and VS Code. See [Velt Docs MCP](/docs/get-started/docs-mcp).
# Velt CLI
Source: https://velt.dev/docs/get-started/cli
Use the add-velt CLI to scaffold Velt collaboration features into your Next.js app with a single command.
Add Velt real-time collaboration to an existing Next.js project from your terminal. The CLI installs dependencies, generates components, and auto-wires `VeltProvider` into your app layout. No manual configuration required.
> [card] [GitHub Repository](https://github.com/velt-js/add-velt-next-js)
>
> velt-js/add-velt-next-js
## When to Use the CLI
* You want to add Velt to a Next.js project quickly from the command line
* You prefer a non-interactive, flag-driven workflow
* You want to scaffold specific features (comments, notifications, CRDT) in one step
* You are setting up Velt without an AI coding assistant
> [!NOTE]
>
> If you are using an AI coding agent like Claude Code or Cursor, see the [MCP Installer](/docs/get-started/mcp-installer) for an AI-assisted setup experience.
## Prerequisites
* **Node.js** 18+
* **Next.js** 13.4.0+ (App Router or Pages Router)
* **React** 18.2.0+
* **Package manager**: npm, yarn, or pnpm
* A [Velt API key](https://console.velt.dev)
## Quickstart
Run the CLI in your Next.js project directory:
```bash theme={null}
npx @velt-js/add-velt
```
This installs the baseline Velt SDK (`@veltdev/react`, `@veltdev/types`) and generates core components. To include specific features, add flags:
```bash theme={null}
npx @velt-js/add-velt --comments
```
After the CLI completes, set your API key in `.env.local`:
```bash theme={null}
NEXT_PUBLIC_VELT_API_KEY=your_api_key_here
```
Then update the generated files with your app-specific logic:
1. **`components/velt/VeltInitializeDocument.tsx`**: replace the placeholder document ID with your own (e.g., from a route parameter)
2. **`components/velt/VeltInitializeUser.tsx`**: replace the placeholder user object with your real user context
Start your dev server and verify Velt loads in the browser console.
## Configuration
### API Key
The CLI wires `VeltProvider` to read your API key from the `NEXT_PUBLIC_VELT_API_KEY` environment variable. Add it to `.env.local`:
```bash theme={null}
NEXT_PUBLIC_VELT_API_KEY=your_api_key_here
```
Get your API key from the [Velt Console](https://console.velt.dev).
### Document ID
Update `components/velt/VeltInitializeDocument.tsx` with your document ID source:
```tsx theme={null}
// Replace with your document ID logic
const documentId = 'your-document-id';
const documentName = 'your-document-name';
```
### User Authentication
Update `components/velt/VeltInitializeUser.tsx` with your user retrieval logic:
```tsx theme={null}
// Replace with your user retrieval logic
const user = {
userId: 'user-id',
organizationId: 'organization-id',
email: 'user@example.com',
};
```
## Options
### Feature Flags
| Flag | Description |
| - | - |
| `--comments` | Add inline comments (VeltComments, VeltCommentsSidebar, VeltCursor) |
| `--notifications` | Add notifications (VeltNotificationsTool, VeltCursor) |
| `--presence` | Add presence indicators (VeltPresence) |
| `--cursors` | Add live cursors (VeltCursor) |
> [!NOTE]
>
> The CLI supports core scaffolding features. For additional features like Recorder, Single Editor Mode, Self-Hosting Data, Activity Logs, and Huddle, use the [MCP Installer](/docs/get-started/mcp-installer) with an AI coding agent.
### CRDT Type Flags (choose one)
| Flag | Description |
| - | - |
| `--reactflow-crdt` | Canvas collaboration with ReactFlow |
| `--tiptap-crdt` | Rich text editor collaboration with Tiptap |
| `--codemirror-crdt` | Code editor collaboration with CodeMirror |
### Combined Flag
| Flag | Description |
| - | - |
| `--all` | Enable comments + notifications + CRDT (requires a CRDT type flag) |
### Installation Flags
| Flag | Description |
| - | - |
| `--force`, `-f` | Force overwrite existing files |
| `--legacy-peer-deps` | Use legacy peer deps (npm only) |
| `--help`, `-h` | Show help message |
## What the CLI Does
The CLI performs these steps automatically:
1. **Detects your project**: finds `next.config.js`/`next.config.ts`, determines App Router vs Pages Router, and identifies your package manager (npm, yarn, or pnpm with workspace support)
2. **Installs dependencies**: adds `@veltdev/react` and `@veltdev/types`, plus feature-specific packages (e.g., `yjs` for CRDT)
3. **Generates components**: creates files under `components/velt/` for collaboration, document initialization, and user authentication
4. **Copies assets**: adds icon SVGs to `public/icons/` when features like notifications are selected
After the CLI completes, you need to manually wrap your page content with `VeltProvider`. The CLI skips auto-wiring the layout if it detects a `metadata` export (server component). See the [Troubleshooting](#manual-veltprovider-setup) section for the required code.
## Generated Files
### Core (always created)
```
components/velt/
├── VeltCollaboration.tsx # Main collaboration wrapper
├── VeltInitializeDocument.tsx # Document initialization hook
└── VeltInitializeUser.tsx # User authentication hook
```
### With features enabled
When you use `--comments`, `--notifications`, or CRDT flags, the CLI also generates:
```
components/velt/
├── VeltTools.tsx # Toolbar (presence, sidebar, notifications)
└── ui-customization/
├── VeltCustomization.tsx # Dark mode + wireframe wrapper
├── styles.css # Custom styles
└── ... # Feature-specific wireframe files
```
To use the toolbar components, import `VeltTools` into your page:
```tsx theme={null}
import VeltTools from '@/components/velt/VeltTools';
export default function MyPage() {
return (
<>
{/* Your page content */}
>
);
}
```
## Examples
```bash theme={null}
# Core only (minimal setup)
npx @velt-js/add-velt
# Comments only (includes Presence + Cursors)
npx @velt-js/add-velt --comments
# Notifications only (includes Presence + Cursors)
npx @velt-js/add-velt --notifications
# Comments + Notifications
npx @velt-js/add-velt --comments --notifications
# All features with ReactFlow CRDT
npx @velt-js/add-velt --all --reactflow-crdt
# All features with Tiptap CRDT
npx @velt-js/add-velt --all --tiptap-crdt
# Force overwrite existing files
npx @velt-js/add-velt --all --reactflow-crdt --force
```
## Troubleshooting
### Dependency conflicts
If installation fails due to peer dependency issues:
```bash theme={null}
npx @velt-js/add-velt --force
# or (npm only)
npx @velt-js/add-velt --legacy-peer-deps
```
The CLI uses a smart retry strategy that automatically tries `--force` and `--legacy-peer-deps` as fallbacks.
### Existing files
Use `--force` to overwrite previously generated files:
```bash theme={null}
npx @velt-js/add-velt --comments --force
```
### Multiple CRDT types
Only one CRDT type can be selected at a time:
```bash theme={null}
# Wrong — will error
npx @velt-js/add-velt --reactflow-crdt --tiptap-crdt
# Correct
npx @velt-js/add-velt --reactflow-crdt
```
### `--all` without a CRDT type
The `--all` flag requires a CRDT type:
```bash theme={null}
# Wrong — will error
npx @velt-js/add-velt --all
# Correct
npx @velt-js/add-velt --all --reactflow-crdt
```
### Manual VeltProvider setup
After running the CLI, wrap your page content with `VeltProvider` in the page where collaboration happens (NOT in `layout.tsx`):
```tsx theme={null}
// app/dashboard/[docId]/page.tsx (or your collaboration page)
"use client";
import { VeltProvider } from '@veltdev/react';
import { useVeltAuthProvider } from '@/components/velt/VeltInitializeUser';
import { VeltCollaboration } from '@/components/velt/VeltCollaboration';
export default function DocumentPage() {
const { authProvider } = useVeltAuthProvider();
return (
{/* Your page content */}
);
}
```
> [!WARNING]
>
> Do NOT place `VeltProvider` in `app/layout.tsx`. If your layout exports `metadata` (a server-only feature), adding `VeltProvider` there requires `"use client"` which conflicts with the metadata export. Place VeltProvider in the specific page where collaboration features are needed.
## Next Steps
* **[Quickstart](/docs/get-started/quickstart)**: Manual step-by-step Velt setup (without the CLI)
* **[Agent Skills](/docs/get-started/skills)**: Teach your AI coding agent correct Velt patterns
* **[MCP Installer](/docs/get-started/mcp-installer)**: AI-assisted Velt installation through MCP
* **[Comments Overview](/docs/async-collaboration/comments/overview)**: Learn about commenting features
* **[CRDT Setup](/docs/realtime-collaboration/crdt/overview)**: Set up collaborative editing
* **[Key Concepts](/docs/key-concepts/overview)**: Understand documents, locations, users, and access control
# Velt Docs MCP
Source: https://velt.dev/docs/get-started/docs-mcp
Search and browse Velt documentation from Cursor, Claude, Claude Code, VS Code, and other MCP-compatible clients.
Search and browse Velt's documentation directly in your MCP-compatible editor. The Docs MCP server helps you find SDK, API, and feature info without leaving your editor.
Endpoint: `https://velt.dev/docs/mcp`
## When to Use
* You want docs answers in Cursor, Claude, Claude Code, or VS Code while coding
* Skills or the installation plugin don't cover a specific question
* You need quick lookup of setup steps, APIs, or feature guides
> [!NOTE]
>
> For guided Velt **installation**, use the [Velt Installation MCP](/docs/get-started/mcp-installer). For REST API data access, see [MCP Servers](/docs/mcp/mcp).
## Setup
> [tab] Claude
>
> To use the Velt Docs MCP server with Claude:
>
> **1. Add the Velt Docs MCP server to Claude**
>
> 1. Navigate to the [Connectors](https://claude.ai/settings/connectors) page in the Claude settings.
>
> 2. Select **Add custom connector**.
>
> 3. Add the Velt Docs MCP server:
>
> * Name: `Velt`
>
> * URL: `https://velt.dev/docs/mcp`
>
> 4. Select **Add**.
>
> **2. Access the MCP server in your chat**
>
> 1. When using Claude, select the attachments button (the plus icon).
> 2. Select the Velt Docs MCP server.
> 3. Ask Claude a question about Velt.
>
> See the [Model Context Protocol documentation](https://modelcontextprotocol.io/docs/tutorials/use-remote-mcp-server#connecting-to-a-remote-mcp-server) for more details.
> [tab] Claude Code
>
> To use the Velt Docs MCP server with Claude Code, run the following command:
>
> ```bash theme={null}
> claude mcp add --transport http Velt https://velt.dev/docs/mcp
> ```
>
> Test the connection by running:
>
> ```bash theme={null}
> claude mcp list
> ```
>
> See the [Claude Code documentation](https://docs.anthropic.com/en/docs/claude-code/mcp#installing-mcp-servers) for more details.
> [tab] Cursor
>
> [Install in Cursor](cursor://anysphere.cursor-deeplink/mcp/install?name=velt\&config=eyJuYW1lIjoiVmVsdCIsInVybCI6Imh0dHBzOi8vdmVsdC5kZXYvZG9jcy9tY3AiLCJoZWFkZXJzIjp7fX0%3D)
>
> To connect the Velt Docs MCP server to Cursor, follow these steps:
>
> **1. Open MCP settings**
>
> 1. Use Command + Shift + P (Ctrl + Shift + P on Windows) to open the command palette.
> 2. Search for "Open MCP settings".
> 3. Select **Add custom MCP**. This will open the `mcp.json` file.
>
> **2. Configure the Velt Docs MCP server**
>
> In `mcp.json`, add:
>
> ```json theme={null}
> {
> "mcpServers": {
> "Velt": {
> "url": "https://velt.dev/docs/mcp"
> }
> }
> }
> ```
>
> **3. Test the connection**
>
> In Cursor's chat, ask "What tools do you have available?" Cursor should show the Velt Docs MCP server as an available tool.
>
> See [Installing MCP servers](https://docs.cursor.com/en/context/mcp#installing-mcp-servers) in the Cursor documentation for more details.
> [tab] VS Code
>
> [Install in VS Code](https://vscode.dev/redirect/mcp/install?name=Velt\&config=%7B%22type%22%3A%22http%22%2C%22url%22%3A%22https%3A%2F%2Fvelt.dev%2Fdocs%2Fmcp%22%7D)
>
> To connect the Velt Docs MCP server to VS Code, click the **Install in VS Code** button. Or to manually connect the MCP server, create a `.vscode/mcp.json` file and add:
>
> ```json theme={null}
> {
> "servers": {
> "Velt": {
> "type": "http",
> "url": "https://velt.dev/docs/mcp"
> }
> }
> }
> ```
>
> See the [VS Code documentation](https://code.visualstudio.com/docs/copilot/chat/mcp-servers) for more details.
## Example Usage
Once the Velt Docs MCP server is configured, search for documentation from your client.
For example, in Cursor, ask:
**Query:**
`how to add Velt popover comments?`
**Result:**
The MCP returns relevant documentation pages and snippets related to adding popover comments.
**More examples:**
* `Generate sample data for adding Velt comment annotations via Velt Rest API`
## Next Steps
* [Installation Plugin](/docs/get-started/installation-plugin): bundles Docs MCP with skills and rules
* [Velt Installation MCP](/docs/get-started/mcp-installer): guided SDK install
* [Agent Skills](/docs/get-started/skills): offline implementation patterns
* [REST APIs MCP](/docs/mcp/mcp): query and mutate Velt data via REST APIs
# Installation Plugin
Source: https://velt.dev/docs/get-started/installation-plugin
Install the Velt installation plugin in Cursor or Claude Code to get skills, rules, an expert agent, and MCP servers for setting up and building with the Velt SDK.
Add Velt collaboration knowledge directly into your AI coding editor. The Velt **installation plugin** gives your AI agent access to slash-command skills, 14 bundled agent-skills (282 implementation rules), 6 embedded best-practice rules, a `velt-expert` agent persona, and two MCP servers, so it can scaffold, debug, and extend Velt features with accurate, up-to-date patterns.
> [card] [Cursor Plugin](https://github.com/velt-js/velt-plugin-cursor)
>
> velt-js/velt-plugin-cursor
> [card] [Claude Code Plugin](https://github.com/velt-js/velt-plugin-claude)
>
> velt-js/velt-plugin-claude
## When to Use the Installation Plugin
* You are setting up or building with Velt in Cursor or Claude Code and want your AI agent to have deep Velt SDK knowledge
* You want slash-command skills like `/install-velt`, `/add-comments`, or `/velt-help` available in your editor
* You want always-on rules that prevent common Velt integration mistakes (e.g., incorrect `VeltProvider` placement, missing `setDocuments`)
* You want the `velt-expert` agent persona for architecture and integration guidance
> [!NOTE]
>
> The installation plugin bundles MCP servers, skills, rules, and an agent into a single installable package for SDK setup and feature work. If you only need one of these:
>
> * **MCP servers only**: See the [MCP Installer](/docs/get-started/mcp-installer)
> * **Skills only** (for any AI agent): See [Agent Skills](/docs/get-started/skills)
> * **No AI agent**: See the [CLI](/docs/get-started/cli)
> * **Matching Velt UI to a Figma design**: See the [UI Customization Plugin](/docs/get-started/ui-customization-plugin)
## Prerequisites
* **Node.js** 18+
* **Cursor** or **Claude Code** with plugin support
* A [Velt API key](https://console.velt.dev)
## Quickstart
> [tab] Cursor
>
> ### Option 1: Local Plugin Directory
>
> 1. Clone the Cursor plugin repository:
>
> ```bash theme={null}
> git clone https://github.com/velt-js/velt-plugin-cursor.git
> ```
>
> 2. Open Cursor Settings → Plugins
> 3. Add the local plugin path (the repo root is the plugin):
>
> ```
> /velt-plugin-cursor
> ```
>
> 4. Restart Cursor.
>
> ### Option 2: Marketplace CLI
>
> From within Cursor, run:
>
> ```
> /plugin marketplace add /velt-plugin-cursor
> ```
> [tab] Claude Code
>
> Clone the Claude Code plugin repository and point Claude Code at it:
>
> ```bash theme={null}
> git clone https://github.com/velt-js/velt-plugin-claude.git
> claude --plugin-dir velt-plugin-claude
> ```
After installation, verify by typing `/velt-help` in your editor's AI chat. The agent should respond using Velt-specific knowledge.
## What's Included
The plugin bundles four types of resources:
| Resource | Count | Description |
| - | - | - |
| **Skills** | 2 | Slash commands: `/install-velt` and `/velt-help` |
| **Bundled Agent-Skills** | 14 | Full implementation rules (282 rules across setup, comments, CRDT, notifications, recorder, single editor mode, self-hosting data, activity logs, presence, cursors, huddle, REST APIs, proxy server, AI rewriter) |
| **Rules** | 6 | Embedded best practices (3 always-on, 3 glob-triggered) |
| **Agent** | 1 | `velt-expert` persona for architecture guidance |
| **MCP Servers** | 2 | `velt-installer` (guided setup) and `velt-docs` (documentation search) |
## Available Skills
| Skill | Description | MCP Tool Used |
| - | - | - |
| `/install-velt` | Full guided Velt SDK installation with feature selection (comments, presence, cursors, notifications, recorder, CRDT, single editor mode, self-hosting data, activity logs, huddle) | `install_velt_interactive` |
| `/velt-help` | Answer questions about the Velt SDK | `velt-docs` MCP |
## Embedded Rules
The plugin includes 6 rules distilled from the most critical agent-skills patterns. Three are always active; three activate when your AI agent works on matching files.
| Rule | Covers | Activation |
| - | - | - |
| `velt-core-setup` | Installation, `VeltProvider`, API key, domain safelist | Always on |
| `velt-auth-patterns` | User object, `authProvider`, JWT, auth provider mapping | Always on |
| `velt-document-identity` | `setDocuments`, document ID strategies, anti-patterns | Always on |
| `velt-comments-patterns` | All comment modes, component placement, editor integration | Glob-triggered |
| `velt-crdt-patterns` | CRDT stores, Tiptap integration, history disable | Glob-triggered |
| `velt-notifications-patterns` | Setup, panel config, hooks, email, webhooks | Glob-triggered |
## How It Works
The plugin follows a three-tier priority chain when answering questions or generating code:
1. **Embedded rules** (always loaded): distilled best practices that cover the most common mistakes
2. **Bundled agent-skills** (14 skills with 282 rules): full detailed patterns with code examples from the [agent-skills repository](https://github.com/velt-js/agent-skills)
3. **velt-docs MCP** (live query): fetches the latest API details or topics not covered by the first two tiers
This means the agent can answer most questions instantly from local knowledge, and only reaches out to the live docs API when needed.
## Cursor Plugin Structure
The Cursor plugin lives in its own repository at [`velt-plugin-cursor`](https://github.com/velt-js/velt-plugin-cursor). The repo root is the plugin directory.
```
velt-plugin-cursor/
├── .plugin/
│ └── plugin.json # Open Plugins standard manifest
├── .cursor-plugin/
│ └── plugin.json # Cursor backward-compat manifest
├── .mcp.json # MCP server configuration
├── agents/
│ └── velt-expert.md # Expert agent persona
├── assets/
│ └── velt.svg # Plugin logo
├── rules/ # 6 individual .mdc rule files
│ ├── velt-core-setup.mdc
│ ├── velt-auth-patterns.mdc
│ ├── velt-document-identity.mdc
│ ├── velt-comments-patterns.mdc
│ ├── velt-crdt-patterns.mdc
│ └── velt-notifications-patterns.mdc
├── skills/ # Core skills + 12 bundled agent-skills
│ ├── install-velt/SKILL.md
│ ├── velt-help/SKILL.md
│ ├── velt-setup-best-practices/
│ ├── velt-comments-best-practices/
│ ├── velt-crdt-best-practices/
│ ├── velt-notifications-best-practices/
│ ├── velt-recorder-best-practices/
│ ├── velt-single-editor-mode-best-practices/
│ ├── velt-self-hosting-data-best-practices/
│ ├── velt-activity-best-practices/
│ ├── velt-presence-best-practices/
│ ├── velt-cursors-best-practices/
│ ├── velt-huddle-best-practices/
│ ├── velt-rest-apis-best-practices/
│ ├── velt-proxy-server-best-practices/
│ └── velt-rewriter-best-practices/
└── packages/shared/ # Source of truth (used by build)
```
## Claude Code Implementation
The Claude Code plugin lives in its own repository at [`velt-plugin-claude`](https://github.com/velt-js/velt-plugin-claude) and follows the Claude Code plugin specification.
### Plugin Structure
```
velt-plugin-claude/
├── .claude-plugin/
│ └── plugin.json # Plugin manifest
├── .mcp.json # MCP server configuration
├── agents/
│ └── velt-expert.md # Expert agent persona
├── guides/
│ └── velt-rules.md # Combined best-practices guide (all 6 rules)
├── skills/
│ ├── install-velt/SKILL.md
│ ├── velt-help/SKILL.md
│ ├── velt-setup-best-practices/ # 24 rules
│ ├── velt-comments-best-practices/ # 69 rules
│ ├── velt-crdt-best-practices/ # 44 rules
│ ├── velt-notifications-best-practices/ # 17 rules
│ ├── velt-recorder-best-practices/ # 23 rules
│ ├── velt-single-editor-mode-best-practices/ # 14 rules
│ ├── velt-self-hosting-data-best-practices/ # 21 rules
│ ├── velt-activity-best-practices/ # 11 rules
│ ├── velt-presence-best-practices/ # 13 rules
│ ├── velt-cursors-best-practices/ # 11 rules
│ ├── velt-huddle-best-practices/ # 10 rules
│ ├── velt-rest-apis-best-practices/ # 9 rules
│ ├── velt-proxy-server-best-practices/ # 14 rules
│ └── velt-rewriter-best-practices/ # 2 rules
└── README.md
```
### Plugin Manifest
The manifest at `.claude-plugin/plugin.json` registers the plugin with Claude Code:
```json theme={null}
{
"name": "velt",
"description": "Add real-time collaboration (comments, presence, cursors, CRDT editing, notifications) to React and Next.js apps using the Velt SDK.",
"version": "1.0.0",
"author": { "name": "Velt", "email": "support@velt.dev" },
"homepage": "https://velt.dev/docs",
"repository": "https://github.com/velt-js/velt-plugin-claude",
"license": "MIT",
"keywords": ["velt", "collaboration", "comments", "presence", "cursors", "crdt", "real-time", "react", "nextjs"]
}
```
### MCP Server Configuration
The `.mcp.json` file configures two MCP servers that Claude Code connects to automatically:
```json theme={null}
{
"mcpServers": {
"velt-installer": {
"command": "npx",
"args": ["-y", "@velt-js/mcp-installer"]
},
"velt-docs": {
"type": "http",
"url": "https://velt.dev/docs/mcp"
}
}
}
```
* **`velt-installer`**: runs locally via `npx`, exposes `install_velt_interactive`, `take_project_screenshot`, and `detect_comment_placement` tools
* **`velt-docs`**: connects to the remote Velt docs API over HTTP for live documentation queries
### Agent Persona
The `velt-expert` agent at `agents/velt-expert.md` is a Velt SDK specialist. It uses frontmatter to register with Claude Code:
```yaml theme={null}
---
name: velt-expert
description: Velt collaboration SDK expert for architecture, setup, and integration guidance.
---
```
The agent follows these key principles:
* `VeltProvider` goes in `page.tsx`, not `layout.tsx` (Next.js App Router)
* All files importing `@veltdev/react` need `"use client"` directive
* Authenticate users before setting documents
* `setDocuments` in a child component, never in `VeltProvider`'s component
* For Tiptap CRDT: always disable history (`StarterKit.configure({ history: false })`)
### Combined Rules Guide
Unlike Cursor (which uses individual `.mdc` rule files with `alwaysApply` and glob triggers), the Claude Code plugin combines all 6 rules into a single `guides/velt-rules.md` file. This guide covers:
1. **Core setup**: `VeltProvider`, API key, domain safelist
2. **Authentication**: user object, `authProvider`, JWT, provider mapping
3. **Document identity**: `setDocuments`, ID strategies, anti-patterns
4. **Comments**: all modes (freestyle, popover, text, stream, page, editor-integrated)
5. **CRDT**: store types, Tiptap integration, history disable
6. **Notifications**: panel config, hooks, email via SendGrid, webhooks
Every skill's `SKILL.md` includes a footer that references this guide:
```
**Important**: Always consult `guides/velt-rules.md` for embedded best practices before querying external sources.
```
### Skill Format
Each Claude Code skill uses `description` frontmatter (Cursor uses both `name` and `description`):
```yaml theme={null}
---
description: Full guided installation of the Velt collaboration SDK into a React or Next.js project.
---
```
Skills follow a consistent structure: **Trigger** (when to activate), **Workflow** (step-by-step instructions), **Guardrails** (constraints), **Priority Chain** (where to look for answers), and **Output** (what gets delivered).
### Differences from Cursor Plugin
| Aspect | Cursor ([`velt-plugin-cursor`](https://github.com/velt-js/velt-plugin-cursor)) | Claude Code ([`velt-plugin-claude`](https://github.com/velt-js/velt-plugin-claude)) |
| - | - | - |
| **Repository** | Separate repo with build system and shared source | Separate standalone repo (no build system needed) |
| **Manifest** | `.plugin/plugin.json` + `.cursor-plugin/plugin.json` (Open Plugins standard) | `.claude-plugin/plugin.json` with simpler schema |
| **Rules** | 6 individual `.mdc` files with `alwaysApply` / glob frontmatter | Single `guides/velt-rules.md` combining all 6 rules |
| **MCP config** | `.mcp.json` (dotfile) | `.mcp.json` (dotfile), `velt-docs` uses `"type": "http"` |
| **Skill frontmatter** | `name` + `description` | `description` only |
| **Agent footer** | No rules reference footer | Appends `guides/velt-rules.md` reference to agent and all skills |
| **Logo** | `assets/velt.svg` included | Not included |
| **Build system** | `npm run build` from `packages/shared/` source | Static, no build required |
## Contributing
If you are contributing to the Cursor plugin, the [`velt-plugin-cursor`](https://github.com/velt-js/velt-plugin-cursor) repository uses a shared-source architecture. All canonical content lives in `packages/shared/` and is built into the Cursor plugin at the repo root.
### Build Workflow
```bash theme={null}
# 1. Sync the agent-skills reference (from a sibling ../agent-skills directory)
npm run sync
# 2. Generate the Cursor plugin from shared source
npm run build
# 3. Validate the Cursor plugin is complete
npm run validate
# Or run all three:
npm run all
```
### Sync Options
By default, `npm run sync` looks for the agent-skills repository at `../agent-skills`. To override:
```bash theme={null}
node scripts/sync-agent-skills.mjs /path/to/agent-skills
```
### What the Build Does
* Adds platform-specific frontmatter to skills and agents
* Converts shared rules to `.mdc` files with `alwaysApply` and glob frontmatter
* Copies bundled agent-skills into the plugin
* Generates `.plugin/plugin.json` and `.cursor-plugin/plugin.json` manifests
### Validation Checks
`npm run validate` verifies:
* All core skills and 14 bundled agent-skills present
* Both MCP servers configured
* Agent persona present
* JSON manifests valid and free of path traversal
* Logo asset present
## Troubleshooting
### Plugin not loading after installation
Restart your editor after adding the plugin path. Verify the plugin directory contains a `.cursor-plugin/plugin.json` (Cursor) or `.claude-plugin/plugin.json` (Claude Code) manifest file.
### Skills not appearing
Confirm the plugin directory points to the correct repository root (`velt-plugin-cursor` or `velt-plugin-claude`), not `packages/shared`.
### Stale rules or skills
If you updated the shared source, re-run the build:
```bash theme={null}
npm run build
```
Then restart your editor to pick up the changes.
### MCP servers not connecting
The plugin configures two MCP servers automatically. If they fail to connect, verify that `npx -y @velt-js/mcp-installer` runs successfully in your terminal:
```bash theme={null}
echo '{"jsonrpc":"2.0","method":"tools/list","id":1}' | npx -y @velt-js/mcp-installer
```
For the docs MCP server, verify `https://velt.dev/docs/mcp` is reachable from your network.
### Claude Code: `guides/velt-rules.md` not found
Ensure you are pointing at `velt-plugin-claude`, not `velt-plugin-cursor`. The Claude Code plugin uses a combined rules guide at `guides/velt-rules.md`, while Cursor uses individual `.mdc` files in `rules/`.
## Next Steps
* **[UI Customization Plugin](/docs/get-started/ui-customization-plugin)**: Turn a Figma design into verified Velt UI customization
* **[MCP Installer](/docs/get-started/mcp-installer)**: AI-assisted Velt installation through MCP (without the full plugin)
* **[Agent Skills](/docs/get-started/skills)**: Standalone skill packages for any AI coding agent
* **[CLI](/docs/get-started/cli)**: Terminal-based Velt setup without an AI agent
* **[Quickstart](/docs/get-started/quickstart)**: Manual step-by-step Velt setup
* **[Key Concepts](/docs/key-concepts/overview)**: Understand documents, locations, users, and access control
# Velt Installation MCP
Source: https://velt.dev/docs/get-started/mcp-installer
Use the Velt MCP server to install collaboration features into React and Next.js projects through your AI coding agent.
Install Velt collaboration features into your React or Next.js project through an AI coding agent. The Velt MCP (Model Context Protocol) server connects to editors like Claude Code, Cursor, and Windsurf, enabling guided installation with plan generation, codebase scanning, and user approval, all through natural conversation.
> [card] [GitHub Repository](https://github.com/velt-js/velt-mcp-installer)
>
> velt-js/velt-mcp-installer
## When to Use the MCP Installer
* You are using an AI coding agent (Claude Code, Cursor, Windsurf, or Claude Desktop)
* You want an interactive, guided setup with automatic codebase analysis
* You want the AI to generate an implementation plan before making changes
* You need help wiring Velt into an existing authentication system or document structure
> [!NOTE]
>
> For a non-interactive, terminal-based workflow, see the
> [CLI](/docs/get-started/cli) page instead.
## Prerequisites
* **Node.js** 18+
* An existing **React** or **Next.js** project (Next.js App Router, Pages Router, Vite + React, or Create React App)
* A [Velt API key and auth token](https://console.velt.dev)
* An MCP-compatible AI coding editor
### Recommended: Install Agent Skills
For the best results, install Velt Agent Skills before using the MCP installer. Skills give your AI agent access to verified Velt implementation patterns.
```bash theme={null}
npx skills add velt-js/agent-skills
```
See [Agent Skills](/docs/get-started/skills) for details.
## Quickstart
### Step 1: Add the MCP Server
Add the Velt MCP server to your editor. The commands below use `npx` to automatically download and run `@velt-js/mcp-installer`. You can also install it globally with:
```bash theme={null}
npm install -g @velt-js/mcp-installer
```
> [tab] Claude Code
>
> Run this command in your terminal:
>
> ```bash theme={null}
> claude mcp add velt-installer -- npx -y @velt-js/mcp-installer
> ```
> [tab] Cursor
>
> Add to `.cursor/mcp.json` in your project (or global config):
>
> ```json theme={null}
> {
> "mcpServers": {
> "velt-installer": {
> "command": "npx",
> "args": ["-y", "@velt-js/mcp-installer"]
> }
> }
> }
> ```
> [tab] Windsurf
>
> Add to your Windsurf MCP config:
>
> ```json theme={null}
> {
> "mcpServers": {
> "velt-installer": {
> "command": "npx",
> "args": ["-y", "@velt-js/mcp-installer"]
> }
> }
> }
> ```
> [tab] Claude Desktop
>
> Add to `~/Library/Application Support/Claude/claude_desktop_config.json` (macOS) or `%APPDATA%\Claude\claude_desktop_config.json` (Windows):
>
> ```json theme={null}
> {
> "mcpServers": {
> "velt-installer": {
> "command": "npx",
> "args": ["-y", "@velt-js/mcp-installer"]
> }
> }
> }
> ```
> [tab] Other
>
> The server runs over stdio. Use this command to start it:
>
> ```bash theme={null}
> npx -y @velt-js/mcp-installer
> ```
>
> Add it to your editor's MCP server configuration with `command: "npx"` and `args: ["-y", "@velt-js/mcp-installer"]`.
Restart your editor after adding the config.
### Step 2: Start the Installation
In your AI chat, say:
```
install velt
```
The AI will walk you through each step one at a time:
1. Confirm your project directory
2. Provide your Velt API key and auth token
3. Select features (or type **SKIP** for CLI-only mode)
4. Choose where to install `VeltProvider` (`app/page.tsx` recommended)
5. Choose corner position for Velt UI components
6. Review the implementation plan
7. Approve and apply changes
## Installation Modes
### Guided Mode (Default)
The guided mode generates a full implementation plan with codebase analysis before making any changes.
**Workflow:**
1. **Collect info**: the AI asks setup questions one at a time (project path, API key, auth token, features, provider location, corner position)
2. **Discovery consent**: the AI asks whether to scan your codebase for integration points (document ID sources, authentication patterns, JWT wiring)
3. **Verification**: if scanning is approved, the AI shows findings for you to confirm, edit, or override
4. **Plan generation**: a detailed implementation plan is generated based on your project structure and wiring data
5. **Apply**: after you approve the plan, the AI applies changes step by step
6. **Validation**: full QA validation runs automatically after installation
> [!WARNING]
>
> The installer recommends placing `VeltProvider` in `app/page.tsx`, not
> `app/layout.tsx`. Follow this recommendation unless you have a specific reason
> to do otherwise.
### CLI-Only Mode (SKIP)
For experienced Velt developers who want the scaffold files without full integration:
1. At the feature selection step, type **SKIP**
2. The Velt CLI runs with core-only flags
3. You receive a TODO checklist for manual setup
Use this mode when you want to wire features yourself or just need the base files.
## Available Features
| Feature | Description |
| - | - |
| Comments | Inline comments with 8 types: freestyle, popover, page, text, inline, tiptap, lexical, slate |
| Presence | Real-time user avatars and online status |
| Cursors | Live cursor position tracking |
| Notifications | Async collaboration notifications |
| Recorder | Audio, video, and screen recording with playback |
| CRDT | Collaborative editing with Tiptap, CodeMirror, BlockNote, or ReactFlow |
| Single Editor Mode | Exclusive editing access: one user edits at a time, others view with live sync |
| Self-Hosting Data | Store comments, attachments, reactions, and user PII on your own database (PostgreSQL) |
| Activity Logs | Real-time activity feed showing comments, reactions, priority changes, recordings |
| Huddle | Audio, video, and screen sharing with ephemeral chat and flock mode |
## Codebase Discovery
In guided mode, the installer can automatically scan your project for integration points:
| Discovery Target | What It Detects |
| - | - |
| **Document ID** | Dynamic route params (`[id]`), query params, state variables, database fetches |
| **User Authentication** | Next-Auth, Clerk, Auth0, Auth, Supabase Auth, custom auth |
| **JWT Authentication** | Token generation endpoints, bearer auth patterns |
| **Setup Location** | Root layout, specific pages, custom providers |
Each finding includes a confidence level (HIGH, MEDIUM, LOW, NONE). For uncertain findings, the installer asks you to verify rather than guessing.
If you decline the codebase scan, the AI asks a manual questionnaire covering document ID source, user authentication, JWT setup, and component insertion location.
## Framework Support
| Framework | Support | `"use client"` Directives |
| - | - | - |
| Next.js (App Router) | Full | Auto-applied |
| Next.js (Pages Router) | Full | N/A |
| Vite + React | Full | Not needed |
| Create React App | Full | Not needed |
## Generated Code Structure
After installation, the generated files follow this pattern:
```
app/
├── layout.tsx # Wraps with AppUserProvider
├── page.tsx # Contains VeltProvider with authProvider hook
└── userAuth/
├── AppUserContext.tsx # User context provider
└── useAppUser.tsx # User data hook
components/velt/
├── VeltInitializeUser.tsx # Exports useVeltAuthProvider hook
├── VeltInitializeDocument.tsx # Exports useCurrentDocument hook
└── VeltCollaboration.tsx # All Velt feature components
app/api/velt/token/
└── route.ts # JWT token generation API (if JWT is configured)
```
## MCP Tools
The MCP server exposes these tools to your AI agent:
| Tool | Description |
| - | - |
| `install_velt_interactive` | Unified installer with guided or CLI-only mode |
| `install_velt_freestyle` | Legacy installer for basic freestyle comments |
| `take_project_screenshot` | Capture a screenshot of your running app via Playwright |
| `detect_comment_placement` | Analyze project structure to find the best locations for comments |
## Troubleshooting
### MCP server not loading
After adding the configuration, restart your editor. The MCP server runs over stdio and must be started by the editor process.
### AI not detecting the installer
Verify the MCP config is valid JSON and that `npx -y @velt-js/mcp-installer` runs successfully in your terminal. You can test with:
```bash theme={null}
echo '{"jsonrpc":"2.0","method":"tools/list","id":1}' | npx -y @velt-js/mcp-installer
```
### Discovery scan returns low confidence
If the codebase scan cannot determine your document ID or auth setup with confidence, the AI will ask explicit follow-up questions. You can also choose the manual questionnaire path by declining the scan.
### Validation errors after installation
The installer runs QA validation automatically. Check the browser console for Velt-specific errors after starting your dev server. Common issues include missing API keys or incorrect document IDs.
## Next Steps
* **[Agent Skills](/docs/get-started/skills)**: Install skills to improve AI-generated Velt code
* **[CLI](/docs/get-started/cli)**: Terminal-based Velt setup without an AI agent
* **[Quickstart](/docs/get-started/quickstart)**: Manual step-by-step Velt setup
* **[Comments Overview](/docs/async-collaboration/comments/overview)**: Learn about commenting features
* **[Key Concepts](/docs/key-concepts/overview)**: Understand documents, locations, users, and access control
# Getting Started
Source: https://velt.dev/docs/get-started/overview
Explore the Velt SDK quickstart, setup paths, and supported features such as comments, presence, notifications, recordings, and AI rewriter.
## Getting Started
> [card] [Quickstart](/docs/get-started/quickstart)
>
> Set up Velt with a fresh app
> [card] [Setup](/docs/get-started/quickstart)
>
> Integrate Velt with an existing app
## Popular Features
> [card] [Comments](/docs/async-collaboration/comments/overview)
>
> Enable contextual discussions within your app
> [card] [In-app Notifications](/docs/async-collaboration/notifications/overview)
>
> Notify users about comment updates or add custom app notifications
> [card] [Recorder](/docs/async-collaboration/recorder/overview)
>
> Loom-style audio, video & screen recording with AI transcription
> [card] [Huddle](/docs/realtime-collaboration/huddle/overview)
>
> Slack-style huddle calls within your app
## Async Collaboration
> [card] [Comments](/docs/async-collaboration/comments/overview)
>
> Leave a comment anywhere
> [card] [Comments Sidebar](/docs/async-collaboration/comments-sidebar/overview)
>
> A sidebar that holds your comments
> [card] [In-app Notifications](/docs/async-collaboration/notifications/overview)
>
> Notification center in your app
> [card] [Recorder](/docs/async-collaboration/recorder/overview)
>
> Embeddable audio, video & screen recording
> [card] [Media Player Comments](/docs/async-collaboration/comments/setup/video-player-setup/custom-video-player-setup)
>
> Frame.io style comments on video
> [card] [System Comments](/docs/api-reference/rest-apis/v2/comments-feature/comment-annotations/add-comment-annotations)
>
> Leave comments using an API
> [card] [Reactions](/docs/async-collaboration/reactions/overview)
>
> Add reactions to components
> [card] [View Analytics](/docs/async-collaboration/view-analytics/overview)
>
> Show which users viewed a document
> [card] [Arrows](/docs/async-collaboration/arrows/overview)
>
> Point at what is important
> [card] [Activity Logs](/docs/async-collaboration/activity/overview)
>
> A unified timeline of who did what, and when
> [card] [Suggestions](/docs/async-collaboration/suggestions/overview)
>
> Google Docs-style suggested edits with accept/reject
## Realtime Collaboration
> [card] [Live State Sync](/docs/realtime-collaboration/live-state-sync/overview)
>
> Sync the state of your app realtime
> [card] [Single Editor Mode](/docs/realtime-collaboration/single-editor-mode/overview)
>
> Lock access to a single editor
> [card] [Presence](/docs/realtime-collaboration/presence/overview)
>
> See who else is browsing online
> [card] [Cursors](/docs/realtime-collaboration/cursors/overview)
>
> See where everyone else is browsing
> [card] [Follow Me Mode](/docs/realtime-collaboration/flock-mode/overview)
>
> Let others follow along your screen
> [card] [Huddle](/docs/realtime-collaboration/huddle/overview)
>
> Hop on a group call with everyone
> [card] [Live Selection](/docs/realtime-collaboration/live-selection/overview)
>
> See what others are editing
> [card] [Multiplayer Editing](/docs/realtime-collaboration/crdt/overview)
>
> CRDT (Yjs) based collaborative editing
> [card] [Video Player Sync](/docs/realtime-collaboration/video-player-sync/overview)
>
> Watch videos in sync with everyone
## AI
> [card] [AI Rewriter](/docs/ai/rewriter/overview)
>
> Select text and use AI to rewrite or improve it
> [card] [Review Workflow Builder](/docs/ai/approval-engine/overview)
>
> Multi-step approval workflows with AI agents and humans
> [card] [Agent Comments](/docs/ai/agent-comments)
>
> Let AI agents leave comments and findings in Velt
> [card] [Chat SDK Adapter](/docs/ai/chat-sdk-adapter)
>
> Build bots that read and respond to comment threads
## Advanced
> [card] [Webhooks](/docs/webhooks/basic)
>
> Call a webhook when a comment is added
> [card] [Email Notifications](/docs/async-collaboration/comments/notifications#email-notifications)
>
> Set up email notifications
> [card] [REST APIs](/docs/api-reference/rest-apis/v2/workspace/create)
>
> Retrieve or modify data
> [card] [UI Customization](/docs/ui-customization/overview)
>
> Fully customize Velt Components
# Quickstart
Source: https://velt.dev/docs/get-started/quickstart
Install the Velt SDK, configure your API key and allowed domains, and add collaborative comments and presence in React, Angular, Vue, or HTML.
Get Velt up and running in your app with comments, presence, and real-time collaboration features. You'll install the package, configure authentication, set up documents, and see collaborative features working immediately.
> [!WARNING]
>
> The SDK will not work without proper authentication and document initialization.
## Prerequisites
* Package manager (npm, yarn, or pnpm)
* Node.js (v14 or higher)
* React 16+, Vue 2+, Angular 12+, or vanilla HTML/JS
* A [Velt account with an API key](https://console.velt.dev)
* Optional: TypeScript types package for better development experience
## Setup
### Step 1: Install Dependencies
Install the required packages:
> [tab] React / Next.js
>
> ```bash theme={null}
> npm install @veltdev/react
> # Optional: npm install --save-dev @veltdev/types
> ```
> [tab] Angular
>
> ```bash theme={null}
> npm install @veltdev/client
> # Optional: npm install --save-dev @veltdev/types
> ```
> [tab] Vue.js
>
> ```bash theme={null}
> npm install @veltdev/client
> # Optional: npm install --save-dev @veltdev/types
> ```
> [tab] HTML
>
> Use our CDN Script
>
> ```html theme={null}
>
> ```
### Step 2: Get Your API Key
1. Go to [console.velt.dev](https://console.velt.dev) and create an account
2. Copy your API key from the dashboard

> [!NOTE]
>
> Velt uses a single API key on the client (frontend). There is no separate public/private key pair — the API key is paired with your allowed domains list to restrict where it can be used. For backend calls to Velt's REST APIs, generate a separate [Auth Token](/docs/security/auth-tokens) in the Velt Console and pass it as the `x-velt-auth-token` header alongside the API key. Keep auth tokens server-side only.
### Step 3: Safelist Your Domain
In the Velt Console, add your app's domain to "Managed Domains" to whitelist it for development and production use.

> [!TIP]
>
> Managing many environments? You can also add, list, and remove allowed domains programmatically via the REST APIs:
>
> * [Add Domains](/docs/api-reference/rest-apis/v2/workspace/add-domain) — `POST /v2/workspace/domains/add` (supports wildcard subdomains, e.g. `*.example.com`)
> * [Get Domains](/docs/api-reference/rest-apis/v2/workspace/domains-get)
> * [Delete Domains](/docs/api-reference/rest-apis/v2/workspace/delete-domain)
>
> Both endpoints require your API key and an [Auth Token](/docs/security/auth-tokens) and are designed for automating environment provisioning.
### Step 4: Initialize Velt
Initialize the SDK and render the base collaborative components. Pick your framework and:
* React: wrap your app with `VeltProvider` and pass your API key.
* Angular/Vue/HTML: call the init function with your API key to bootstrap the client.
This confirms the SDK is loaded and ready for adding features in later steps.
See the tabs below for your specific implementation:
> [tab] React / Next.js
>
> Wrap your app with `VeltProvider` and pass your API key.
>
> > [!WARNING]
> >
> > If using Next.js, add `'use client'` directive at the top of files containing Velt components to ensure proper client-side rendering.
>
> ```jsx Step 1: Provider Setup theme={null}
> 'use client'; // MAKE SURE TO INCLUDE 'use client' for Next.js implementation
>
> import { VeltProvider } from '@veltdev/react';
>
> export default function App() {
> return (
>
> {/* Your app content */}
>
> );
> }
> ```
> [tab] Angular
>
> Step 1: Add `schemas: [CUSTOM_ELEMENTS_SCHEMA]` to allow Angular to render Velt's custom elements (web components).
>
> Step 2: Boot the Velt client by calling `initVelt` with your API key.
>
> ```jsx Step 1: App Module Setup theme={null}
> import { CUSTOM_ELEMENTS_SCHEMA, NgModule } from '@angular/core';
> import { BrowserModule } from '@angular/platform-browser';
> import { AppRoutingModule } from './app-routing.module';
> import { AppComponent } from './app.component';
>
> @NgModule({
> declarations: [
> AppComponent
> ],
> imports: [
> BrowserModule,
> AppRoutingModule
> ],
> providers: [],
> bootstrap: [AppComponent],
> schemas: [CUSTOM_ELEMENTS_SCHEMA], // Add this line
> })
> export class AppModule { }
> ```
>
> ```jsx Step 2: Initialize Velt theme={null}
> import { initVelt } from '@veltdev/client';
>
> export class AppComponent implements OnInit {
> async ngOnInit() {
> await initVelt('YOUR_VELT_API_KEY');
> }
> }
> ```
> [tab] Vue.js
>
> Step 1: Register Velt's custom elements by setting `Vue.config.ignoredElements = [/velt-*/]`.
>
> Step 2: Boot the Velt client by calling `initVelt` with your API key.
>
> ```js Step 1: Main.js Setup theme={null}
> import Vue from 'vue';
> import App from './App.vue';
>
> // Allow Velt elements
> Vue.config.ignoredElements = [/velt-*/];
>
> new Vue({
> render: h => h(App),
> }).$mount('#app');
> ```
>
> ```js Step 2: Initialize Velt theme={null}
> import { initVelt } from '@veltdev/client';
>
> export default {
> name: 'App',
> async mounted() {
> await initVelt('YOUR_VELT_API_KEY');
> }
> }
> ```
> [tab] HTML
>
> Call `Velt.init('YOUR_VELT_API_KEY')` to bootstrap the client before rendering Velt components.
>
> ```js Step 1: Script Include and Init theme={null}
>
>
> ```
### Step 5: Authenticate Users
There are two ways to authenticate in Velt. Pick one based on your needs:
* **Auth Provider (recommended)**: Configure once and Velt will **fetch/refresh tokens automatically**. See details in the [Key Concepts](/docs/key-concepts/overview#authenticate-a-user).
* **Identify API (more personable)**: Call `identify(user, options)` directly where you need it for more control. If you use Identify, you must refresh tokens yourself, see [Token Refresh](/docs/get-started/advanced#token-refresh).
> [!TIP]
>
> After authenticating, you can retrieve the current user object anytime using [`getCurrentUser()`](/docs/api-reference/sdk/api/api-methods#getcurrentuser) or [`useCurrentUser()`](/docs/api-reference/sdk/api/react-hooks#usecurrentuser).
> [!WARNING]
>
> **Critical Authentication Requirement:**
>
> * You must authenticate the user. The recommended path is configuring `authProvider` on `VeltProvider` during initialization.
> [!TIP]
>
> During development, `generateToken` can be omitted; however, for production it is highly recommended to provide `generateToken` for basic security and seamless token refresh.
You first need to create a user object with the required user information. The `user` object should include the following fields: `userId`, `organizationId`, `name`, `email`, and `photoUrl`.
```javascript theme={null}
// Example user object
const user = {
userId: 'user-123',
organizationId: 'org-abc',
name: 'John Doe',
email: 'john.doe@example.com',
photoUrl: 'https://i.pravatar.cc/300',
};
```
> [!NOTE]
>
> **Error Handling**: By default, authentication methods return `null` on failure. You can configure them to throw errors instead by setting `throwError: true`. [Learn more about error handling](/docs/get-started/advanced#error-handling-in-authentication).
Then, you need to provide a function that generates a Velt JWT token from your backend. See the [JWT Token Setup](/docs/get-started/advanced#jwt-authentication-tokens). Tokens expire after 48 hours, handle renewals as shown in [Token Refresh](/docs/get-started/advanced#token-refresh).
> [!NOTE]
>
> Access control roles: Assign users as **Editor** or **Viewer** per resource (organization, folder, document) via your JWT token permissions or backend access APIs. Editors can write collaboration data (e.g., add/edit comments); Viewers are read-only. See: [Access Control](/docs/key-concepts/overview#access-control), APIs [Generate Token](/docs/api-reference/rest-apis/v2/auth/generate-token), [Add Permissions](/docs/api-reference/rest-apis/v2/auth/add-permissions), [Add/Update Users](/docs/api-reference/rest-apis/v2/users/add-users).
> [tab] React / Next.js
>
> ```jsx theme={null}
> return (
> apiKey="YOUR_VELT_API_KEY"
> authProvider={{
> user,
> retryConfig: { retryCount: 3, retryDelay: 1000 },
> generateToken: async () => {
> const token = await __generateVeltAuthTokenFromYourBackend__();
> return token;
> }
> }}
> >
> {/* Your app content */}
>
> );
> ```
> [tab] Angular
>
> ```jsx theme={null}
> Velt.setVeltAuthProvider({
> user,
> retryConfig: { retryCount: 3, retryDelay: 1000 },
> generateToken: async () => {
> const token = await __generateVeltAuthTokenFromYourBackend__();
> return token;
> }
> });
> ```
> [tab] Vue.js
>
> ```js theme={null}
> Velt.setVeltAuthProvider({
> user,
> retryConfig: { retryCount: 3, retryDelay: 1000 },
> generateToken: async () => {
> const token = await __generateVeltAuthTokenFromYourBackend__();
> return token;
> }
> });
> ```
> [tab] HTML
>
> ```html theme={null}
>
> ```
### Step 6: Initialize Document
A **Document** represents a shared collaborative space where users can interact. The `setDocument` method initializes this space and takes a unique `documentId` and optional `metadata`.
By default, users can only access documents within their own organization. Use this to set the document for the current organization the user is logged into.
Learn more about documents [here](/docs/key-concepts/overview#documents).
To subscribe to multiple documents in a single call, use `setDocuments` and pass an array; see [here for more information](/docs/key-concepts/overview#subscribe-to-documents-from-other-organizations).
> [!WARNING]
>
> The SDK will not work without initializing the document.
> [tab] React / Next.js
>
> ```jsx React / Next.js theme={null}
> import { useEffect } from 'react';
> import { useVeltClient } from '@veltdev/react';
>
> export default function DocumentComponent() {
> const { client } = useVeltClient();
>
> useEffect(() => {
> if (client) {
> client.setDocuments([
> { id: 'unique-document-id', metadata: { documentName: 'Document Name' } }
> ]);
> }
> }, [client]);
>
> return (
>
> {/* Your document content */}
>
> );
> }
> ```
> [tab] Angular
>
> ```jsx Angular Document Setup theme={null}
> import { Component } from '@angular/core';
> import { initVelt } from '@veltdev/client';
>
> @Component({
> selector: 'app-document',
> template: `
`
> })
> export class DocumentComponent {
> client: any;
>
> async ngOnInit() {
> this.client = await initVelt('YOUR_VELT_API_KEY');
> // Set document for current organization
> this.client.setDocuments([
> { id: 'unique-document-id', metadata: { documentName: 'Document Name' } }
> ]);
> }
> }
> ```
>
> ```jsx Angular Service Approach theme={null}
> // In your document service
> export class DocumentService {
> client: any;
>
> async initializeDocument() {
> if (this.client) {
> this.client.setDocuments([
> { id: 'unique-document-id', metadata: { documentName: 'Document Name' } }
> ]);
> }
> }
> }
> ```
> [tab] Vue.js
>
> ```js Vue.js Document Setup theme={null}
> import { initVelt } from '@veltdev/client';
>
> export default {
> name: 'DocumentComponent',
> data() {
> return {
> client: null
> }
> },
> async mounted() {
> this.client = await initVelt('YOUR_VELT_API_KEY');
> // Set document for current organization
> this.client.setDocuments([
> { id: 'unique-document-id', metadata: { documentName: 'Document Name' } }
> ]);
> }
> }
> ```
>
> ```js Vue.js Composition API theme={null}
> import { ref, onMounted } from 'vue';
> import { initVelt } from '@veltdev/client';
>
> export default {
> setup() {
> const client = ref(null);
>
> onMounted(async () => {
> client.value = await initVelt('YOUR_VELT_API_KEY');
> // Set document for current organization
> client.value.setDocuments([
> { id: 'unique-document-id', metadata: { documentName: 'Document Name' } }
> ]);
> });
>
> return {
> client
> }
> }
> }
> ```
> [tab] HTML
>
> ```js HTML Document Setup theme={null}
> // In your script tag
> async function loadVelt() {
> await Velt.init("YOUR_VELT_API_KEY");
>
> // Set document for current organization
> Velt.setDocuments([
> { id: 'unique-document-id', metadata: { documentName: 'Document Name' } }
> ]);
> }
> ```
>
> ```html Complete HTML Document theme={null}
>
>
>
>
> My Document
>
>
>
>
> My Document
>
>
>
>
> ```
### Step 7: Install Velt Feature Components
Add the `VeltComments`, `VeltCommentTool`, and `VeltPresence` components to enable comments and presence features.
Use the tabs below to see the setup for React, Angular, Vue, and HTML.
> [tab] React / Next.js
>
> Render the comments surface at the app root; render presence and the comment tool within the document view:
>
> ```jsx App.js theme={null}
> import { VeltProvider, VeltComments } from '@veltdev/react';
>
>
>
>
>
>
> ```
>
> ```jsx YourDocument.js theme={null}
> import { VeltCommentTool, VeltPresence } from '@veltdev/react';
>
>
>
>
>
> ```
> [tab] Angular
>
> Render the comments surface in the root template; render presence and the comment tool in the document component template:
>
> ```html app.component.html theme={null}
>
>
> ```
>
> ```html your-document.component.html theme={null}
>
>
>
> ```
> [tab] Vue.js
>
> Render the comments surface in App.vue; render presence and the comment tool in your document component:
>
> ```html App.vue theme={null}
>
>
>
>
>
>
> ```
>
> ```html YourDocument.vue theme={null}
>
>
>
>
>
>
>
> ```
> [tab] HTML
>
> In your root component add these features (tags inside ``):
>
> ```html index.html theme={null}
>
> My Collaborative App
>
>
>
>
>
> ```
### Step 8: Verify Setup
A good first step is to check if the Velt SDK has been initialized correctly. Open your browser's developer console and run the following command:
```js theme={null}
await Velt.getMetadata()
```
This should return the document metadata you've set. If it returns an error or `null`, check the console for any initialization errors.
**To test comments functionality:**
1. Click the `VeltCommentTool` button, then hover over any element on the page to leave a comment
2. Click the `VeltCommentTool` button, then draw a box on the page to leave a comment
3. Try highlighting any text to leave a comment
4. Test replying to comments and using the comments tool
**To test presence functionality:**
1. Open two browser tabs side by side with one in incognito mode
2. Log in with different users in each tab
3. You should see user avatars appear showing presence in both tabs
> [!TIP]
>
> If you don't see the comments tool, check your browser console for API key or network errors.
## Debugging
**Common issues:**
* **Invalid API key or domain not whitelisted**: Verify your API key and ensure your domain is added under "Managed Domains" in the [Velt Console](https://console.velt.dev)
* **Component not rendering**: Ensure the VeltProvider/script loads before your components
* **No collaborative features**: Verify that both authentication and document initialization are properly set up
* **Users can't see each other**: Ensure both users are in the same organization and document
* **Package not found**: Clear npm cache and reinstall (`npm cache clean --force`)
* **TypeScript errors**: Install the optional types package (`@veltdev/types`)
## Notes
* **API Key Required**: Always use a valid API key from the [Velt Console](https://console.velt.dev)
* **Framework Compatibility**: Ensure your framework version meets the minimum requirements
* **Child Components**: Call authentication and document setup methods in child components, never in the same file as your VeltProvider
* **Next.js 'use client'**: Add `'use client'` directive at the top of files containing Velt components for proper client-side rendering
* **Organization ID**: Always include the `organizationId` when identifying users - this is required for proper access control
* **Document Required**: The SDK will not work without calling `setDocument()` - this defines the collaborative space
* **@mention Support**: To enable @mention functionality, set up user contacts [here](/docs/key-concepts/overview#contact-list)
* **Location Support**: For organizing users within documents, learn about Locations [here](/docs/key-concepts/overview#set-location)
* **TypeScript Support**: Install the optional types package for better development experience
## Complete Example
> [tab] React / Next.js
>
> > [!WARNING]
> >
> > If using Next.js, add `'use client'` directive at the top of files containing Velt components to ensure proper client-side rendering.
>
> ```jsx App.js - Root Component theme={null}
> import { VeltProvider, VeltComments } from '@veltdev/react';
> import AuthComponent from './AuthComponent';
> import DocumentComponent from './DocumentComponent';
>
> export default function App() {
> return (
>
>
>
>
>
> );
> }
> ```
>
> ```jsx AuthComponent.js - User Authentication theme={null}
> import { useIdentify } from '@veltdev/react';
>
> export default function AuthComponent() {
> const userService = () => ({
> uid: "user123",
> organizationId: "org123",
> displayName: "John Doe",
> email: "john@example.com",
> photoURL: "https://i.pravatar.cc/300"
> });
>
> const yourAuthenticatedUser = userService();
> const { uid, displayName, email, photoURL, organizationId } = yourAuthenticatedUser;
>
> const user = {
> userId: uid,
> organizationId: organizationId,
> name: displayName,
> email: email,
> photoUrl: photoURL,
> color: "#FF6B6B",
> textColor: "#FFFFFF"
> };
>
> useIdentify(user);
>
> return User: {user.name}
;
> }
> ```
>
> ```jsx DocumentComponent.js - Document Setup theme={null}
> import { useSetDocument, VeltCommentTool, VeltPresence } from '@veltdev/react';
>
> export default function DocumentComponent() {
> useSetDocument('my-document-id', { documentName: 'My Collaborative Document' });
>
> return (
>
>
My Document
>
This is a collaborative document where multiple users can comment and see each other's presence.
>
>
>
> );
> }
> ```
> [tab] Angular
>
> ```jsx app.module.ts - Module Setup theme={null}
> import { CUSTOM_ELEMENTS_SCHEMA, NgModule } from '@angular/core';
> import { BrowserModule } from '@angular/platform-browser';
> import { AppRoutingModule } from './app-routing.module';
> import { AppComponent } from './app.component';
>
> @NgModule({
> declarations: [
> AppComponent
> ],
> imports: [
> BrowserModule,
> AppRoutingModule
> ],
> providers: [],
> bootstrap: [AppComponent],
> schemas: [CUSTOM_ELEMENTS_SCHEMA], // Add this line
> })
> export class AppModule { }
> ```
>
> ```jsx app.component.ts - Component Setup theme={null}
> import { Component, OnInit } from '@angular/core';
> import { initVelt } from '@veltdev/client';
>
> @Component({
> selector: 'app-root',
> templateUrl: './app.component.html',
> styleUrls: ['./app.component.scss']
> })
> export class AppComponent implements OnInit {
> client: any;
>
> async ngOnInit() {
> this.client = await initVelt('YOUR_VELT_API_KEY');
>
> // Authenticate user
> const user = {
> userId: 'user123',
> organizationId: 'org123',
> name: 'John Doe',
> email: 'john@example.com',
> photoUrl: 'https://i.pravatar.cc/300',
> color: '#FF6B6B',
> textColor: '#FFFFFF'
> };
> await this.client.identify(user);
>
> // Set document
> await this.client.setDocument('my-document-id', { documentName: 'My Document' });
> }
> }
> ```
>
> ```html app.component.html - Template theme={null}
>
>
My Collaborative App
>
This is a collaborative document where multiple users can comment and see each other's presence.
>
>
>
>
> ```
> [tab] Vue.js
>
> ```js main.js - Vue Configuration theme={null}
> import Vue from 'vue';
> import App from './App.vue';
>
> // Allow Velt elements
> Vue.config.ignoredElements = [/velt-*/];
>
> new Vue({
> render: h => h(App),
> }).$mount('#app');
> ```
>
> ```js App.vue - Component Setup theme={null}
> import { initVelt } from '@veltdev/client';
>
> export default {
> name: 'App',
> data() {
> return {
> client: null
> }
> },
> async mounted() {
> this.client = await initVelt('YOUR_VELT_API_KEY');
>
> // Authenticate user
> const user = {
> userId: 'user123',
> organizationId: 'org123',
> name: 'John Doe',
> email: 'john@example.com',
> photoUrl: 'https://i.pravatar.cc/300',
> color: '#FF6B6B',
> textColor: '#FFFFFF'
> };
> await this.client.identify(user);
>
> // Set document
> await this.client.setDocument('my-document-id', { documentName: 'My Document' });
> }
> }
> ```
>
> ```html App.vue Template theme={null}
>
>
>
>
>
>
> ```
> [tab] HTML
>
> ```html index.html - Complete Setup theme={null}
>
>
>
>
> My Collaborative App
>
>
>
>
> My Collaborative App
>
>
>
>
>
>
> ```
>
> ```html Simple HTML Setup theme={null}
>
>
>
>
> My Collaborative App
>
>
>
>
> My Collaborative App
>
>
>
>
> ```
## Next Steps
Now that you've completed the basic setup, you can explore more advanced Velt features and concepts:
* **[Key Concepts](/docs/key-concepts/overview)**: For new developers we recommend reading through our curated list for an in-depth breakdown of the Velt SDK and cool features.
* **[Documents and Locations](/docs/key-concepts/overview#documents)**: Learn how to structure your app's collaborative spaces.
* **[Users and User Groups](/docs/key-concepts/overview#users)**: Configure and manage your users and groups.
* **[Access Control](/docs/key-concepts/overview#access-control)**: Define permissions to control who can access what.
* **[Authentication](/docs/key-concepts/overview#authentication)**: Explore more advanced authentication methods.
* **[UI Customization](/docs/ui-customization/overview)**: Customize layouts, styling, templates, and actions for Velt components.
# Quickstart Old Copy
Source: https://velt.dev/docs/get-started/quickstart-old
Quickstart for React. For other frameworks like `vue`, `angular`, `svelte`, `vanilla js` etc. check out the setup guide.
## 1. Create a React app
Create a new React app [using any method](https://react.dev/learn/start-a-new-react-project) you prefer.
## 2. Install the Velt React package onto your app
```bash Terminal theme={null}
cd my-app && npm install @veltdev/react
```
## 3. Install types (optional)
If you're using TypeScript, you can install the types package.
```bash Terminal theme={null}
npm install --save-dev @veltdev/types
```
## 4. Grab your Velt API Key
Go to [console.velt.dev](https://console.velt.dev) and grab your Velt API Key

## 5. Safelist your domain
In the Velt console, add the URL where your app is deployed to the list of Managed Domains.

## 6. Configure the VeltProvider
In **App.js**, add the `VeltProvider` component to the root of your app with your Velt API Key.
```js App.js theme={null}
```
## 7. Identify your user
In **YourAuthComponent.js**, use the `useIdentify()` hook from the Velt SDK to identify your user.
```js YourAuthComponent.js theme={null}
import { useIdentify } from '@veltdev/react';
useIdentify(user)
```
> [!WARNING]
>
> Make sure to call `useIdentify()` within a child component of the Velt Provider. Otherwise, it will not work.
## 8. Set the Document ID
In **YourDocument.js**, use the `useSetDocumentId()` hook from the Velt SDK to set the Document ID.
```js YourDocument.js theme={null}
import { useSetDocumentId } from '@veltdev/react';
useSetDocumentId("my-document-id")
```
## 9. Add the VeltComments, VeltCommentTool and VeltPresence components
In **App.js**, add `VeltComments` to enable the `Comments` functionality.
```js App.js theme={null}
```
In **YourDocument.js**, add the `VeltCommentTool` and `VeltPresence` components to test out the `Comments` and `Presence` functionality.
```js YourDocument.js theme={null}
```
## 10. Test out the Presence and Comments functionality
### Comments
* Click the `VeltCommentTool` button, then hover over any element on the page to leave a comment.
* Click the `VeltCommentTool` button, then try to draw a box on the page to leave a comment.
* You can also highlight any text to leave a comment.
### Presence
* Open two browser tabs side by side with one in Incognito mode. You should see a bubble showing the other browser's profile avatar pop up.
## 11. Need more details on how to integrate this into an existing app?
Check out this guide on [how to set up Velt with your existing app](/docs/get-started/quickstart)
```jsx App.js theme={null}
import { VeltProvider, VeltComments, VeltPresence } from '@veltdev/react';
import YourAuthComponent from './YourAuthComponent';
import YourDocument from './YourDocument';
export default function App() {
return (
);
}
```
```jsx YourAuthComponent.js theme={null}
import { useIdentify} from "@veltdev/react";
import { useState } from "react";
export default function YourAuthComponent() {
const userService = () => {
return {
uid: "user1",
displayName: "User 1",
email: "user1@velt.dev",
photoURL: "https://i.pravatar.cc/301"
};
};
// Fetch user data from user service
let yourAuthenticatedUser = userService();
const { uid, displayName, email, photoURL } = yourAuthenticatedUser;
// Create the Velt user object
let veltUser = {
userId: uid,
name: displayName,
email: email,
photoUrl: photoURL,
};
//identify Velt user
useIdentify(veltUser)
let [user,setUser] = useState(veltUser)
return User: {user?.userId}
;
}
```
```jsx YourDocument.js theme={null}
import { useSetDocumentId, VeltCommentTool, VeltPresence } from '@veltdev/react';
import { useEffect, useState } from 'react';
export default function YourDocument() {
useSetDocumentId('my-document-id')
return (
);
}
```
# Agent Skills
Source: https://velt.dev/docs/get-started/skills
Use Velt Agent Skills to get accurate, best-practice code from AI coding agents like Claude Code, Cursor, and GitHub Copilot.
Get better results from AI coding agents when building with Velt. Agent Skills are structured knowledge packages that teach your AI agent the correct Velt patterns, so it writes working code on the first try instead of guessing from outdated training data.
> [card] [GitHub Repository](https://github.com/velt-js/agent-skills)
>
> velt-js/agent-skills
> [!NOTE]
>
> Agent Skills follow the open [Agent Skills](https://agentskills.io/) format and work with Claude Code, Cursor, GitHub Copilot, and other AI coding agents that support skill discovery.
## What Are Agent Skills?
Agent Skills are folders of instructions, rules, and code examples that AI agents can discover and reference while helping you write code. Each skill covers a specific area of the Velt SDK and contains prioritized rules with correct and incorrect code patterns, verification checklists, and source pointers back to the official docs.
Instead of relying on the agent's general training data (which may be outdated or incomplete), skills give the agent access to verified, up-to-date Velt implementation patterns.
## When to Use Skills
Install Agent Skills when you are:
* Setting up Velt in a new project for the first time
* Adding collaborative commenting to a React, Next.js, or web application
* Integrating real-time collaborative editing with CRDT (Yjs) and editors like Tiptap, BlockNote, or CodeMirror
* Implementing in-app notifications, email delivery, or webhook integrations
* Adding audio, video, or screen recording with playback
* Implementing Single Editor Mode (exclusive editing access with viewer/editor roles)
* Self-hosting user-generated content (comments, attachments, reactions, user PII) on your own database
* Adding real-time activity logs and audit trails
* Adding real-time user presence avatars and online status indicators
* Adding live cursor tracking across collaborators
* Adding audio/video huddles and screen sharing
* Calling Velt REST APIs or handling webhooks from your backend
* Routing Velt SDK traffic through a reverse proxy (nginx) for enterprise network policies
* Adding the AI text-rewriter or building a custom rewriter UI
* Debugging issues with Velt features and looking for correct patterns
## Installation
Install all available Velt skills with a single command:
```bash theme={null}
npx skills add velt-js/agent-skills
```
Skills are automatically available once installed. Your AI agent will use them when relevant tasks are detected.
## Available Skills
The repository contains skills covering the core areas of the Velt SDK:
> [card] velt-setup-best-practices
>
> **24 rules** across 8 categories covering installation, VeltProvider configuration, user authentication, JWT tokens, and document initialization.
>
> Use when setting up Velt in a new React, Next.js, Angular, Vue, or HTML project.
> [card] velt-comments-best-practices
>
> **69 rules** across 12 categories covering comment modes (Freestyle, Popover, Stream, Text, Page, Inline), rich text editor integrations (Tiptap, SlateJS, Lexical), standalone components, and media/chart comments.
>
> Use when adding collaborative commenting to your application.
> [card] velt-crdt-best-practices
>
> **44 rules** across 5 categories covering CRDT store setup, Tiptap, BlockNote, CodeMirror, and ReactFlow integrations.
>
> Use when implementing real-time collaborative editing.
> [card] velt-notifications-best-practices
>
> **17 rules** across 8 categories covering notification panels, data access, delivery channels, and webhook integrations.
>
> Use when adding in-app notifications or email delivery.
> [card] velt-recorder-best-practices
>
> **23 rules** covering audio, video, and screen recording setup, VeltRecorderTool configuration, floating control panels, pinned recording notes, RecordingPlayback with VeltRecorderPlayer, and UI wireframes.
>
> Use when adding recording features to your application.
> [card] velt-single-editor-mode-best-practices
>
> **14 rules** across 7 categories covering exclusive editing access, editor/viewer role management, access request handoff, element-level sync control, timeout-based editor transfer, and multi-tab restrictions.
>
> Use when implementing one-user-at-a-time editing with live content sync.
> [card] velt-self-hosting-data-best-practices
>
> **21 rules** across 8 categories covering data providers (comments, attachments, reactions, recordings, notifications, users), backend API routes, Python SDK (velt-py), Node SDK (@veltdev/node), type definitions, and response format contracts.
>
> Use when storing user-generated content on your own infrastructure instead of Velt servers.
> [card] velt-activity-best-practices
>
> **11 rules** across 5 categories covering real-time activity feeds, VeltActivityLog component, custom activity logging, CRDT debounce configuration, type-safe action type filtering, and server-side REST API.
>
> Use when adding activity logs, audit trails, or real-time event feeds.
> [card] velt-presence-best-practices
>
> **13 rules** covering user presence avatars, online/away/offline status indicators, inactivity timeout configuration, location-based presence filtering, and presence data subscriptions.
>
> Use when adding real-time user presence to your application.
> [card] velt-cursors-best-practices
>
> **11 rules** covering live cursor tracking, avatar-mode cursors, element whitelisting, inactivity timeouts, and cursor position subscriptions.
>
> Use when adding real-time cursor sharing across collaborators.
> [card] velt-huddle-best-practices
>
> **10 rules** covering audio/video/screen sharing huddles, ephemeral chat, flock mode (follow-me), cursor-mode huddle bubbles, and webhook integration.
>
> Use when adding in-app audio/video calls or screen sharing.
> [card] velt-rest-apis-best-practices
>
> **9 rules** covering Velt REST API v2 endpoints, JWT token generation, webhook handling (comment events, huddle events, CRDT updates), and server-side user/document/organization management.
>
> Use when calling Velt APIs from your backend or handling Velt webhooks.
> [card] velt-proxy-server-best-practices
>
> **14 rules** covering reverse proxy (nginx) setup for all 6 Velt service hosts (CDN, API, persistence DB, ephemeral DB, storage, auth), proxyConfig SDK configuration, CSP whitelisting, Subresource Integrity (SRI), and forceLongPolling.
>
> Use when routing Velt SDK traffic through your own reverse proxy.
> [card] velt-rewriter-best-practices
>
> **2 rules** covering the AI text-rewriter: programmatic control of the default selection toolbar via `RewriterElement.enableDefaultUI()` / `disableDefaultUI()`, and the open `AiModel` union type on `RewriterAskAiRequest.model` (OpenAI, Anthropic, Gemini identifiers + open-string escape hatch).
>
> Use when adding the AI rewriter to your application or replacing the default rewriter toolbar with a custom UI.
## How Skills Are Organized
Each skill follows a consistent structure:
```
skills/{skill-name}/
SKILL.md # Agent-facing manifest (when to apply, category index)
AGENTS.md # Generated compressed index of all rules
AGENTS.full.md # Generated verbose guide with all rules expanded
README.md # Contributor guide
metadata.json # Version, organization, and metadata
rules/
_sections.md # Section definitions and ordering
_template.md # Template for new rules
shared/ # Framework-agnostic rules
react/ # React / Next.js specific rules
non-react/ # Non-React specific rules
```
Rules are organized into **category folders** (e.g., `core/`, `panel/`, `data/`) within framework groups (`shared/`, `react/`, `non-react/`). Each rule file is named `{prefix}-{descriptive-name}.md` where the prefix matches its category.
## How to Pick the Right Skill
| You want to... | Use this skill |
| - | - |
| Set up Velt for the first time | `velt-setup-best-practices` |
| Add comments (any mode or editor) | `velt-comments-best-practices` |
| Add real-time collaborative editing (CRDT/Yjs) | `velt-crdt-best-practices` |
| Add notifications or email delivery | `velt-notifications-best-practices` |
| Add audio/video/screen recording | `velt-recorder-best-practices` |
| Add exclusive editing (one editor at a time) | `velt-single-editor-mode-best-practices` |
| Store data on your own database | `velt-self-hosting-data-best-practices` |
| Add activity logs or audit trails | `velt-activity-best-practices` |
| Add user presence avatars | `velt-presence-best-practices` |
| Add live cursor tracking | `velt-cursors-best-practices` |
| Add audio/video huddles | `velt-huddle-best-practices` |
| Call Velt REST APIs or handle webhooks | `velt-rest-apis-best-practices` |
| Use a Python backend SDK | `velt-self-hosting-data-best-practices` (covers `velt-py`) |
| Use a TypeScript/Node.js backend SDK | `velt-self-hosting-data-best-practices` (covers `@veltdev/node`) |
| Route Velt traffic through a reverse proxy | `velt-proxy-server-best-practices` |
| Add the AI text-rewriter or replace its default toolbar | `velt-rewriter-best-practices` |
## Example Prompts
Once skills are installed, you can give your AI agent prompts like these. The agent will automatically reference the relevant skill rules.
**Setting up Velt in a new project:**
```
Set up Velt collaboration in my Next.js app. I need comments and presence.
My API key is in .env.local as NEXT_PUBLIC_VELT_API_KEY.
```
**Adding CRDT collaborative editing:**
```
Set up Velt CRDT for my Tiptap editor. The document ID comes from
the route parameter. Ask me for any identifiers you need.
```
**Debugging an integration issue:**
```
Help me debug why my collaborative cursors aren't showing.
Check the Velt skills for correct setup patterns before suggesting fixes.
```
## Rule Priority Levels
Each rule in a skill is assigned an impact level so the agent knows what matters most:
| Level | Improvement | Examples |
| - | - | - |
| **CRITICAL** | Prevents failure or 10-100x improvement | Provider setup, authentication, core initialization |
| **HIGH** | Major quality gain (5-20x) | Comment modes, CRDT editor integration |
| **MEDIUM-HIGH** | Significant benefit (2-5x) | Standalone components, design patterns |
| **MEDIUM** | Noticeable gain (1.5-3x) | UI customization, data handling |
| **LOW-MEDIUM** | Minor benefit (1.2-2x) | Configuration, debugging patterns |
| **LOW** | Incremental or edge cases | Advanced techniques, polish |
## Staying Up to Date
Skills are updated as the Velt SDK evolves with new features, API changes, and improved patterns. To pull the latest rules into your project, re-run the install command:
```bash theme={null}
npx skills add velt-js/agent-skills
```
This will fetch the latest version of all skills, including any new rules or updated code examples.
You can also watch the [agent-skills GitHub repository](https://github.com/velt-js/agent-skills) to get notified when new skills or rules are published. For broader SDK updates and announcements, follow us on [X](https://x.com/veltjs) and [LinkedIn](https://www.linkedin.com/company/veltjs/).
## Next Steps
* **[Quickstart](/docs/get-started/quickstart)**: Set up Velt in your app from scratch
* **[Comments Overview](/docs/async-collaboration/comments/overview)**: Learn about Velt's commenting features
* **[Notifications Overview](/docs/async-collaboration/notifications/overview)**: Learn about in-app notifications
* **[Key Concepts](/docs/key-concepts/overview)**: Understand documents, locations, users, and access control
# UI Customization Plugin
Source: https://velt.dev/docs/get-started/ui-customization-plugin
Install the velt-customize plugin in Cursor or Claude Code to turn a Figma design into clean Velt UI customization (comments + notifications) on your React app.
Turn a **Figma design** into working **Velt UI customization** directly in your AI coding editor. The `velt-customize` plugin reads your design from Figma, plans the customization surface by surface, builds it in your app, and verifies each result against the design in a real browser, or honestly reports what the Velt SDK can't do yet.
> [card] [Cursor Plugin](https://github.com/velt-js/velt-figma-plugin-cursor)
>
> velt-js/velt-figma-plugin-cursor
> [card] [Claude Code Plugin](https://github.com/velt-js/velt-figma-plugin-claude)
>
> velt-js/velt-figma-plugin-claude
## When to Use
* You have a Figma design for how Velt comments or notifications should look in your product
* You want your AI agent to build the customization for you (CSS, wireframes, or primitives) instead of hand-writing it
* You want every result verified against the design in a live browser, not just generated and hoped for
**No Figma design?** Follow the [UI Customization guide](/docs/ui-customization/overview) manually; the plugin currently requires Figma.
> [!NOTE]
>
> This plugin customizes Velt's **UI** on an app where Velt is already installed and working. If you haven't set up Velt yet, start with the [Installation Plugin](/docs/get-started/installation-plugin) or [Quickstart](/docs/get-started/quickstart) first.
## Prerequisites
* **Node.js** 18+
* A **React app** with `@veltdev/react` installed, authenticated, and rendering Velt's default UI
* A **Figma design** of your desired Velt UI, plus a [Figma personal access token](https://www.figma.com/developers/api#access-tokens) (figma.com → Settings → Security → Personal access tokens)
* **Chrome** with the Claude in Chrome extension (Claude Code), or Cursor's built-in browser, to verify results against the design
* **`playwright-core`** (Cursor install step below) for device-resolution screenshot capture
## Quickstart
> [tab] Cursor
>
> 1. Clone the plugin repository and install it:
>
> ```bash theme={null}
> git clone https://github.com/velt-js/velt-figma-plugin-cursor.git
> cd velt-figma-plugin-cursor
> npm run all
> ```
>
> This validates the plugin and copies its skills, rules, commands, and agents into `~/.cursor/`. **Fully restart Cursor** afterwards. If you later move the repo or pull updates, run `npm run all` again.
>
> 2. Store your Figma token (kept in your OS keychain, never in a file):
>
> ```bash theme={null}
> node scripts/figma-extract.mjs token set
> ```
>
> 3. Install the one screenshot dependency:
>
> ```bash theme={null}
> npm i -g playwright-core
> ```
>
> 4. Open **your app's repo** in Cursor (not the plugin repo), make sure the app is running, and start a run:
>
> ```
> /velt-customize-run --mode "wireframes + primitives" --budget balanced
> ```
>
> `` is the exact page where Velt renders in your running app (e.g. `http://localhost:3000/inline-comments?documentId=my-run-1`). Include a run-unique `documentId` so runs never pollute each other's comment data.
> [tab] Claude Code
>
> 1. Inside Claude Code, install the plugin and restart:
>
> ```
> /plugin marketplace add velt-js/velt-figma-plugin-claude
> /plugin install velt-customize@velt-customize
> ```
>
> Then restart Claude Code (or run `/reload-plugins`).
>
> 2. Store your Figma token (kept in your OS keychain, never in a file). Run this **inside Claude Code** (`$CLAUDE_PLUGIN_ROOT` only exists there), or just ask Claude to run it:
>
> ```bash theme={null}
> node "$CLAUDE_PLUGIN_ROOT/scripts/figma-extract.mjs" token set
> ```
>
> 3. Connect the **Claude in Chrome** extension. The plugin uses Chrome to check your running app against the design.
>
> 4. Open your app's folder in Claude Code, make sure your dev server can run, and start a run:
>
> ```
> /velt-customize:run --mode "wireframes + primitives" --budget balanced
> ```
>
> `` is the exact page where Velt renders in your running app (e.g. `http://localhost:3000/inline-comments?documentId=my-run-1`). Include a run-unique `documentId` so runs never pollute each other's comment data.
> [!NOTE]
>
> A **Loop** is just a Figma section or frame that groups the design frames you want built, in order. The Figma URL must point at one Loop node in your file (right-click the Loop → Copy link), not the whole file. Keep a Loop to 8 frames or fewer; split bigger designs into several Loops and run them one at a time. The app URL is **required** too; without it the run halts and asks for it. Preflight verifies that Velt actually renders at that URL.
> [!NOTE]
>
> A full customization run can take **up to about 4 hours**, depending on Loop size, `--budget`, and how many fix iterations the verification agent (the Judge) needs. Plan to leave the editor and app running until the handoff report finishes.
### Run Options
| Flag | Values | Description |
| - | - | - |
| `--mode` | `strictly wireframe`, `strictly primitives`, `wireframes + primitives`, `freeform` | How the plugin is allowed to build; these correspond to the [Wireframes](/docs/ui-customization/layout) and [Primitives](/docs/ui-customization/primitives) approaches. Leave it out and it asks you, with a recommendation |
| `--budget` | `strict`, `balanced`, `thorough` | How much polish effort per design frame/surface, also caps fix iterations per defect (6 / 8 / 12) |
| `--auto` | - | Fully unattended run (CI/cloud): no questions asked. Requires `--mode`; reads the Figma token from the `FIGMA_TOKEN` environment variable. `--cloud` is a legacy alias |
## What's Included
| Resource | Count | Description |
| - | - | - |
| **Commands** | 5 | Run, fix, replay, clear, and memory (see below) |
| **Agents** | 6 | `velt-orchestrator` (drives the run), `velt-planner-structure` and `velt-planner-style` (plan structure, then styles against the real rendered DOM), `velt-builder` (builds), `velt-judge-2` (independently verifies), `velt-judge` (legacy) |
| **Skills** | 14 | Customization approaches (CSS, wireframes, primitives), extraction, verification, comments, notifications, references, and rules |
| **Guide** | 1 | A bundled customization knowledge base: the single source of truth the agents read on every run (same content as the [UI Customization](/docs/ui-customization/overview) docs) |
## Available Commands
| Cursor | Claude Code | Description |
| - | - | - |
| `/velt-customize-run ` | `/velt-customize:run ` | Start a customization run from a Figma Loop node URL and live app page |
| `/velt-customize-fix ""` | `/velt-customize:fix ""` | Surgically fix one described mismatch, then re-verify the affected area |
| `/velt-customize-replay` | `/velt-customize:replay` | Open the session-replay player for every stage, measurement, and fix of a run, with screenshots |
| `/velt-customize-clear` | `/velt-customize:clear` | Wipe run state and start fresh (does not touch generated code) |
| `/velt-customize-memory` | `/velt-customize:memory` | Inspect what the plugin has learned across runs |
## How It Works
Each run follows a plan → approve → two-phase build → verify loop:
1. **Plan structure**: reads your Figma Loop via the Figma REST API, recognizes which Velt component each design element is, and picks the cheapest viable approach per surface
2. **Approach gate**: shows you a per-surface coverage matrix with a recommendation and **waits for your confirmation** before building anything
3. **Structure build**: mounts a bare wireframe skeleton (no cosmetic CSS) family by family
4. **DOM snapshot → style plan → style build**: snapshots the real rendered DOM, maps the design's exact values onto real selectors, then applies styles
5. **Judge → fix**: an independent fresh-context Judge (`velt-judge-2`) verifies the whole design in a live browser with screenshot evidence. Each defect is fixed and re-measured until it's clean, or documented as a blocker or SDK gap
6. **Report**: coverage achieved, screenshots, any SDK gaps, and the generated code under `components/velt/ui-customization/`
You can watch progress live from a second terminal:
> [tab] Cursor
>
> ```bash theme={null}
> node /path/to/velt-figma-plugin-cursor/scripts/progress.mjs --watch
> ```
> [tab] Claude Code
>
> ```bash theme={null}
> node "$CLAUDE_PLUGIN_ROOT/scripts/progress.mjs" --watch
> ```
After a run, `/velt-customize-replay` (Cursor) or `/velt-customize:replay` (Claude Code) opens a session-replay player over every stage, measurement, and fix, with screenshots, so you can scrub to where something drifted.
## Troubleshooting
### The run halts at preflight
Preflight checks every prerequisite (Figma token, browser, target app URL, Node version) and halts with the exact fix if any is missing. Follow the printed instruction and re-run the command.
### "No Figma token" error
Design intake uses the Figma REST API and requires a token. There is no Figma desktop fallback. Store one with `figma-extract.mjs token set`, or set the `FIGMA_TOKEN` environment variable in CI/cloud environments. Verify with `figma-extract.mjs token status`.
### Commands don't appear after install
Restart your editor fully. Cursor loads plugin files from `~/.cursor/` (re-run `npm run all` after moving or updating the repo), and Claude Code registers plugin commands at startup (or use `/reload-plugins`).
### App URL doesn't render Velt
Pass the exact page where Velt comments or notifications are mounted, not just the app origin. Preflight verifies that URL; if Velt isn't there, fix the URL and re-run. Include a unique `documentId` query param so concurrent runs don't share comment data.
***
## Next Steps
* [UI Customization](/docs/ui-customization/overview): the customization guide the plugin agents read on every run
* [Installation Plugin](/docs/get-started/installation-plugin): Velt SDK knowledge, skills, and MCP servers for your editor
* [Quickstart](/docs/get-started/quickstart): set up Velt in your app first
# CSS Injection
Source: https://velt.dev/docs/global-styles/css-injection
> [tab] React / Next.js
>
> ## Custom CSS Injection
>
> You can inject CSS with our special `client.injectCustomCss()` method.
>
> ### Passing style definition via string
>
> ```jsx theme={null}
> client?.injectCustomCss({
> type: 'styles',
> value: `
> .modal-div.dialog .modal-author__name {
> font-size: 10rem !important;
> background-color: green !important;
> color: white !important;
> }
> `
> });
> ```
>
> ### Passing style via link.
>
> ```jsx theme={null}
> client?.injectCustomCss({
> type: 'link',
> value: '/relative_path_to_css/styles.css' // you could also pass the absolute link: 'https://yourappdomain.com/pathtocss/styles.css'
> });
> ```
> [tab] Other Frameworks
>
> ## Custom CSS Injection
>
> You can inject CSS with our special `client.injectCustomCss()` method.
>
> ### Passing style definition via string
>
> ```jsx theme={null}
> Velt?.injectCustomCss({
> type: 'styles',
> value: `
> .modal-div.dialog .modal-author__name {
> font-size: 10rem !important;
> background-color: green !important;
> color: white !important;
> }
> `
> });
> ```
>
> ### Passing style via link.
>
> ```jsx theme={null}
> Velt?.injectCustomCss({
> type: 'link',
> value: '/relative_path_to_css/styles.css' // you could also pass the absolute link: 'https://yourappdomain.com/pathtocss/styles.css'
> });
> ```
```jsx React / Next.js theme={null}
import { useVeltClient } from '@veltdev/react';
import { useEffect, useState } from 'react';
export default function YourDocument() {
const { client } = useVeltClient();
useEffect(() => {
if (client) {
client?.injectCustomCss({
type: 'styles',
value: `
.modal-div.dialog .modal-author__name {
font-size: 10rem !important;
background-color: green !important;
color: white !important;
}
`
});
client?.injectCustomCss({
type: 'link',
value: '/relative_path_to_css/styles.css' // you could also pass the absolute link: 'https://yourappdomain.com/pathtocss/styles.css'
});
}
}, [client]);
return (
//your document template
);
}
```
```html HTML theme={null}
```
# Dark Mode
Source: https://velt.dev/docs/global-styles/dark-mode
> [tab] React / Next.js
>
> ## Enable Dark Mode on all Components
>
> To enable Dark Mode on all Components, call the `client.setDarkMode(true)`
>
> ```jsx theme={null}
> let client = useVeltClient();
> client.setDarkMode(true);
> ```
>
> ## Enable Dark Mode on individual Components
>
> To enable Dark Mode on individual components, set the `darkMode` attribute to `true`.
>
> ```jsx theme={null}
>
>
>
>
>
> ```
>
> API Methods:
>
> ```jsx theme={null}
> commentElement.enableDarkMode()
> commentElement.disableDarkMode()
> ```
> [tab] Other Frameworks
>
> ## Enable Dark Mode on all Components
>
> To enable Dark Mode on all Components, call the `Velt.setDarkMode(true)`
>
> ```jsx theme={null}
> Velt.setDarkMode(true);
> ```
>
> ## Enable Dark Mode on individual Components
>
> To enable Dark Mode on individual components, set the `dark-mode` attribute to `true`.
>
> ```jsx theme={null}
>
>
>
>
>
> ```
>
> API Methods:
>
> ```jsx theme={null}
> commentElement.enableDarkMode()
> commentElement.disableDarkMode()
> ```
# Global Styles
Source: https://velt.dev/docs/global-styles/global-styles
To edit the styling for all Velt components, you can use the following global CSS variables. This is recommended over editing the CSS for each tool individually.
```scss theme={null}
// default state
--velt-tool-padding: 6px;
--velt-tool-icon-size: 1.5rem;
--velt-tool-icon-color: var(--velt-neutral-4);
--velt-tool-border-radius: 50px;
--velt-tool-border-color: transparent;
--velt-tool-border: 2px solid var(--velt-tool-border-color);
--velt-tool-bg-color: transparent;
// default focus state
--velt-tool-focus-icon-size: var(--velt-tool-icon-size);
--velt-tool-focus-icon-color: var(--velt-tool-icon-color);
--velt-tool-focus-border-radius: var(--velt-tool-border-radius);
--velt-tool-focus-border-color: var(--velt-neutral-7);
--velt-tool-focus-border: 2px solid var(--velt-tool-focus-border-color);
--velt-tool-focus-bg-color: var(--velt-tool-bg-color);
// default hover state
--velt-tool-hover-icon-size: var(--velt-tool-icon-size);
--velt-tool-hover-icon-color: var(--velt-neutral-3);
--velt-tool-hover-border-radius: var(--velt-tool-border-radius);
--velt-tool-hover-border-color: var(--velt-neutral-7);
--velt-tool-hover-border: 2px solid var(--velt-tool-hover-border-color);
--velt-tool-hover-bg-color: var(--velt-neutral-7);
// active state
--velt-tool-active-icon-size: var(--velt-tool-icon-size);
--velt-tool-active-icon-color: var(--velt-neutral-9);
--velt-tool-active-border-radius: var(--velt-tool-border-radius);
--velt-tool-active-border-color: var(--velt-purple);
--velt-tool-active-border: 2px solid var(--velt-tool-active-border-color);
--velt-tool-active-bg-color: var(--velt-purple);
// active focus state
--velt-tool-active-focus-icon-size: var(--velt-tool-icon-size);
--velt-tool-active-focus-icon-color: var(--velt-tool-icon-color);
--velt-tool-active-focus-border-radius: var(--velt-tool-border-radius);
--velt-tool-active-focus-border-color: rgba(255, 255, 255, 0.24);
--velt-tool-active-focus-border: 2px solid
var(--velt-tool-active-focus-border-color);
--velt-tool-active-focus-bg-color: var(--velt-purple);
// active hover state
--velt-tool-active-hover-icon-size: var(--velt-tool-icon-size);
--velt-tool-active-hover-icon-color: var(--velt-tool-icon-color);
--velt-tool-active-hover-border-radius: var(--velt-tool-border-radius);
--velt-tool-active-hover-border-color: #433fa7;
--velt-tool-active-hover-border: 2px solid
var(--velt-tool-active-hover-border-color);
--velt-tool-active-hover-bg-color: #433fa7;
```
```scss Styles.css theme={null}
// default state
--velt-tool-padding: 6px;
--velt-tool-icon-size: 1.5rem;
--velt-tool-icon-color: var(--velt-neutral-4);
--velt-tool-border-radius: 50px;
--velt-tool-border-color: transparent;
--velt-tool-border: 2px solid var(--velt-tool-border-color);
--velt-tool-bg-color: transparent;
// default focus state
--velt-tool-focus-icon-size: var(--velt-tool-icon-size);
--velt-tool-focus-icon-color: var(--velt-tool-icon-color);
--velt-tool-focus-border-radius: var(--velt-tool-border-radius);
--velt-tool-focus-border-color: var(--velt-neutral-7);
--velt-tool-focus-border: 2px solid var(--velt-tool-focus-border-color);
--velt-tool-focus-bg-color: var(--velt-tool-bg-color);
// default hover state
--velt-tool-hover-icon-size: var(--velt-tool-icon-size);
--velt-tool-hover-icon-color: var(--velt-neutral-3);
--velt-tool-hover-border-radius: var(--velt-tool-border-radius);
--velt-tool-hover-border-color: var(--velt-neutral-7);
--velt-tool-hover-border: 2px solid var(--velt-tool-hover-border-color);
--velt-tool-hover-bg-color: var(--velt-neutral-7);
// active state
--velt-tool-active-icon-size: var(--velt-tool-icon-size);
--velt-tool-active-icon-color: var(--velt-neutral-9);
--velt-tool-active-border-radius: var(--velt-tool-border-radius);
--velt-tool-active-border-color: var(--velt-purple);
--velt-tool-active-border: 2px solid var(--velt-tool-active-border-color);
--velt-tool-active-bg-color: var(--velt-purple);
// active focus state
--velt-tool-active-focus-icon-size: var(--velt-tool-icon-size);
--velt-tool-active-focus-icon-color: var(--velt-tool-icon-color);
--velt-tool-active-focus-border-radius: var(--velt-tool-border-radius);
--velt-tool-active-focus-border-color: rgba(255, 255, 255, 0.24);
--velt-tool-active-focus-border: 2px solid
var(--velt-tool-active-focus-border-color);
--velt-tool-active-focus-bg-color: var(--velt-purple);
// active hover state
--velt-tool-active-hover-icon-size: var(--velt-tool-icon-size);
--velt-tool-active-hover-icon-color: var(--velt-tool-icon-color);
--velt-tool-active-hover-border-radius: var(--velt-tool-border-radius);
--velt-tool-active-hover-border-color: #433fa7;
--velt-tool-active-hover-border: 2px solid
var(--velt-tool-active-hover-border-color);
--velt-tool-active-hover-bg-color: #433fa7;
```
# Customize Behavior
Source: https://velt.dev/docs/in-app-user-feedback/customize-behavior
> [tab] React
>
> ## 1. Feedback Mode
>
> By default the component will be in `Feedback` mode. This will make your component say *"Give feedback"* and have a heart icon.
>
> ```js theme={null}
>
> ```
>
> [https://landing-page-demo-velt.vercel.app/?feature=user-request\&type=user-feedback](https://landing-page-demo-velt.vercel.app/?feature=user-request\&type=user-feedback)
>
> ## 2. Report Bugs Mode
>
> To enable `Report Bugs` mode, set the type attribute to `reportBug`. This will make your component say *"Report bugs"* and have a bug icon.
>
> ```js theme={null}
>
> ```
>
> [https://landing-page-demo-velt.vercel.app/?feature=user-request\&type=report-bug](https://landing-page-demo-velt.vercel.app/?feature=user-request\&type=report-bug)
>
> ## 3. Contact Us Mode
>
> To enable `Contact Us` mode, set the type attribute to 'contactUs\`. This will make your component say *"Contact us"* and have an email icon.
>
> ```js theme={null}
>
> ```
>
> [https://landing-page-demo-velt.vercel.app/?feature=user-request\&type=contact-us](https://landing-page-demo-velt.vercel.app/?feature=user-request\&type=contact-us)
> [tab] Other Frameworks
>
> ## 1. Feedback Mode
>
> By default the component will be in `Feedback` mode. This will make your component say *"Give feedback"* and have a heart icon.
>
> ```js theme={null}
>
> ```
>
> [https://landing-page-demo-velt.vercel.app/?feature=user-request\&type=user-feedback](https://landing-page-demo-velt.vercel.app/?feature=user-request\&type=user-feedback)
>
> ## 2. Report Bugs Mode
>
> To enable `Report Bugs` mode, set the type attribute to `reportBug`. This will make your component say *"Report bugs"* and have a bug icon.
>
> ```js theme={null}
>
> ```
>
> [https://landing-page-demo-velt.vercel.app/?feature=user-request\&type=report-bug](https://landing-page-demo-velt.vercel.app/?feature=user-request\&type=report-bug)
>
> ## 3. Contact Us Mode
>
> To enable `Contact Us` mode, set the type attribute to 'contactUs\`. This will make your component say *"Contact us"* and have an email icon.
>
> ```js theme={null}
>
> ```
>
> [https://landing-page-demo-velt.vercel.app/?feature=user-request\&type=contact-us](https://landing-page-demo-velt.vercel.app/?feature=user-request\&type=contact-us)
```js React theme={null}
import { VeltUserRequestTool } from '@veltdev/react';
function YourComponent() {
return (
{/* Feedback Mode */}
{/* Report Bug Mode */}
{/* Contact Us Mode */}
)
}
```
```html HTML theme={null}
```
# Overview
Source: https://velt.dev/docs/in-app-user-feedback/overview
> [tab] Feedback
>
> [https://landing-page-demo-velt.vercel.app/?feature=user-request\&type=user-feedback](https://landing-page-demo-velt.vercel.app/?feature=user-request\&type=user-feedback)
>
> [Open in larger window](https://landing-page-demo-velt.vercel.app/?feature=user-request\&type=user-feedback)
> [tab] Report Bug
>
> [https://landing-page-demo-velt.vercel.app/?feature=user-request\&type=report-bug](https://landing-page-demo-velt.vercel.app/?feature=user-request\&type=report-bug)
>
> [Open in larger window](https://landing-page-demo-velt.vercel.app/?feature=user-request\&type=report-bug)
> [tab] Contact Us
>
> [https://landing-page-demo-velt.vercel.app/?feature=user-request\&type=contact-us](https://landing-page-demo-velt.vercel.app/?feature=user-request\&type=contact-us)
>
> [Open in larger window](https://landing-page-demo-velt.vercel.app/?feature=user-request\&type=contact-us)
# Setup
Source: https://velt.dev/docs/in-app-user-feedback/setup
> [tab] React / Next.js
>
> ## 1. Import VeltUserRequestTool from @veltdev/react
>
> Import the `VeltUserRequestTool` component.
>
> ```js theme={null}
> import { VeltUserRequestTool } from '@veltdev/react';
> ```
>
> ## 2. Place the VeltUserRequestTool component
>
> Place the component wherever you want the invite button to appear.
>
> ```js theme={null}
>
>
>
> ```
> [tab] Other Frameworks
>
> ## 1. Place the \ component
>
> Place the component wherever you want the invite button to appear.
>
> ```jsx theme={null}
>
>
>
> ```
```js React / Next.js theme={null}
import { VeltUserRequestTool } from '@veltdev/react';
function YourComponent() {
return (
)
}
```
```html HTML theme={null}
Collaboration App
```
# AG Grid
Source: https://velt.dev/docs/integrations/ag-grid
## How to add Velt attributes to AG Grid cells?
Some Velt features like live selection require adding Velt specific attributes to the cell elements. Here's how you can do it:
1. In your AG Grid column definitions, use the `cell renderer` property to customize the cell rendering.
2. Within the `cell renderer`, add the necessary Velt attributes to the cell element.
Here's a code sample that shows how to add the `data-velt-live-selection-enabled` attribute and other required attributes to AG Grid cell div tags:
```jsx theme={null}
colDefs: ColDef[] = [
{
field: "FIELD_NAME",
cellRenderer: (params: any) => {
// Let AG Grid render the default cell, then modify the outer div
setTimeout(() => {
const cellElement = params.eGridCell;
// Add Velt attributes to the parent cell div
cellElement.setAttribute('data-velt-live-selection-enabled', 'true');
// Add other Velt attributes as required
}, 0); // Timeout to wait for the DOM to be ready
return params.value; // Use the default renderer, which is the text value
},
editable: true, // Set to true if the column is editable
},
];
```
# Overview
Source: https://velt.dev/docs/key-concepts/overview
## Overview
Velt organizes your collaborative data in a clear hierarchy. This structure helps control Velt feature data access with precision.
The hierarchy is: Organization → Folders → Documents → Locations.
Here are the core concepts:
* [Organizations](#organizations): The top-level container for everything. Think of it as your customer's entire account (e.g., Meta). It holds all their users, groups, and collaborative data.
* [Folders](#folders): A way to group and organize documents, just like in a file system. Folders can contain other folders and documents, inheriting permissions.
* [Documents](#documents): The primary collaborative space. This is where features like comments, presence, and cursors come alive. A document could be a design file, a dashboard, a spreadsheet, or a specific page in your app.
* [Locations](#locations): An optional, granular subspace within a document. If a document is a slide deck, a location is a single slide. If a document is a video, a location could be a specific timestamp.
* [Users](#users): Your end users who use your app.
* [Access Control](#access-control): The rules that control who can access what Velt feature data.
* [Authentication](#authenticate-a-user): The process of authenticating a user in Velt.
## Organizations
### Overview
An **Organization** is the top-level entity.
* It contains folders, documents, locations and users.
* Think of an `organization` as the account belonging to a company (e.g., Company A). This account may have several `users` (Company A employees). A `document` will be any file created within the organization (e.g., document, spreadsheet, slides, etc.). A `location` will be any child section within the document (e.g., slide within a presentation).
### Properties
* By default, Users within the organization can access all of its resources like folder, documents, contact list etc. This can be modified using access control settings.
* A user can be added to multiple organizations but can only log in to one organization at a time.
* Access to resources can be restricted by setting controls at the individual resource level.
### APIs
### Frontend APIs
#### Sign in User into an Organization
* Sign in the user into an organization using [these options](/docs/key-concepts/overview#sign-in-a-user).
* User needs to sign in to an organization in order to perform CRUD operations on it.
### Backend APIs
#### Create Organization
* When the user signs into an organization it will be created automatically if it doesn't exist.
* Explicitly create an organization using the REST API. [Learn more](/docs/api-reference/rest-apis/v2/organizations/add-organizations)
#### Update Organization
* Update organization using the REST API. [Learn more](/docs/api-reference/rest-apis/v2/organizations/update-organizations)
#### Delete Organization
* Delete organization using the REST API. [Learn more](/docs/api-reference/rest-apis/v2/organizations/delete-organizations)
* It will delete all the data (folders, documents, locations and users) within the organization.
#### Get Organization
* Get organization and its metadata using the REST API. [Learn more](/docs/api-reference/rest-apis/v2/organizations/get-organizations-v2)
#### Disable Organization
* Disable CRUD access to an organization using the REST API. [Learn more](/docs/api-reference/rest-apis/v2/organizations/update-organization-disable-state)
#### Provision Access to an Organization
* Provision access to an organization using [access control APIs](/docs/key-concepts/overview#access-control)
## Folders
### Overview
Folders help you organize documents in a hierarchical way, like a traditional file system.
### Properties
* Folders can contain both documents and subfolders.
* Folders use the same permission model as Organizations and Documents.
* By default, folders inherit the permission from their organization.
* A user can be added to multiple Folders but can only initialize one Folder at a time.
* By default, all Folder users have access to all Folder resources including subfolders, documents, locations and user contacts.
* Access to individual resources within the Folder **cannot** be restricted by setting controls at the individual resource level.
* Access of the Folder cascades to all resources within the Folder.
### APIs
### Frontend APIs
#### Subscribe to a folder
* Subscribe to a folder and its documents using the `setDocuments` method.
* Subscribe to all documents in the folder or a specific set of documents. If you want to subscribe to specific documents in the folder then you can pass up to 30 documents at a time.
> [!NOTE]
>
> **Filtering Behavior:** When using `setDocuments` with the `allDocuments` flag, the method automatically filters out documents the user doesn't have access to instead of failing the entire operation. The folder document limit is set to 50 documents when using `allDocuments: true`. Any documents the user doesn't have access to are silently filtered from the result.
> [tab] React / Next.js
>
> **Using Hooks:**
>
> ```jsx expandable theme={null}
> const { setDocuments } = useSetDocuments();
>
> {/* Subscribe to a folder and all its documents */}
> const rootDocument = [
> {
> id: 'document-1',
> metadata: {
> documentName: 'Document 1'
> }
> }
> ];
>
> setDocuments(
> rootDocument,
> {
> folderId: 'folder1',
> allDocuments: true
> }
> );
>
>
> {/* Subscribe to a folder and some documents */}
> const documents = [
> {
> id: 'document-1',
> metadata: {
> documentName: 'Document 1'
> }
> },
> {
> id: 'document-2',
> metadata: {
> documentName: 'Document 2'
> }
> }
> ];
>
> setDocuments(
> documents,
> {
> folderId: 'folder1',
> }
> );
> ```
>
> **Using API:**
>
> ```jsx expandable theme={null}
> {/* Subscribe to a folder and all its documents */}
> await client.setDocuments(
> rootDocument,
> {
> folderId: 'folder1',
> allDocuments: true
> }
> );
>
> {/* Subscribe to a folder and some documents */}
> await client.setDocuments(
> documents,
> {
> folderId: 'folder1',
> }
> );
> ```
> [tab] Other Frameworks
>
> ```js expandable theme={null}
> // Subscribe to a folder and all its documents
> const rootDocument = [
> {
> id: 'document-1',
> metadata: {
> documentName: 'Document 1'
> }
> }
> ];
>
> await Velt.setDocuments(
> rootDocument,
> {
> folderId: 'folder1',
> allDocuments: true
> }
> );
>
> // Subscribe to a folder and some documents
>
> const documents = [
> {
> id: 'document-1',
> metadata: {
> documentName: 'Document 1'
> }
> },
> {
> id: 'document-2',
> metadata: {
> documentName: 'Document 2'
> }
> }
> ];
>
> await Velt.setDocuments(
> documents,
> {
> folderId: 'folder1',
> }
> );
> ```
#### Fetch folder metadata
* Retrieve folder metadata and its subfolders using either `organizationId` or `folderId`, with support for pagination.
> [tab] React / Next.js
>
> ```jsx expandable theme={null}
> // Get all folders for a specific organization
> const folderMetadata = await client.fetchFolders({
> organizationId: 'org1'
> });
>
> // Get a specific folder's metadata with its immediate subfolders
> const folderMetadata = await client.fetchFolders({
> organizationId: 'org1',
> folderId: 'folder1'
> });
>
> console.log(folderMetadata); // { data: { folder1: { ... } }, nextPageToken: '...' }
> ```
> [tab] Other Frameworks
>
> ```js expandable theme={null}
> // Get all folders for a specific organization
> const folderMetadata = await Velt.fetchFolders({
> organizationId: 'org1'
> });
>
> // Get a specific folder's metadata with its immediate subfolders
> const folderMetadata = await Velt.fetchFolders({
> organizationId: 'org1',
> folderId: 'folder1'
> });
>
> console.log(folderMetadata); // { data: { folder1: { ... } }, nextPageToken: '...' }
> ```
### Backend APIs
#### Create Folder
* Create a folder using the REST API. [Learn more](/docs/api-reference/rest-apis/v2/folders/add-folder)
#### Update Folder
* Update folder using the REST API. [Learn more](/docs/api-reference/rest-apis/v2/folders/update-folder)
#### Move Documents to Folder
* Move documents to a folder using the REST API. [Learn more](/docs/api-reference/rest-apis/v2/documents/move-documents)
#### Delete Folder
* Delete folder using the REST API. [Learn more](/docs/api-reference/rest-apis/v2/folders/delete-folder)
* It will delete all the data (subfolders, documents, locations and users) within the folder.
#### Get Folder
* Get folder and its metadata using the REST API. [Learn more](/docs/api-reference/rest-apis/v2/folders/get-folders)
#### Update Folder Access Type
* Update the access type of a folder using the REST API. [Learn more](/docs/api-reference/rest-apis/v2/folders/update-folder-access)
#### Provision Access to a Folder
Provision access to a folder using [access control APIs](/docs/key-concepts/overview#access-control)
## Documents
### Overview
A **Document** is a collaborative space within an Organization where users work together in real time. Each document includes:
* Feature data (such as Comments, Presence, Cursors, etc.)
* Locations
* Users (distinct from Organization users; see Access Control for details)
For example, in a slide presentation app, the whole slide deck would be a single document.
### Properties
* Anyone connected to the same `documentId` can see and interact with each other's activity, like presence, cursors, comments etc.
* Users can subscribe to a single document or multiple documents at the same time.
* Document inherits the permission from its organization and parent folder.
* A user can be added to multiple Documents.
* You can set Document level access control to override the Organization's access control it inherited but not the Folder's access control.
> [!NOTE]
>
> **Document Access Priority:** Document-level access settings now take priority over folder-level access settings. If a document has its own explicit access configuration, those settings will be used. If the document doesn't have explicit access settings, it will inherit from its parent folder or organization.
### Monthly Active Documents (MADs)
Velt bills on **Monthly Active Documents (MADs)**, not seats or connections.
* A **MAD** is a unique document that receives at least one CRUD operation from any Velt feature during the calendar month. Features include comments, notifications, CRDT, reactions, and recorder.
* Documents that only initialize but never receive a Velt CRUD operation do **not** count as a MAD. For example, a user opens a page and connects to Velt without triggering any CRUD activity.
* Velt does not bill for connections alone. Billing applies only to Velt SDK CRUD usage.
* MAD is distinct from **MAR (Monthly Active Room)**, which counts a document as active on connection alone. In practice, MADs are a subset of MARs.
For plan-level MAD limits, see the [pricing page](https://velt.dev/pricing).
### APIs
### Frontend APIs
#### Subscribe to Documents
* Use this to set and subscribe to one or multiple documents at the same time.
* You can specify 30 documents at a time.
* The first document in the list will be considered as the root document.
* For features like comments, notifications, recorder, reactions etc. you will be able to read and write to multiple documents at the same time.
* For features like cursors, presence, huddle, live state sync etc. it will default to the root document.
* Sidebar will automatically show data from all the documents.
> [!WARNING]
>
> **Access Filtering:** The `setDocuments` method now filters out documents the user doesn't have access to instead of failing the entire operation. Previously, if any document in the array was inaccessible, the entire query would fail. Now only accessible documents are subscribed, and inaccessible ones are silently filtered out.
**Params:**
* `documents`: [Document\[\]](/docs/api-reference/sdk/models/data-models#document)
* `options?`: [SetDocumentsRequestOptions](/docs/api-reference/sdk/models/data-models#setdocumentsrequestoptions)
> [tab] React / Next.js
>
> **Using Hooks:**
>
> ```jsx theme={null}
> const documents = [
> {
> id: 'document-1',
> metadata: {
> documentName: 'Document 1'
> }
> },
> {
> id: 'document-2',
> metadata: {
> documentName: 'Document 2'
> }
> }
> ];
> const { setDocuments } = useSetDocuments();
> setDocuments(documents);
> ```
>
> **Using API:**
>
> ```jsx theme={null}
> const documents = [
> {
> id: 'document-1',
> metadata: {
> documentName: 'Document 1'
> }
> },
> {
> id: 'document-2',
> metadata: {
> documentName: 'Document 2'
> }
> }
> ];
> await client.setDocuments(documents);
> ```
> [tab] Other Frameworks
>
> **Using API:**
>
> ```js theme={null}
> const documents = [
> {
> id: 'document-1',
> metadata: {
> documentName: 'Document 1'
> }
> },
> {
> id: 'document-2',
> metadata: {
> documentName: 'Document 2'
> }
> }
> ];
> await Velt.setDocuments(documents);
> ```
**With Options:**
> [tab] React / Next.js
>
> **Subscribe to all documents in a folder:**
>
> ```jsx theme={null}
> const { setDocuments } = useSetDocuments();
>
> setDocuments(
> [{ id: 'document-1', metadata: { documentName: 'Document 1' } }],
> {
> folderId: 'my-folder-id',
> allDocuments: true
> }
> );
> ```
>
> **Filter by location and specify a root document:**
>
> ```jsx theme={null}
> const { setDocuments } = useSetDocuments();
>
> setDocuments(
> [
> { id: 'document-1', metadata: { documentName: 'Document 1' } },
> { id: 'document-2', metadata: { documentName: 'Document 2' } }
> ],
> {
> locationId: 'scene-1',
> rootDocumentId: 'document-2'
> }
> );
> ```
>
> **Override the debounce window:**
>
> ```jsx theme={null}
> const { setDocuments } = useSetDocuments();
>
> setDocuments(
> [{ id: 'document-1', metadata: { documentName: 'Document 1' } }],
> {
> debounceTime: 300
> }
> );
> ```
>
> **Filter by context fields:**
>
> ```jsx theme={null}
> const { setDocuments } = useSetDocuments();
>
> setDocuments(
> [{ id: 'document-1', metadata: { documentName: 'Document 1' } }],
> {
> context: {
> customField: 'value'
> }
> }
> );
> ```
> [tab] Other Frameworks
>
> **Subscribe to all documents in a folder:**
>
> ```js theme={null}
> await Velt.setDocuments(
> [{ id: 'document-1', metadata: { documentName: 'Document 1' } }],
> {
> folderId: 'my-folder-id',
> allDocuments: true
> }
> );
> ```
>
> **Filter by location and specify a root document:**
>
> ```js theme={null}
> await Velt.setDocuments(
> [
> { id: 'document-1', metadata: { documentName: 'Document 1' } },
> { id: 'document-2', metadata: { documentName: 'Document 2' } }
> ],
> {
> locationId: 'scene-1',
> rootDocumentId: 'document-2'
> }
> );
> ```
>
> **Override the debounce window:**
>
> ```js theme={null}
> await Velt.setDocuments(
> [{ id: 'document-1', metadata: { documentName: 'Document 1' } }],
> {
> debounceTime: 300
> }
> );
> ```
>
> **Filter by context fields:**
>
> ```js theme={null}
> await Velt.setDocuments(
> [{ id: 'document-1', metadata: { documentName: 'Document 1' } }],
> {
> context: {
> customField: 'value'
> }
> }
> );
> ```
##### **Read/Write data from multiple documents on the same page**
* If you want to display data (eg: comments) from multiple documents on the same page, add `data-velt-document-id` attribute to the container that contains the `document`.
* It will be used to identify which part of the DOM belongs to which document.
* With no boundary, comments from all loaded documents render, and new comments save to the root document.
* With a boundary set for a document, that document's comments render and save only inside its boundary.
* Documents without a boundary follow the no-boundary rule above.
* Velt ignores blank values.
* Pass `document-id` on a comment bubble, comment tool, comment pin, or inline comments section to pin it to one document.
```html theme={null}
...
...
...
```
#### Filter comments by context
You can filter which comments are loaded when subscribing to documents by passing a `context.access` parameter to `setDocuments()`. This is useful when you only want to fetch specific comments **within a document** that the user has access to.
Learn more about the [Feature Level Access Control](/docs/key-concepts/overview#d-set-feature-level-permissions-using-access-context).
> [tab] React / Next.js
>
> ```jsx theme={null}
> const { client } = useVeltClient();
>
> client.setDocuments(documents, {
> context: {
> access: {
> entityId: ['numberOfVisitors'],
> dashboardId: ['myDashboard'],
> }
> },
> });
> ```
> [tab] Other Frameworks
>
> ```js theme={null}
> Velt.setDocuments(documents, {
> context: {
> access: {
> entityId: ['numberOfVisitors'],
> dashboardId: ['myDashboard'],
> }
> },
> });
> ```
#### Subscribe to Documents from Other Organizations
* By default, users can only access documents within their own organization.
* Enable cross-organization access by passing the target `organizationId` in the options parameter to `setDocument`/`setDocuments` (see Hook & API Example below).
* Ensure that the user has access to the target document in the target organization.
> [tab] React / Next.js
>
> **Using Hook:**
>
> ```jsx expandable theme={null}
> {/* Single Document */}
> useSetDocument("DOCUMENT_ID", {
> organizationId: 'ANOTHER_ORGANIZATION_ID'
> });
>
> {/* Multiple Documents */}
> const documents = [
> {
> id: 'document-1',
> metadata: {
> documentName: 'Document 1'
> }
> },
> {
> id: 'document-2',
> metadata: {
> documentName: 'Document 2'
> }
> }
> ];
> useSetDocuments(documents, {
> organizationId: 'ANOTHER_ORGANIZATION_ID'
> });
> ```
>
> **Using API:**
>
> ```jsx theme={null}
> {/* Single Document */}
> await client.setDocument("DOCUMENT_ID", {
> organizationId: 'ANOTHER_ORGANIZATION_ID'
> });
>
> {/* Multiple Documents */}
> const documents = [
> {
> id: 'document-1',
> metadata: {
> documentName: 'Document 1'
> }
> },
> {
> id: 'document-2',
> metadata: {
> documentName: 'Document 2'
> }
> }
> ];
> await client.setDocuments(documents, {
> organizationId: 'ANOTHER_ORGANIZATION_ID'
> });
> ```
> [tab] Other Frameworks
>
> ```javascript expandable theme={null}
> {/* Single Document */}
> await Velt.setDocument(DOCUMENT_ID, {
> organizationId: 'ANOTHER_ORGANIZATION_ID'
> });
>
> {/* Multiple Documents */}
> const documents = [
> {
> id: 'document-1',
> metadata: {
> documentName: 'Document 1'
> }
> },
> {
> id: 'document-2',
> metadata: {
> documentName: 'Document 2'
> }
> }
> ];
> await Velt.setDocuments(documents, {
> organizationId: 'ANOTHER_ORGANIZATION_ID'
> });
> ```
#### Set Root Document
* Set the root document.
* This is useful when you have multiple documents subscribed in your app and you want to change the root document during the session.
> [tab] React / Next.js
>
> ```jsx theme={null}
> await client.setRootDocument({id:'DOCUMENT_ID'})
> ```
> [tab] Other Frameworks
>
> ```javascript theme={null}
> await Velt.setRootDocument({id:'DOCUMENT_ID'})
> ```
#### Unsubscribe from Documents
* Use this to unsubscribe from all documents at once.
> [tab] React / Next.js
>
> **Using Hooks:**
>
> ```jsx theme={null}
> useUnsetDocuments();
> ```
>
> **Using API:**
>
> ```jsx theme={null}
> await client.unsetDocuments();
> ```
> [tab] Other Frameworks
>
> ```jsx theme={null}
> await Velt.unsetDocuments();
> ```
#### Get Document Metadata
* Use this to get the metadata of a Document.
* This is useful when you want to display the document name in your app or any custom metadata that you have set.
* This returns a subscription with [`DocumentMetadata`](/docs/api-reference/sdk/models/data-models#documentmetadata) object.
> [tab] React / Next.js
>
> ```jsx theme={null}
> client.getDocumentMetadata().subscribe((documentMetadata) => {
> console.log("Current document metadata: ", documentMetadata);
> });
> ```
> [tab] Other Frameworks
>
> ```jsx theme={null}
> Velt.getDocumentMetadata().subscribe((documentMetadata) => {
> console.log("Current document metadata: ", documentMetadata);
> });
> ```
#### [Fetch Documents](/docs/api-reference/sdk/api/api-methods#fetchdocuments)
* Fetch documents by organization, folder, or specific document IDs.
* Use `allDocuments: true` to fetch all documents for an organization or a specific folder.
* Supports pagination via `nextPageToken` in the response.
* When specifying individual `documentIds`, you can **pass up to 30 IDs at a time**.
> [!WARNING]
>
> This is a one-time fetch, not a realtime subscription. You will need to call again to refresh results.
**Params:**
* `request`: [FetchDocumentsRequest](/docs/api-reference/sdk/models/data-models#fetchdocumentsrequest)
* Returns: [FetchDocumentsResponse](/docs/api-reference/sdk/models/data-models#fetchdocumentsresponse)
> [tab] React / Next.js
>
> ```ts theme={null}
> // Gets all documents for given org id
> await client.fetchDocuments({ organizationId: 'org1', allDocuments: true });
>
> // Gets all documents for the given folderId
> await client.fetchDocuments({ organizationId: 'org1', folderId: 'folder1', allDocuments: true });
>
> // Gets specified documents
> await client.fetchDocuments({ organizationId: 'org1', documentIds: ['doc1', 'doc2'] });
> ```
> [tab] Other Frameworks
>
> ```js theme={null}
> // Gets all documents for given org id
> await Velt.fetchDocuments({ organizationId: 'org1', allDocuments: true });
>
> // Gets all documents for the given folderId
> await Velt.fetchDocuments({ organizationId: 'org1', folderId: 'folder1', allDocuments: true });
>
> // Gets specified documents
> await Velt.fetchDocuments({ organizationId: 'org1', documentIds: ['doc1', 'doc2'] });
> ```
### Backend APIs
#### Create Document
* Create a document using the REST API. [Learn more](/docs/api-reference/rest-apis/v2/documents/add-documents)
#### Update Document
* Update document using the REST API. [Learn more](/docs/api-reference/rest-apis/v2/documents/update-documents)
#### Delete Document
* Delete document using the REST API. [Learn more](/docs/api-reference/rest-apis/v2/documents/delete-documents)
* It will delete all the data (locations and users) within the document.
#### Get Document
* Get document and its metadata using the REST API. [Learn more](/docs/api-reference/rest-apis/v2/documents/get-documents-v2)
#### Update Document Access Type
* Update the access type of a document using the REST API. [Learn more](/docs/api-reference/rest-apis/v2/documents/update-document-access)
#### Provision Access to a Document
Provision access to a document using [access control APIs](/docs/key-concepts/overview#access-control)
#### Disable Document
* Disable CRUD access to a document using the REST API. [Learn more](/docs/api-reference/rest-apis/v2/documents/update-document-disable-state)
#### Legacy APIs
##### **Subscribe to a Single Document**
* Use this to initialize and subscribe to a single Document.
* Once you set the document, you will start receiving realtime updates from the document.
* **Params:**
* `documentId`: The unique identifier for the document.
* `metadata`: (optional) This is a key/value pair object where you can set metadata about the document such as `documentName`. documentName is a special field that we use to display the document name in some Velt Components.
> [tab] React / Next.js
>
> **Using Hooks:**
>
> ```jsx theme={null}
> useSetDocument('unique-document-id', {documentName: 'Document Name'});
> ```
>
> **Using API:**
>
> ```jsx theme={null}
> await client.setDocument('unique-document-id', {documentName: 'Document Name'});
> ```
> [tab] Other Frameworks
>
> ```jsx theme={null}
> await Velt.setDocument('unique-document-id', {documentName: 'Document Name'});
> ```
##### **Unsubscribe from a Single Document**
* Use this to unsubscribe from the root Document
* Once you unset the document, you will no longer receive realtime updates from the document.
* For some parts of your app, you may not need Velt. In such cases, you can unset the document.
> [tab] React / Next.js
>
> **Using Hooks:**
>
> ```jsx theme={null}
> useUnsetDocumentId();
> ```
>
> **Using API:**
>
> ```jsx theme={null}
> await client.unsetDocumentId();
> ```
> [tab] Other Frameworks
>
> ```jsx theme={null}
> await Velt.unsetDocumentId();
> ```
## Locations
### Overview
**Locations** are optional subspaces (JSON object) within a document, providing finer partitioning of data.
Locations can represent:
* Pages
* Sections
* Video frames
* Data points on maps/charts
* Any other contextual area
For instance:
* In a slide presentation, the entire slide presentation will be a document and each individual slide will be a location.
* In a dashboard, the entire dashboard is a document but various filters applied will be locations.
* In a video player, the entire video will be the document and timestamps will be locations.
> [!TIP]
>
> If a **Document** is like a house, a **Location** is like a room within the house.
### Properties
* Any user with access to the document will have access to all locations in the document.
* Access controls cannot be set at the location level.
* Locations automatically generate location groups in the sidebar and organizes the comments within the group.
* The location object has these fields:
* `id` (optional when `locationName` is set): A unique string or numeric identifier. An id of `0` is valid and takes precedence over `locationName`.
* `locationName` (optional when `id` is set): A non-empty, human-readable name displayed in Velt components like `VeltCommentsSidebar`. It also identifies the location when `id` is omitted.
* You can add any number of custom fields to the location object.
### APIs
### Frontend APIs
#### Subscribe to Locations
* Use this to set and subscribe to one or multiple locations at the same time.
* The first location in the list will be considered as the root location.
* Features will by default add data to the root location unless you use the location boundaries.
* Sidebar will automatically show data from all the documents.
**Params:**
* `locations`: [Location\[\]](/docs/api-reference/sdk/models/data-models#location)
* `options?`: [SetLocationsRequestOptions](/docs/api-reference/sdk/models/data-models#setlocationsrequestoptions)
* `rootLocationId`: The id of the location that will be set as the root location. If you don't specify this, the first location will be set as the root location.
* `appendLocation`: Set this to `true` to append new locations to the existing locations. By default, `setLocations` replaces the existing additional locations.
> [tab] React / Next.js
>
> **Using Hooks:**
>
> ```jsx theme={null}
> const locations = [
> {id:'location1', locationName:'Location 1'},
> {id:'location2', locationName:'Location 2'}
> ];
> const { setLocations } = useSetLocations();
> setLocations(locations);
> ```
>
> **Using API:**
>
> ```jsx theme={null}
> await client.setLocations([
> {id:'location1', locationName:'Location 1'},
> {id:'location2', locationName:'Location 2'}
> ], {rootLocationId: 'location2'}); // By default 1st location will be set as root location unless rootLocationId is specified.
>
> // Append new locations
> await client.setLocations([
> {id:'location3', locationName:'Location 3'},
> {id:'location4', locationName:'Location 4'}
> ], {appendLocation: true})
> ```
> [tab] Other Frameworks
>
> ```js theme={null}
> await Velt.setLocations([
> {id:'location1', locationName:'Location 1'},
> {id:'location2', locationName:'Location 2'}
> ], {rootLocationId: 'location2'}); // By default 1st location will be set as root location unless rootLocationId is specified.
>
> // Append new locations
> await Velt.setLocations([
> {id:'location3', locationName:'Location 3'},
> {id:'location4', locationName:'Location 4'}
> ], {appendLocation: true})
> ```
##### Read/Write data from multiple locations on the same page using Location Boundaries
* If you want to display data (eg: comments) from multiple locations on the same page, add `data-velt-location-id` attribute to the container that contains the `location`.
* It will be used to identify which part of the DOM belongs to which location.
* This ensures that the comment added within the location is associated with the correct location.
```html theme={null}
...
...
...
```
#### Set Root Location
* Set the root location.
* This is useful when you have multiple locations subscribed in your app and you want to change the root location during the session.
> [tab] React / Next.js
>
> ```jsx theme={null}
> await client.setRootLocation({id:'LOCATION_ID'})
> ```
> [tab] Other Frameworks
>
> ```javascript theme={null}
> await Velt.setRootLocation({id:'LOCATION_ID'})
> ```
#### Unsubscribe from Locations
* Unset locations by ids or all of them if you don't specify any parameters.
> [tab] React / Next.js
>
> ```jsx theme={null}
> // remove specific locations
> await client.unsetLocationsIds(['location1', 'location2', 'location3'])
>
> // remove all locations
> await client.unsetLocationsIds()
> ```
> [tab] Other Frameworks
>
> ```jsx theme={null}
> // remove specific locations
> await Velt.unsetLocationsIds(['location1', 'location2', 'location3'])
>
> // remove all locations
> await Velt.unsetLocationsIds()
> ```
#### Legacy APIs
##### **Subscribe to a Single Location**
* Use this to initialize and subscribe to a single Location.
> [tab] React / Next.js
>
> **Using Hooks:**
>
> ```jsx theme={null}
> useSetLocation({
> 'id': 'locationId1',
> 'locationName': 'MainVideoPlayer',
> 'videoFrame': '120'
> })
> ```
>
> **Using API:**
>
> ```jsx theme={null}
> client.setLocation({
> 'id': 'locationId1',
> 'locationName': 'MainVideoPlayer',
> 'videoFrame': '120'
> })
> ```
> [tab] Other Frameworks
>
> ```jsx theme={null}
> Velt.setLocation({
> 'id': 'locationId1',
> 'locationName': 'MainVideoPlayer',
> 'videoFrame': '120'
> })
> ```
##### **Subscribe to Multiple Locations**
* Use this to subscribe to multiple locations at the same time.
* Add additional locations on the page by using set location with the `true` parameter.
> [tab] React / Next.js
>
> **Using Hooks:**
>
> ```jsx expandable theme={null}
> useSetLocation({
> 'id': 'locationId1',
> 'locationName': 'MainVideoPlayer',
> 'videoFrame': '120'
> // You can keep adding more field to make the location very specific.
> // The field names can be anything.
> })
>
> useSetLocation({
> 'id': 'locationId1',
> 'locationName': 'MainVideoPlayer',
> 'videoFrame': '120'
> // You can keep adding more field to make the location very specific.
> // The field names can be anything.
> }, true)
> ```
>
> **Using API:**
>
> ```jsx theme={null}
> client.setLocation({
> 'id': 'locationId1',
> 'locationName': 'MainVideoPlayer',
> 'videoFrame': '120'
> // You can keep adding more field to make the location very specific.
> // The field names can be anything.
> });
>
> client.setLocation({
> 'id': 'locationId2',
> 'locationName': 'MainVideoPlayer2',
> 'videoFrame': '120'
> // You can keep adding more field to make the location very specific.
> // The field names can be anything.
> }, true);
> ```
> [tab] Other Frameworks
>
> ```jsx expandable theme={null}
> Velt.setLocation({
> 'id': 'locationId1',
> 'locationName': 'MainVideoPlayer',
> 'videoFrame': '120'
> // You can keep adding more field to make the location very specific.
> // The field names can be anything.
> });
>
> Velt.setLocation({
> 'id': 'locationId2',
> 'locationName': 'MainVideoPlayer2',
> 'videoFrame': '120'
> // You can keep adding more field to make the location very specific.
> // The field names can be anything.
> }, true);
> ```
## Users
### Overview
* A `User` is anyone authenticated with the Velt SDK.
* After authentication, a user's profile appears in Velt's collaboration features. For example, their name is shown next to their comments, in `@mentions`, and alongside their avatar in presence and cursor features.
### Contact List
When the user is on a document, they can `@mention` other users. By default, the contact list for the `@mention` feature includes users from:
* Organization.
* Folder.
* Document.
* User Groups.
* `@here`: This is a special group that includes only the users explicitly added on the document. This doesn't include organization users or organization user groups.
### User Groups
User Groups let you organize users into teams (like "engineering" or "marketing") for easier management and access control.
* Mention an entire group (e.g., @engineering) instead of individual users, similar to Slack.
* Organization users can be in multiple groups.
* Only organization users can join user groups.
### Properties
* Uniqueness of the user is determined by its `userId`.
* A user can be part of multiple organizations.
### APIs
### Frontend APIs
#### Authenticate a User
There are two ways to authenticate a user in Velt.
1. Using an Auth Provider (recommended)
2. Using Identify method
> [!NOTE]
>
> **Error Handling**: By default, authentication methods return `null` on failure. You can configure them to throw errors instead by setting `throwError: true`. [Learn more about error handling](/docs/get-started/advanced#error-handling-in-authentication).
##### **1. Use Auth Provider**
* With this approach, you configure an authentication provider by specifying the user you want to authenticate and a function that returns a Velt JWT token.
* This function is automatically called by Velt whenever a token is required, such as during the initial sign-in or when the token expires.
* You should define this authentication provider within the Velt Provider during your app's initialization.
* Use this to [generate a Velt JWT token.](/docs/api-reference/rest-apis/v2/auth/generate-token)
* **Params**:
* `user`: [User](/docs/api-reference/sdk/models/data-models#user)
* `retryConfig`: [AuthRetryConfig](/docs/api-reference/sdk/models/data-models#authretryconfig)
* `generateToken`: `() => Promise`
* `options`: [Options](/docs/api-reference/sdk/models/data-models#options-2)
* `authToken`: `string`
* `forceReset`: `boolean`: By default, once the user is authenticated, the authentication state is preserved in the browser and a new token is not generated until you explicitly sign them out. If you want to force re-login the user, set this to `true`.
> [tab] React / Next.js
>
> ```js theme={null}
> user,
> retryConfig: { retryCount: 3, retryDelay: 1000 },
> generateToken: async () => {
> // See generateVeltAuthToken() tab for example implementation
> const token = await generateVeltAuthToken();
> return token;
> }
> }} />
> ```
> [tab] Other Frameworks
>
> ```js theme={null}
> Velt.setVeltAuthProvider({
> user,
> retryConfig: { retryCount: 3, retryDelay: 1000 },
> generateToken: async () => {
> // See generateVeltAuthToken() tab for example implementation
> const token = await generateVeltAuthToken();
> return token;
> }
> });
>
> ```
> [tab] generateVeltAuthToken()
>
> ```ts expandable theme={null}
> // Backend example: minimal token generator
> export async function generateVeltAuthToken({
> userId,
> organizationId,
> email,
> }: {
> userId: string;
> organizationId: string;
> email?: string;
> }) {
> const res = await fetch('https://api.velt.dev/v2/auth/generate_token', {
> method: 'POST',
> headers: {
> 'Content-Type': 'application/json',
> 'x-velt-api-key': YOUR_VELT_API_KEY_HERE,
> 'x-velt-auth-token': YOUR_VELT_AUTH_TOKEN_HERE,
> },
> body: JSON.stringify({
> data: {
> userId,
> userProperties: {
> organizationId,
> ...(email ? { email } : {}),
> },
> },
> }),
> });
>
> const json = await res.json();
> return json?.result?.data?.token as string | undefined;
> }
> ```
##### **2. Use Identify with JWT Token**
* In this approach, you will call the `identify` method with the `user` object and a JWT token.
* Here you are responsible for re-generating a JWT token whenever it expires.
* This gives you more flexibility on when and where to initialize the user and generate the token.
* **Params**:
* `user`: [User](/docs/api-reference/sdk/models/data-models#user)
* `options`: [Options](/docs/api-reference/sdk/models/data-models#options-2)
* `authToken`: `string`
* `forceReset`: `boolean`: By default, once the user is authenticated, the authentication state is preserved in the browser and a new jwt token is not used until you explicitly sign them out. If you want to force re-login the user, set this to `true`.
> [tab] React / Next.js
>
> **Using Hook:**
>
> ```js theme={null}
> const user = {
> userId: uid,
> organizationId: organizationId, // this is the organization id the user belongs to. You should always use this.
> name: displayName,
> email: email,
> photoUrl: photoURL,
> color: colorCode, // Use valid Hex code value. Used in the background color of the user's avatar.
> textColor: textColor // Use valid Hex code value. Used in the text color of the user's intial when photoUrl is not present.
> };
>
> useIdentify(user, {
> authToken: authToken, // this is optional but highly recommended.
> });
> ```
>
> **Using API:**
>
> ```js theme={null}
> await client.identify(user, {
> authToken: authToken, // this is optional but highly recommended.
> });
> ```
> [tab] Other Frameworks
>
> **Using API:**
>
> ```js theme={null}
> await Velt.identify(user, {
> authToken: authToken, // this is optional but highly recommended.
> });
> ```
##### Sign in with force reset
* By default, when you identify a user, their authentication state is preserved in the browser until you explicitly sign them out.
* If you update a user's metadata or default access settings in the console and want those changes to take effect right away, you should call the `identify` method again with the `forceReset` option set to `true`.
* `Default: false`
```js theme={null}
await client.identify(user, {
forceReset: true
});
```
#### Get Current User
You can retrieve the currently authenticated user object using [`getCurrentUser()`](/docs/api-reference/sdk/api/api-methods#getcurrentuser) method or [`useCurrentUser()`](/docs/api-reference/sdk/api/react-hooks#usecurrentuser) hook.
> [tab] React / Next.js
>
> **Using Hook:**
>
> ```jsx theme={null}
> const currentUser = useCurrentUser();
> console.log('Current user:', currentUser);
> ```
>
> **Using API:**
>
> ```jsx theme={null}
> client.getCurrentUser().subscribe((user) => {
> console.log('Current user:', user);
> });
> ```
> [tab] Other Frameworks
>
> ```js theme={null}
> Velt.getCurrentUser().subscribe((user) => {
> console.log('Current user:', user);
> });
> ```
#### Sign out a User
In a given session or browser tab, if you want to switch users,
you need to first signout the current user and then sign in using `identify` method again.
This will ensure we clean up the current user session and start a new session with the new user.
```jsx theme={null}
client.signOutUser();
```
#### Contact List
### Frontend APIs
You can update the contact list dynamically in your frontend. These updates are not saved in Velt. You can also fetch contacts from your backend and show them in Velt components.
* [Add/Update Users](/docs/async-collaboration/comments/customize-behavior#updatecontactlist)
* [Search Users](/docs/async-collaboration/comments/customize-behavior#customautocompletesearch)
### Backend APIs
You can add/delete users from your backend and save the list in Velt.
* [Add Users](/docs/api-reference/rest-apis/v2/users/add-users)
* [Delete Users](/docs/api-reference/rest-apis/v2/users/delete-users)
#### User Groups:
* [Add User Groups](/docs/api-reference/rest-apis/v2/user-groups/add-groups)
* [Add Users to User Groups](/docs/api-reference/rest-apis/v2/user-groups/add-users-to-group)
* [Delete Users from User Groups](/docs/api-reference/rest-apis/v2/user-groups/delete-users-from-group)
## Access Control
### Overview
Velt's access control system is built around four main concepts:
1. [**Resources**](#1-resources) - The hierarchical structure of your app (Organizations → Folders → Documents)
2. [**Access Types**](#2-access-types) - This is applied to a resource to determine who can access it (public, organizationPrivate, or restricted)
3. [**Roles**](#3-roles) - This is applied to a user to determine what they can do on a resource (editor or viewer)
4. [**Permissions**](#4-permissions) – Define whether a user can access a resource, based on the resource's access type, the user's role, and explicit permission grants. Access can be temporary or permanent.
### Access Control Model
* **Inheritance (default)**: Similar to Google Drive, Velt Resources (Organizations, Folders, and Documents) follow a hierarchical permission model. By default, child resources inherit access control settings from their parents.
* **Overrides**: If a resource defines its own access type or user permissions, those explicit settings **override** the inherited values. This precedence applies during both permission evaluation and access enforcement.
**Example: Think of it like folders in Google Drive**
* You create a **folder** and set it to "Anyone with the link can view"
* Any **document** you add to that folder automatically inherits those same sharing settings
* If you want, you can override a specific document's sharing settings to be more restrictive or more open
**In Velt, this works the same way:**
* All **Folders** in that org automatically inherit `organizationPrivate` access
* All **Documents** in those folders also inherit `organizationPrivate` access
* If you explicitly set a specific Document to `restricted` access, that override takes precedence
### 1. Resources
Velt permissions apply to these resources and at the feature level using **Access Context**:
**Resource-Level Permissions:**
* **Organization** – top-level container that groups users, folders, and documents.
* **Folder** – groups documents under an organization.
* **Document** – individual collaborative unit (e.g., a canvas, page, or file).
> [!NOTE]
>
> Most permission changes occur at the **Folder** and **Document** level, but Organizations can set defaults that flow down hierarchically.
**Feature-Level Permissions (Access Context):**
Access Context enables granular, feature-level permissions using custom metadata. Unlike resource-level permissions that control access to entire organizations, folders, or documents, Access Context allows you to control access to specific features data (like individual comments or notifications) based on custom metadata fields you define.
**When to use Access Context:**
* **Fine-grained control**: When you need to restrict visibility of specific features data within a document rather than the entire document. For example, in a multi-tenant dashboard, users may access the same dashboard (document) but only see comments for widgets they’re authorized to view (scoped by widgetId).
* **Data-driven permissions**: When access needs to be determined by dynamic metadata such as entity IDs, project codes, section identifiers, or other custom fields specific to your application's data model.
* **Complex scenarios**: When resource-level permissions alone are too broad and you need feature-specific isolation within the same collaborative space.
### 2. Access Types
Access types define **who** can access a resource:
* **`public`** **(default)**: Any authenticated user in your app who initializes Velt can access the resource’s collaboration layer.
* **`organizationPrivate`**: Only users in the same organization as the resource can access it.
* **`restricted`**: Only explicitly permitted users can access the resource.
#### APIs (backend)
* **Folder:** Use [Update Folder Access Type](/docs/api-reference/rest-apis/v2/folders/update-folder-access).
* **Document:** Use [Update Document Access Type](/docs/api-reference/rest-apis/v2/documents/update-document-access).
* **Defaults:** Update default access across your app.
**1. Open Velt Console**
Go to the App Config in the Velt Console: [console.velt.dev](https://console.velt.dev/dashboard/config/appconfig)
**2. Choose default access type**
Select the desired default access type for new resources and save your changes.
> [!TIP]
>
> **Access Types = who can access. Roles = what they can do once they have access.** These controls are orthogonal and compose together.
### 3. Roles
Roles define **what** an allowed user can do on a resource:
* **Editor:** Read and write access to collaboration features data for the given resource. **This is the default role.**
* **Viewer:** Read-only access to collaboration features data for the given resource.
> [!NOTE]
>
> Assign or override roles per resource via your backend when granting permissions. Frontend SDK methods cannot set or change `accessRole`.
#### APIs
* [**Add users**](/docs/api-reference/rest-apis/v2/users/add-users)
* [**Remove users**](/docs/api-reference/rest-apis/v2/users/delete-users)
* [**Generate token**](/docs/api-reference/rest-apis/v2/auth/generate-token) (to be used during login)
* [**Add permissions**](/docs/api-reference/rest-apis/v2/auth/add-permissions)
* [**Remove permissions**](/docs/api-reference/rest-apis/v2/auth/remove-permissions)
### 4. Permissions
Permissions control which users can access and collaborate on specific resources in your app. They determine what actions users can perform on organizations, folders, and documents.
Permissions are determined by a combination of the resource's **access type** and the user's **role**.
There are 3 ways to configure permissions in Velt. Choose the approach that best fits your app's architecture:
a. [On-Demand Permissions](#a-on-demand-permissions): Grant or revoke permissions **at runtime** when a user logs in or navigates to a resource.
b. [Synced Permissions](#b-synced-permissions): Periodically or event‑driven sync between your app and Velt. Do an initial bulk load, then keep up with adds/removes/role changes.
c. [Real-time Permission Provider](#c-real-time-permission-provider): With this approach, Velt pings your defined endpoint to verify whether a user should be granted access to a resource (organization, folder, or document). This ensures that your backend is still the source of truth and you don't have to sync the permissions into Velt directly.
### a. On-Demand Permissions
Grant or revoke permissions **at runtime** when a user logs in or navigates to a resource.
* Best when your app has a very complex and granular permissioning system and you want to keep your system as the source of truth.
* Supports temporary (time-bound) access and permanent access, enabling ad‑hoc sharing and expiring invites.
#### Temporary vs. Permanent Access
* **Temporary access**: Grant permissions with an expiry or revoke after session/end of task (e.g., guest reviewers, contractors). Use this when access should automatically end or be short‑lived.
* **Permanent access**: Grant durable permissions for members or long‑term collaborators. Use this when roles rarely change and should persist across sessions.
#### APIs
* [**Add Permissions**](/docs/api-reference/rest-apis/v2/auth/add-permissions)
* **When user logs in**: Use an auth provider with JWT token to grant permissions to the organization present in the `User` object in the auth provider. ([Generate token](/docs/api-reference/rest-apis/v2/auth/generate-token)).
* **When user sets documents**: Call [Add Permissions API](/docs/api-reference/rest-apis/v2/auth/add-permissions) to grant or adjust access for the set of documents or folders in the `setDocuments` method.
* [**Remove Permissions**](/docs/api-reference/rest-apis/v2/auth/remove-permissions)
* Revoke access when the user signs out, loses membership, or navigates away from folder/document using [Remove Permissions API](/docs/api-reference/rest-apis/v2/auth/remove-permissions).
> [!NOTE]
>
> When you include `organizationId` in the identify/auth payload, Velt automatically creates and associates the user with that organization. This happens because the "Auto-create Organization Users" console setting is **enabled by default**. To change this default behavior, [go to Console under App Configuration -> Auto-create Organization User](https://console.velt.dev/dashboard/config/appconfig)
### b. Synced Permissions
* Periodically or event‑driven sync between your app and Velt.
* Do an initial bulk load, then keep up with adds/removes/role changes.
#### APIs
* [**Add users**](/docs/api-reference/rest-apis/v2/users/add-users)
* **Initial sync:** Bulk add existing users so they appear in mentions and can be permissioned.
* **Ongoing sync:** When a user is added or granted permissions to additional resources in your app, call this API to sync that change in Velt.
* [**Remove users**](/docs/api-reference/rest-apis/v2/users/delete-users)
* **Ongoing sync:** When a user is removed or their permissions are revoked to resources in your app, call this API to sync that change in Velt.
> [!NOTE]
>
> When you include `organizationId` in the identify/auth payload, Velt automatically creates and associates the user with that organization. The Auto-create Organization Users console setting is **enabled by default**, so you don't need to pre-create users for on-demand flows. [Go to Console under App Configuration -> Auto-create Organization User](https://console.velt.dev/dashboard/config/appconfig)
### c. Real-time Permission Provider
With this approach, Velt pings your defined endpoint to verify whether a user should be granted access to a resource (organization, folder, or document). This ensures that your backend is still the source of truth and you don't have to sync the permissions into Velt directly.
#### How it works
1. **Configure endpoint**: Set up your backend endpoint URL and optional auth token in the [Velt Console](https://console.velt.dev/dashboard/config/permission-provider).
2. **Initialize frontend**: Configure Permission Provider in your app using VeltProvider or [`setPermissionProvider()`](/docs/api-reference/sdk/api/api-methods#setpermissionprovider).
3. **Automatic validation**: When users access resources (organizations, folders, documents, or contexts), Velt automatically queries your endpoint.
4. **Backend response**: Your backend checks permissions and returns access decisions.
5. **Instant enforcement**: Velt enforces the permissions immediately based on your response.
6. **Auto-revocation** (optional): Configure automatic permission cleanup when users switch documents or log out.
#### When to use
* Your app has complex, dynamic permissions that change frequently
* You want to avoid syncing permission data to an external system
* You need real-time permission validation without backend synchronization overhead
**How to Setup:**
**Step 1: Configure Endpoint in Velt Console**
1. Enable [Permission Provider in Velt Console](https://console.velt.dev/dashboard/config/permission-provider)
2. Add your POST endpoint URL (e.g., [https://yourdomain.com/api/check-permissions](https://yourdomain.com/api/check-permissions))
3. (Optional) Add auth token for request authentication
**Step 2: Implement Your Backend Endpoint**
Your backend receives permission requests from Velt, checks your authorization system, and returns access decisions.
* **Request (Velt → your endpoint)**: [PermissionQuery](/docs/api-reference/sdk/models/data-models#permissionquery)
* **Response (your endpoint → Velt)**: [PermissionResult](/docs/api-reference/sdk/models/data-models#permissionresult)
**Folder context on document requests**
When a document belongs to a folder, its request also carries `resource.parentFolderId`, the `folderId` you set on `setDocuments()`. Use it to make folder scoped access decisions.
* Only `document` requests carry it. `organization` and `context` requests never do, and a `folder` request already has its own id in `resource.id`.
* Requests from `setDocuments`, `getNotifications`, and `setNotifications` all carry it.
* When the document has no folder, the key is omitted. Check for it with `'parentFolderId' in resource`, not `resource.parentFolderId === undefined`.
* Velt sends it as context for your endpoint. It is never an input to Velt's own access decision.
* Treat it as optional in your handler. Read `resource.source` when you need to know which call triggered the request.
**Example**
> [tab] Sample Request from Velt
>
> ```javascript expandable theme={null}
> // Velt sends a POST request to your configured endpoint
> fetch('https://yourdomain.com/api/check-permissions', {
> method: 'POST',
> headers: {
> 'Content-Type': 'application/json',
> 'Authorization': 'Bearer ${permissionProviderToken}'
> },
> body: JSON.stringify({
> data: {
> requests: [
> {
> userId: 'user123',
> resource: {
> id: 'org456',
> type: 'organization',
> source: 'identify',
> organizationId: 'org456'
> }
> },
> {
> userId: 'user123',
> resource: {
> id: 'doc789',
> type: 'document',
> source: 'setDocuments',
> organizationId: 'org456',
> parentFolderId: 'folder101'
> }
> },
> {
> userId: 'user123',
> resource: {
> id: 'folder101',
> type: 'folder',
> source: 'setDocuments',
> organizationId: 'org456'
> }
> },
> {
> userId: 'user123',
> resource: {
> id: 'doc789',
> type: 'context',
> source: 'setDocuments',
> organizationId: 'org456',
> context: {
> access: {
> entityId: 'numberOfVisitors'
> }
> }
> }
> }
> ]
> }
> })
> });
> ```
> [tab] Expected Response from Your Endpoint
>
> ```json expandable theme={null}
> {
> "data": [
> {
> "userId": "user123",
> "resourceId": "org456",
> "type": "organization",
> "organizationId": "org456",
> "hasAccess": true
> },
> {
> "userId": "user123",
> "resourceId": "doc789",
> "type": "document",
> "organizationId": "org456",
> "hasAccess": true,
> "accessRole": "editor",
> "expiresAt": 1699876543210
> },
> {
> "userId": "user123",
> "resourceId": "folder101",
> "type": "folder",
> "organizationId": "org456",
> "hasAccess": true
> },
> {
> "userId": "user123",
> "resourceId": "doc789",
> "type": "context",
> "organizationId": "org456",
> "hasAccess": true
> }
> ],
> "success": true,
> "statusCode": 200,
> "message": "Permissions validated successfully"
> }
> ```
> [tab] Your endpoint sample (Node.js / Express)
>
> ```javascript expandable theme={null}
> app.post('/api/check-permissions', async (req, res) => {
> // Receive requests from Velt
> const { requests } = req.body.data;
>
> // Check your authorization system and build permissions array
> const permissions = [];
>
> for (const request of requests) {
> let permission;
>
> // Handle context-based permission requests
> if (request.resource.type === 'context') {
> const hasAccess = await yourAuthSystem.checkContextAccess(
> request.userId,
> request.resource.id,
> request.resource.context.access
> );
>
> permission = {
> userId: request.userId,
> resourceId: request.resource.id,
> type: 'context',
> organizationId: request.resource.organizationId,
> hasAccess: hasAccess,
> };
> }
> // Handle standard resource permission requests
> else {
> const hasAccess = await yourAuthSystem.checkUserAccess(
> request.userId,
> request.resource.id,
> request.resource.type
> );
>
> permission = {
> userId: request.userId,
> resourceId: request.resource.id,
> type: request.resource.type,
> organizationId: request.resource.organizationId,
> hasAccess: hasAccess,
> };
>
> // For documents, add access role
> if (request.resource.type === 'document' && hasAccess) {
> permission.accessRole = await yourAuthSystem.getUserRole(
> request.userId,
> request.resource.id
> ); // 'viewer' or 'editor'
> permission.expiresAt = Date.now() + 10 * 60 * 1000; // Optional: 10 min expiry
> }
> }
>
> permissions.push(permission);
> }
>
> // Return response in expected format
> res.json({
> data: permissions,
> success: true,
> statusCode: 200,
> message: 'Permissions validated successfully'
> });
> });
> ```
> [tab] Your endpoint sample (Python / Flask)
>
> ```python expandable theme={null}
> @app.route('/api/check-permissions', methods=['POST'])
> def check_permissions():
> # Receive requests from Velt
> request_data = request.json
> requests_list = request_data.get('data', {}).get('requests', [])
>
> # Check your authorization system and build permissions array
> permissions = []
>
> for req in requests_list:
> # Handle context-based permission requests
> if req['resource']['type'] == 'context':
> has_access = your_auth_system.check_context_access(
> req['userId'],
> req['resource']['id'],
> req['resource']['context']['access']
> )
>
> permission = {
> 'userId': req['userId'],
> 'resourceId': req['resource']['id'],
> 'type': 'context',
> 'organizationId': req['resource']['organizationId'],
> 'hasAccess': has_access
> }
> # Handle standard resource permission requests
> else:
> has_access = your_auth_system.check_user_access(
> req['userId'],
> req['resource']['id'],
> req['resource']['type']
> )
>
> permission = {
> 'userId': req['userId'],
> 'resourceId': req['resource']['id'],
> 'type': req['resource']['type'],
> 'organizationId': req['resource']['organizationId'],
> 'hasAccess': has_access
> }
>
> # For documents, add access role
> if req['resource']['type'] == 'document' and has_access:
> permission['accessRole'] = your_auth_system.get_user_role(
> req['userId'],
> req['resource']['id']
> ) # 'viewer' or 'editor'
> permission['expiresAt'] = int(time.time() * 1000) + 10 * 60 * 1000 # Optional: 10 min expiry
>
> permissions.append(permission)
>
> # Return response in expected format
> return jsonify({
> 'data': permissions,
> 'success': True,
> 'statusCode': 200,
> 'message': 'Permissions validated successfully'
> })
> ```
**Step 3: Configure Permission Provider Behavior in your Frontend**
Configure Permission Provider behavior in your frontend using [`setPermissionProvider()`](/docs/api-reference/sdk/api/api-methods#setpermissionprovider).
**Configuration Options:**
View the complete [`VeltPermissionProvider` schema](/docs/api-reference/sdk/models/data-models#veltpermissionprovider) for all available options.
* `isContextEnabled`: Enable context-based permission requests for granular access control per context value. Default: `false`
* `retryConfig`: Configure retry attempts and delays for failed permission requests. Default: 3 retries with 2000ms delay. See [`AuthRetryConfig`](/docs/api-reference/sdk/models/data-models#authretryconfig)
* `forceRefresh`: Force re-validation on each access check when permissions change frequently. Default: `false`
* `revokeAccessOn`: Configure automatic access revocation on specific events (e.g., document unset, user logout).
* `dev`: Opt-in to resolving permissions in the browser for local development and testing. Honored only for dev/test API keys; production keys always use the server-side Permission Provider. Default: `false`. See [Local Development](#local-development-testing-the-permission-provider-locally).
* `endpointConfig`: URL resolver for the dev resolver. The SDK POSTs `{ data: { requests: PermissionQuery[] } }` to the URL. Takes precedence over `resolvePermissions`. See [`ResolverEndpointConfig`](/docs/api-reference/sdk/models/data-models#resolverendpointconfig)
* `resolvePermissions`: In-browser callback resolver, invoked with the same request envelope as the server-side Permission Provider. See [`PermissionResolverRequest`](/docs/api-reference/sdk/models/data-models#permissionresolverrequest)
* `resolveTimeout`: Per-call deadline in milliseconds for the dev resolver. Default: `60000`
> [tab] React / Next.js
>
> You can configure the Permission Provider in two ways:
>
> Option 1: In VeltProvider (Recommended)
>
> ```jsx expandable theme={null}
> apiKey="YOUR_API_KEY"
> permissionProvider={{
> isContextEnabled: true,
> retryConfig: { retryCount: 3, retryDelay: 2000 },
> forceRefresh: false,
> }}
> >
> {/* Your app */}
>
> ```
>
> Option 2: Using setPermissionProvider()
>
> ```jsx expandable theme={null}
> const { client } = useVeltClient();
> client.setPermissionProvider({
> isContextEnabled: true,
> retryConfig: { retryCount: 3, retryDelay: 2000 },
> forceRefresh: false,
> });
> ```
>
> > [!NOTE]
> >
> > When using `setPermissionProvider()` method, call it before `identify()`, `setAuthProvider()`, and `setDocument()` methods to ensure proper initialization.
> [tab] Other Frameworks
>
> > [!NOTE]
> >
> > When using `setPermissionProvider()` method, call it before `identify()`, `setAuthProvider()`, and `setDocument()` methods to ensure proper initialization.
>
> ```javascript theme={null}
> Velt.setPermissionProvider({
> isContextEnabled: true,
> retryConfig: { retryCount: 3, retryDelay: 2000 },
> forceRefresh: false,
> });
> ```
#### Local Development (Testing the Permission Provider locally)
The Real-time Permission Provider is server-to-server: Velt's backend POSTs to the endpoint registered in the Console, which it cannot reach when that endpoint is `localhost`. Previously, testing locally required exposing your endpoint through a tunnel such as ngrok or Cloudflare Tunnel. With `dev: true`, the browser resolves permissions instead and relays the results to Velt's backend. Your localhost endpoint is always reachable from the browser, so no tunnel is needed.
You can resolve permissions in two ways:
* **URL resolver** (`endpointConfig`): the SDK POSTs the permission requests to your URL. The request envelope is identical to the server-side Permission Provider contract, so an existing `/api/check-permissions` handler works unchanged.
* **Callback resolver** (`resolvePermissions`): resolve the requests inline in the browser. Receives a [`PermissionResolverRequest`](/docs/api-reference/sdk/models/data-models#permissionresolverrequest) and returns [`PermissionResult[]`](/docs/api-reference/sdk/models/data-models#permissionresult) or a [`ResolverResponse`](/docs/api-reference/sdk/models/data-models#resolverresponse)``.
> [tab] React / Next.js
>
> ```jsx expandable theme={null}
> const { client } = useVeltClient();
>
> // URL resolver — browser POSTs to a localhost endpoint, no tunnel required
> client.setPermissionProvider({
> dev: true,
> endpointConfig: {
> url: 'http://localhost:3000/api/check-permissions',
> },
> resolveTimeout: 60000,
> retryConfig: { retryCount: 3, retryDelay: 1000 },
> });
>
> // Callback resolver — resolve inline in the browser
> client.setPermissionProvider({
> dev: true,
> resolvePermissions: async ({ data: { requests } }) => {
> // return PermissionResult[] or ResolverResponse
> // PermissionResult is flat — lift id/type/organizationId out of `resource`
> return requests.map(q => ({
> userId: q.userId,
> resourceId: q.resource.id,
> organizationId: q.resource.organizationId,
> type: q.resource.type,
> hasAccess: true,
> }));
> },
> });
> ```
> [tab] Other Frameworks
>
> ```javascript expandable theme={null}
> // URL resolver — browser POSTs to a localhost endpoint, no tunnel required
> Velt.setPermissionProvider({
> dev: true,
> endpointConfig: {
> url: 'http://localhost:3000/api/check-permissions',
> },
> resolveTimeout: 60000,
> retryConfig: { retryCount: 3, retryDelay: 1000 },
> });
>
> // Callback resolver — resolve inline in the browser
> Velt.setPermissionProvider({
> dev: true,
> resolvePermissions: async ({ data: { requests } }) => {
> // return PermissionResult[] or ResolverResponse
> // PermissionResult is flat — lift id/type/organizationId out of `resource`
> return requests.map(q => ({
> userId: q.userId,
> resourceId: q.resource.id,
> organizationId: q.resource.organizationId,
> type: q.resource.type,
> hasAccess: true,
> }));
> },
> });
> ```
> [!WARNING]
>
> The `dev` flag is an ergonomic switch, not a security control. Client-resolved results are honored only for dev/test API keys. Production keys always use the server-side Permission Provider regardless of the `dev` flag.
> [!NOTE]
>
> * The dev resolver fails closed: resolver errors, timeouts, exhausted retries, and malformed payloads all deny access.
> * `endpointConfig.url` takes precedence over `resolvePermissions` when both are set.
> * A one-shot `console.warn` fires while the dev resolver is active, and when `dev: true` is set without a usable resolver configured.
**Step 4: Configure Auto Revoke Access (optional)**
* Automatically revoke permissions when specific events occur, providing better control over user access and security.
* Access is automatically revoked from both cache and backend when triggered. This ensures immediate permission removal without requiring manual cleanup.
* Context access is only revoked when the user logs out and not at document unset.
**Configuration Options:**
* `type`: [`RevokeAccessOnType`](/docs/api-reference/sdk/models/data-models#revokeaccessontype)
* `document_unset`: Revokes access when user unsets or leaves a document
* `user_logout`: Revokes access when user logs out
* `revokeOrganizationAccess`: Set to `true` to also revoke organization-level permissions (default: `false`)
> [tab] React / Next.js
>
> **Option 1: In VeltProvider (Recommended)**
>
> ```jsx expandable theme={null}
> apiKey="YOUR_API_KEY"
> permissionProvider={{
> isContextEnabled: true,
> revokeAccessOn: {
> type: 'document_unset', // Revoke access when user leaves document
> revokeOrganizationAccess: false // Keep organization access
> }
> }}
> >
> {/* Your app */}
>
> ```
>
> **Option 2: Using setPermissionProvider()**
>
> ```jsx expandable theme={null}
> const { client } = useVeltClient();
>
> // Example 1: Revoke access on document unset only
> client.setPermissionProvider({
> revokeAccessOn: {
> type: 'document_unset',
> revokeOrganizationAccess: false
> }
> });
>
> // Example 2: Revoke all access including organization on user logout
> client.setPermissionProvider({
> revokeAccessOn: {
> type: 'user_logout',
> revokeOrganizationAccess: true // Also revoke organization permissions
> }
> });
> ```
>
> > [!NOTE]
> >
> > Context-level access is only revoked on user logout, not on document unset.
> [tab] Other Frameworks
>
> ```javascript expandable theme={null}
> // Example 1: Revoke access on document unset only
> Velt.setPermissionProvider({
> revokeAccessOn: {
> type: 'document_unset',
> revokeOrganizationAccess: false
> }
> });
>
> // Example 2: Revoke all access including organization on user logout
> Velt.setPermissionProvider({
> revokeAccessOn: {
> type: 'user_logout',
> revokeOrganizationAccess: true // Also revoke organization permissions
> }
> });
> ```
**Permission Provider Events**
[**On()**](/docs/api-reference/sdk/api/api-methods#on-5)
Monitor permission checks by subscribing to Permission Provider events. These are the sub-event types you can receive:
| Sub-Event Type | Description | Event Object |
| - | - | - |
| `resourceAccessRequestFormed` | Triggered when a permission request is formed internally before being sent | [PermissionProviderEvent](/docs/api-reference/sdk/models/data-models#permissionproviderevent) |
| `resourceAccessRequestTriggered` | Triggered when a permission request is actually triggered and sent | [PermissionProviderEvent](/docs/api-reference/sdk/models/data-models#permissionproviderevent) |
| `resourceAccessResult` | Triggered when a permission check result is received from your server | [PermissionProviderEvent](/docs/api-reference/sdk/models/data-models#permissionproviderevent) |
| `resourceAccessError` | Triggered when an error occurs during permission checking | [PermissionProviderEvent](/docs/api-reference/sdk/models/data-models#permissionproviderevent) |
| `resourceAccessResultFromCache` | Triggered when a permission result is retrieved from cache instead of making a new request | [PermissionProviderEvent](/docs/api-reference/sdk/models/data-models#permissionproviderevent) |
| `revokeAccessOnDocumentUnsetTriggered` | Triggered when permissions are automatically revoked due to document unset trigger | [RevokeAccessEvent](/docs/api-reference/sdk/models/data-models#revokeaccessevent) |
| `revokeAccessOnUserLogoutTriggered` | Triggered when permissions are automatically revoked due to user logout trigger | [RevokeAccessEvent](/docs/api-reference/sdk/models/data-models#revokeaccessevent) |
> [tab] React / Next.js
>
> **Using React Hook**
>
> ```jsx expandable theme={null}
> import { useVeltEventCallback } from '@veltdev/react';
>
> function PermissionMonitor() {
> // Subscribe to all permission provider events
> useVeltEventCallback('permissionProvider', (event) => {
> console.log('Permission provider event:', event);
> });
> // Event payload example for resourceAccessRequestTriggered:
> // {
> // "event": "resourceAccessRequestTriggered",
> // "timestamp": 1761580810137,
> // "methodName": "onResourceAccessRequired",
> // "source": "internal",
> // "payload": {
> // "requests": [
> // {
> // "userId": "1.1",
> // "resource": {
> // "id": "org1",
> // "type": "organization",
> // "source": "identify"
> // }
> // }
> // ],
> // "fromCache": false
> // }
> // }
>
> // Event payload example for resourceAccessResult:
> // {
> // "event": "resourceAccessResult",
> // "timestamp": 1761580811228,
> // "methodName": "onResourceAccessRequired",
> // "source": "internal",
> // "payload": {
> // "result": {
> // "data": [
> // {
> // "userId": "1.1",
> // "resourceId": "org1",
> // "type": "organization",
> // "hasAccess": true
> // }
> // ],
> // "success": true,
> // "statusCode": 200,
> // "signature": "811824052c1ea76f22fc67b36ca5dd867b89d4efeb85cf648bbbc0d2c0675545"
> // }
> // }
> // }
>
> // Event payload example for revokeAccessOnDocumentUnsetTriggered:
> // {
> // "event": "revokeAccessOnDocumentUnsetTriggered",
> // "timestamp": 1761580810137,
> // "payload": {
> // "userId": "user_123",
> // "documentId": "doc_456",
> // "organizationId": "org_789",
> // "revokeOrganizationAccess": false
> // }
> // }
>
> // Event payload example for revokeAccessOnUserLogoutTriggered:
> // {
> // "event": "revokeAccessOnUserLogoutTriggered",
> // "timestamp": 1761580810137,
> // "payload": {
> // "userId": "user_123",
> // "organizationId": "org_789",
> // "revokeOrganizationAccess": true
> // }
> // }
> return Monitoring permission events...
;
> }
> ```
>
> **Using Client Method**
>
> ```jsx expandable theme={null}
> const { client } = useVeltClient();
>
> // Subscribe to all permission provider events
> client.on('permissionProvider').subscribe(event => console.log(event));
>
> // Event payload example for resourceAccessRequestFormed:
> // {
> // "event": "resourceAccessRequestFormed",
> // "methodName": "identify",
> // "timestamp": 1761580810137,
> // "source": "internal",
> // "payload": {
> // "requests": [
> // {
> // "userId": "1.1",
> // "resource": {
> // "id": "org1",
> // "type": "organization",
> // "source": "identify"
> // }
> // }
> // ]
> // }
> // }
>
> // Event payload example for resourceAccessRequestTriggered:
> // {
> // "event": "resourceAccessRequestTriggered",
> // "timestamp": 1761580810137,
> // "methodName": "onResourceAccessRequired",
> // "source": "internal",
> // "payload": {
> // "requests": [
> // {
> // "userId": "1.1",
> // "resource": {
> // "id": "org1",
> // "type": "organization",
> // "source": "identify"
> // }
> // }
> // ],
> // "fromCache": false
> // }
> // }
>
> // Event payload example for resourceAccessResult:
> // {
> // "event": "resourceAccessResult",
> // "timestamp": 1761580811228,
> // "methodName": "onResourceAccessRequired",
> // "source": "internal",
> // "payload": {
> // "result": {
> // "data": [
> // {
> // "userId": "1.1",
> // "resourceId": "org1",
> // "type": "organization",
> // "hasAccess": true
> // }
> // ],
> // "success": true,
> // "statusCode": 200,
> // "signature": "811824052c1ea76f22fc67b36ca5dd867b89d4efeb85cf648bbbc0d2c0675545"
> // }
> // }
> // }
>
> // Event payload example for revokeAccessOnDocumentUnsetTriggered:
> // {
> // "event": "revokeAccessOnDocumentUnsetTriggered",
> // "timestamp": 1761580810137,
> // "payload": {
> // "userId": "user_123",
> // "documentId": "doc_456",
> // "organizationId": "org_789",
> // "revokeOrganizationAccess": false
> // }
> // }
>
>
> // Event payload example for revokeAccessOnUserLogoutTriggered:
> // {
> // "event": "revokeAccessOnUserLogoutTriggered",
> // "timestamp": 1761580810137,
> // "payload": {
> // "userId": "user_123",
> // "organizationId": "org_789",
> // "revokeOrganizationAccess": true
> // }
> // }
>
> ```
> [tab] Other Frameworks
>
> ```javascript theme={null}
> // Subscribe to all permission provider events
> Velt.on('permissionProvider').subscribe(event => console.log(event));
>
> // Event payload example for resourceAccessRequestFormed:
> // {
> // "event": "resourceAccessRequestFormed",
> // "methodName": "identify",
> // "timestamp": 1761580810137,
> // "source": "internal",
> // "payload": {
> // "requests": [
> // {
> // "userId": "1.1",
> // "resource": {
> // "id": "org1",
> // "type": "organization",
> // "source": "identify"
> // }
> // }
> // ]
> // }
> // }
>
> // Event payload example for resourceAccessRequestTriggered:
> // {
> // "event": "resourceAccessRequestTriggered",
> // "timestamp": 1761580810137,
> // "methodName": "onResourceAccessRequired",
> // "source": "internal",
> // "payload": {
> // "requests": [
> // {
> // "userId": "1.1",
> // "resource": {
> // "id": "org1",
> // "type": "organization",
> // "source": "identify"
> // }
> // }
> // ],
> // "fromCache": false
> // }
> // }
>
>
> // Event payload example for resourceAccessResult:
> // {
> // "event": "resourceAccessResult",
> // "timestamp": 1761580811228,
> // "methodName": "onResourceAccessRequired",
> // "source": "internal",
> // "payload": {
> // "result": {
> // "data": [
> // {
> // "userId": "1.1",
> // "resourceId": "org1",
> // "type": "organization",
> // "hasAccess": true
> // }
> // ],
> // "success": true,
> // "statusCode": 200,
> // "signature": "811824052c1ea76f22fc67b36ca5dd867b89d4efeb85cf648bbbc0d2c0675545"
> // }
> // }
> // }
>
> // Event payload example for revokeAccessOnDocumentUnsetTriggered:
> // {
> // "event": "revokeAccessOnDocumentUnsetTriggered",
> // "timestamp": 1761580810137,
> // "payload": {
> // "userId": "user_123",
> // "documentId": "doc_456",
> // "organizationId": "org_789",
> // "revokeOrganizationAccess": false
> // }
> // }
>
> // Event payload example for revokeAccessOnUserLogoutTriggered:
> // {
> // "event": "revokeAccessOnUserLogoutTriggered",
> // "timestamp": 1761580810137,
> // "payload": {
> // "userId": "user_123",
> // "organizationId": "org_789",
> // "revokeOrganizationAccess": true
> // }
> // }
> ```
### d. Set Feature Level Permissions using Access Context
Access Context allows you to set granular, feature-level permissions using custom metadata. When configured, new feature data is added and existing feature data is fetched only for the access context values the current user has access to.
#### How it works
Access Context enables you to control access to specific features (like comments, notifications) based on custom metadata fields. For example, you could restrict comment visibility based on `widgetId`, `dashboardId`, or any custom field relevant to your application.
**Matching Logic:**
* When multiple fields are present in the context, Velt checks access for each field combination
* When multiple array values exist in each field, each value creates a separate permission request
* A user must have access to **all** fields in a context to view the associated feature data
* The access context supports up to **200 items** total
#### Configuration Steps
**Step 1: Add Access Context to Features**
You need to add access context metadata to your features on both frontend and backend.
**Frontend:**
> [!NOTE]
>
> If you add access context to comments, other features associated with it (like notifications) will automatically inherit the same access context.
>
> Comment notifications are also filtered by the comment's visibility. A notification must pass both checks, the Access Context check and the visibility check, before a user receives it.
When a comment annotation is added, attach the access context using the `addContext()` method. Pass a **string or number** for each context field:
> [tab] React / Next.js
>
> ```jsx theme={null}
> const commentElement = client.getCommentElement();
>
> commentElement.on('addCommentAnnotation').subscribe((event) => {
> event.addContext({
> access: {
> widgetId: 2 // Pass string or number, not array
> }
> });
> });
> ```
> [tab] Other Frameworks
>
> ```js theme={null}
> const commentElement = Velt.getCommentElement();
>
> commentElement.on('addCommentAnnotation').subscribe((event) => {
> event.addContext({
> access: {
> widgetId: 2 // Pass string or number, not array
> }
> });
> });
> ```
> [!WARNING]
>
> **Reserved names.** Velt reserves the prefixes `organizationPrivate:` and `__velt_private_self:` for comment visibility. Do not use them in your Access Context field names. Velt reads a field named `organizationPrivate` as a visibility setting, not as your metadata. The comment then loads for the wrong users. Velt does not block this at runtime, so the check is yours.
**Backend:**
If you are adding comments or notifications using REST APIs, you can use the following:
> [tab] Comments
>
> Use the REST API to add access context when creating comments programmatically:
>
> ```json theme={null}
> POST /v2/comments
> {
> "data": {
> "organizationId": "org1",
> "documentId": "document1",
> "commentText": "This is a comment",
> "context": {
> "access": {
> "widgetId": 2
> }
> }
> }
> }
> ```
> [tab] Notifications
>
> Use the REST API to add access context when creating notifications:
>
> ```json theme={null}
> POST /v2/notifications
> {
> "data": {
> "organizationId": "org1",
> "documentId": "document1",
> "notificationText": "New update available",
> "context": {
> "access": {
> "dashboardId": "dashboard1"
> }
> }
> }
> }
> ```
**Step 2: Enable Context-Based Permissions**
Enable access context permission validation by setting `isContextEnabled: true` in your Permission Provider configuration. When enabled, the Permission Provider will receive individual requests for each context value, allowing you to control access at a granular level for features like comments and notifications.
> [tab] React / Next.js
>
> Option 1: In VeltProvider (Recommended)
>
> ```jsx expandable theme={null}
> apiKey="YOUR_API_KEY"
> permissionProvider={{
> isContextEnabled: true, // Enable context-based permissions for notifications
> retryConfig: {
> retryCount: 3,
> retryDelay: 2000
> },
> forceRefresh: false,
> revokeAccessOn: [
> {
> type: "document_unset",
> revokeOrganizationAccess: false
> },
> {
> type: "user_logout",
> revokeOrganizationAccess: true
> }
> ]
> }}
> >
> {/* Your app */}
>
> ```
>
> Option 2: Using setPermissionProvider()
>
> ```jsx expandable theme={null}
> const { client } = useVeltClient();
>
> client.setPermissionProvider({
> isContextEnabled: true, // Enable context-based permissions for notifications
> retryConfig: {
> retryCount: 3,
> retryDelay: 2000
> },
> forceRefresh: false,
> revokeAccessOn: [
> {
> type: "document_unset",
> revokeOrganizationAccess: false
> },
> {
> type: "user_logout",
> revokeOrganizationAccess: true
> }
> ]
> });
> ```
> [tab] Other Frameworks
>
> ```js expandable theme={null}
> Velt.setPermissionProvider({
> isContextEnabled: true, // Enable context-based permissions for notifications
> retryConfig: {
> retryCount: 3,
> retryDelay: 2000
> },
> forceRefresh: false,
> revokeAccessOn: [
> {
> type: "document_unset",
> revokeOrganizationAccess: false
> },
> {
> type: "user_logout",
> revokeOrganizationAccess: true
> }
> ]
> });
> ```
**Step 3: Subscribe to documents with specific Access Context**
Add access context when subscribing to documents. Pass the access context values as arrays in `setDocuments()`. Each value will generate a separate permission request:
> [!NOTE]
>
> **Context to Permission Conversion:** When you pass arrays of context values in `setDocuments()`, Velt automatically converts them to individual permission requests. For example, `entityId: ['value1', 'value2']` becomes two separate requests with `entityId: 'value1'` and `entityId: 'value2'`.
> [tab] React / Next.js
>
> ```jsx expandable theme={null}
> const { client } = useVeltClient();
>
> client.setDocuments(documents, {
> context: {
> access: {
> widgetId: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] // Up to 200 items total
> }
> }
> });
> ```
> [tab] Other Frameworks
>
> ```js expandable theme={null}
> Velt.setDocuments(documents, {
> context: {
> access: {
> widgetId: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] // Up to 200 items total
> }
> }
> });
> ```
> [tab] Request Example
>
> **Example Request to Your Permission Provider Endpoint:**
>
> ```json expandable theme={null}
> {
> "data": {
> "requests": [
> {
> "userId": "1.1",
> "resource": {
> "id": "document1",
> "type": "document",
> "source": "setDocuments",
> "organizationId": "org1"
> }
> },
> {
> "userId": "1.1",
> "resource": {
> "id": "{\"widgetId\":1}",
> "type": "context",
> "source": "setDocuments",
> "organizationId": "org1",
> "context": {
> "access": { "widgetId": 1 }
> }
> }
> },
> {
> "userId": "1.1",
> "resource": {
> "id": "{\"widgetId\":2}",
> "type": "context",
> "source": "setDocuments",
> "organizationId": "org1",
> "context": {
> "access": { "widgetId": 2 }
> }
> }
> }
> // ... more context items
> ]
> }
> }
> ```
> [tab] Response Example
>
> **Example Response from Your Endpoint:**
>
> ```json expandable theme={null}
> {
> "data": [
> {
> "userId": "1.1",
> "resourceId": "document1",
> "type": "document",
> "hasAccess": true,
> "organizationId": "org1"
> },
> {
> "userId": "1.1",
> "resourceId": "{\"widgetId\":1}",
> "type": "context",
> "hasAccess": true,
> "organizationId": "org1"
> },
> {
> "userId": "1.1",
> "resourceId": "{\"widgetId\":2}",
> "type": "context",
> "hasAccess": false,
> "organizationId": "org1"
> }
> // ... more context results
> ],
> "success": true,
> "statusCode": 200
> }
> ```
#### Access Context and Private Comments
Access Context and [Private Comments](/docs/async-collaboration/comments/customize-behavior#private-comments-beta) are independent systems. A comment can use both at the same time.
* Access Context decides which context a comment belongs to.
* Visibility decides who can read the comment.
How they compose:
* Making a comment private keeps its Access Context.
* Updating a comment's Access Context keeps its visibility.
* A private comment with an Access Context shows only under that context, for everyone including the author.
Access Context is a data partition, not a permission. To limit who can read a comment, set its visibility. No integration change required.
### Query Permissions
The following APIs can be used to query user permissions regardless of which permission approach you're using (On-Demand, Synced, or Real-time Permission Provider).
#### Backend API
[**Get Permissions**](/docs/api-reference/rest-apis/v2/auth/get-permissions): Query a user's effective permissions/roles for the given resources. This returns what permissions your user has according to Velt.
#### Frontend APIs
##### getUserPermissions()
One-time fetch that returns a promise with the current user's permissions.
* **Params:** `request?`: [GetUserPermissionsRequest](/docs/api-reference/sdk/models/data-models#getuserpermissionsrequest)
* **Returns:** `Promise<`[GetUserPermissionsResponse](/docs/api-reference/sdk/models/data-models#getuserpermissionsresponse)`>`
> [tab] React / Next.js
>
> ```ts theme={null}
> const request = {
> organizationId: 'org_123',
> folderIds: ['folder_1', 'folder_2'],
> documentIds: ['doc_1', 'doc_2']
> };
>
> const permissions = await client.getUserPermissions(request);
> ```
> [tab] Other Frameworks
>
> ```js theme={null}
> const request = {
> organizationId: 'org_123',
> folderIds: ['folder_1', 'folder_2'],
> documentIds: ['doc_1', 'doc_2']
> };
>
> const permissions = await Velt.getUserPermissions(request);
> ```
##### getCurrentUserPermissions()
Subscribe to real-time permission updates for the current authenticated user. Returns an observable that emits whenever permissions change.
* **Params:** None
* **Returns:** `Observable<`[GetUserPermissionsResponse](/docs/api-reference/sdk/models/data-models#getuserpermissionsresponse)`>`
> [tab] React / Next.js
>
> ```ts theme={null}
> const subscription = client.getCurrentUserPermissions().subscribe((permissions) => {
> console.log('Current user permissions:', permissions);
> });
>
> // Cleanup when done
> subscription.unsubscribe();
> ```
> [tab] Other Frameworks
>
> ```js theme={null}
> const subscription = Velt.getCurrentUserPermissions().subscribe((permissions) => {
> console.log('Current user permissions:', permissions);
> });
>
> // Cleanup when done
> subscription.unsubscribe();
> ```
**Response Structure:**
Both APIs return the same response format:
```json theme={null}
{
"result": {
"status": "success",
"message": "User permissions retrieved successfully.",
"data": {
"user_123": {
"folders": {
"folder1": {
"accessRole": "editor",
"accessType": "restricted"
}
},
"documents": {
"document1": {
"accessRole": "editor",
"accessType": "restricted"
}
},
"organization": {
"org1": {
"accessRole": "editor"
}
},
"context": {
"accessFields": ["widgetId:1", "widgetId:2", "widgetId:3"]
}
}
}
}
}
```
> [!NOTE]
>
> See the [API Reference](/docs/api-reference/sdk/api/api-methods#getcurrentuserpermissions) for detailed method documentation.
# Customize Behavior
Source: https://velt.dev/docs/live-co-editing/customize-behavior
# Customize UI
Source: https://velt.dev/docs/live-co-editing/customize-ui
# Overview
Source: https://velt.dev/docs/live-co-editing/overview
> [!WARNING]
>
> Live Co-Editing is still in beta. If you would like to test it out please email [support@velt.dev](mailto:support@velt.dev) to get setup.
## Live Co-Editing
`Live Co-editing` enables Enable seamless co-editing experience in your app. We sync & merge your app state across all clients.
# Setup
Source: https://velt.dev/docs/live-co-editing/setup
# REST APIs MCP Server (Beta)
Source: https://velt.dev/docs/mcp/mcp
Interact with your Velt data from Cursor, Windsurf, Claude Desktop, and other MCP-compatible clients via the REST APIs MCP server.
Interact with your Velt data directly from MCP-compatible clients such as Cursor, Windsurf, and Claude Desktop. This server exposes Velt REST APIs as tools.
> [!NOTE]
>
> Looking for documentation search in your editor? See [Velt Docs MCP](/docs/get-started/docs-mcp). For guided SDK install, see [Velt Installation MCP](/docs/get-started/mcp-installer).
## Supported MCP Clients
The MCP server is compatible with any client that supports MCP. Here are few examples:
* [Cursor](https://www.cursor.com/)
* [Windsurf](https://windsurf.dev/)
* [Claude Desktop](https://www.anthropic.com/products/claude-desktop)
## Tools
The MCP server exposes **all** the [Velt REST APIs](/docs/api-reference/rest-apis/v2/workspace/create) as tools.
Below you will find links to different collections of APIs:
* [Organizations](/docs/api-reference/rest-apis/v2/organizations/add-organizations)
* [Folders](/docs/api-reference/rest-apis/v2/folders/add-folder)
* [Documents](/docs/api-reference/rest-apis/v2/documents/get-documents-v2)
* [Users](/docs/api-reference/rest-apis/v2/users/get-users-v2)
* [User Groups](/docs/api-reference/rest-apis/v2/user-groups/add-groups)
* [Comments](/docs/api-reference/rest-apis/v2/comments-feature/comments/get-comments)
* [Notifications](/docs/api-reference/rest-apis/v2/notifications/get-notifications-v2)
* [Live State](/docs/api-reference/rest-apis/v2/livestate/broadcast-event)
* [Workspace](/docs/api-reference/rest-apis/v2/workspace/add-domain)
## Setup
You can set up the REST API MCP Server using any of the following methods. Note you will be required to provide your Velt API key and Velt Auth token to the MCP server.
### Using Smithery CLI
The easiest way to get started is by using the `@smithery/cli` package installer. This will automatically download and configure the MCP server for your chosen client.
You can visit: [https://smithery.ai/server/@velt-js/velt-api-mcp](https://smithery.ai/server/@velt-js/velt-api-mcp) to see the list of clients supported by the MCP server and steps to install it. Here are some examples:
> [tab] Claude Desktop
>
> ```bash theme={null}
> npx -y @smithery/cli install @velt-js/velt-api-mcp --client claude
> ```
> [tab] Cursor
>
> ```bash theme={null}
> npx -y @smithery/cli install @velt-js/velt-api-mcp --client cursor
> ```
> [tab] Windsurf
>
> ```bash theme={null}
> npx -y @smithery/cli install @velt-js/velt-api-mcp --client windsurf
> ```
> [tab] Cline
>
> ```bash theme={null}
> npx -y @smithery/cli install @velt-js/velt-api-mcp --client cline
> ```
> [tab] VSCode
>
> ```bash theme={null}
> npx -y @smithery/cli install @velt-js/velt-api-mcp --client vscode
> ```
### Manual Configuration
If you prefer to configure the server manually, follow these steps.
1. **Install the Server Package:**
```bash theme={null}
npm i @veltdev/api-mcp
```
2. **Configure your client:**
Here are some examples:
> [tab] Claude Desktop
>
> 1. Open Claude Desktop.
>
> 2. Go to **Settings > Developer > Edit Config**.
>
> 3. Add the following configuration to the `mcpServers` section in your config file. Make sure to replace the placeholder values.
>
> ```json theme={null}
> {
> "mcpServers": {
> "velt-api-mcp": {
> "command": "node",
> "args": ["/dist/index.js"],
> "env": {
> "VELT_API_KEY": "",
> "VELT_AUTH_TOKEN": ""
> }
> }
> }
> }
> ```
>
> 4. Save the configuration file.
>
> 5. Restart Claude Desktop. The `velt-api-mcp` server will now be available in the tools menu.
> [tab] Cursor
>
> 1. Open Cursor.
> 2. Go to **Cursor Settings → Tools & Integrations → New MCP Server**.
> 3. Add the following configuration, replacing the placeholders with the full path to the server and your Velt secrets.
> ```json theme={null}
> {
> "mcpServers": {
> "velt-api-mcp": {
> "command": "node",
> "args": ["/dist/index.js"],
> "env": {
> "VELT_API_KEY": "",
> "VELT_AUTH_TOKEN": ""
> }
> }
> }
> }
> ```
> 4. Ensure the server is enabled in the MCP List.
> [tab] Windsurf
>
> 1. Open Windsurf.
> 2. Go to **Windsurf Settings → Manage Plugins → View Raw Config**.
> 3. Add the following configuration, replacing the placeholders with the full path to the server and your Velt secrets.
> ```json theme={null}
> {
> "mcpServers": {
> "velt-api-mcp": {
> "command": "node",
> "args": ["/dist/index.js"],
> "env": {
> "VELT_API_KEY": "",
> "VELT_AUTH_TOKEN": ""
> }
> }
> }
> }
> ```
> 4. Ensure the server is enabled in the MCP List.
## Use cases
Once configured, you can interact with the Velt API through your MCP client. Here are some examples:
1. **Querying Velt Data:**
* How many comments are there in this organization: ORGANIZATION_ID?
* Provide a list of users in the this organization: ORGANIZATION_ID.
* Give me a list of all open comments in this organization: ORGANIZATION_ID.
* Get all notifications for this user: USER_ID.
* and more...
2. **Adding or updating sample data:**
* Add, update or delete comments in a given document.
* Add notification for a given user.
* and more...
3. **Analysis:**
If you are using an agentic client like Cursor, you can also ask questions like:
* What are users discussing in comments in this organization: ORGANIZATION_ID?
* Categorize the comments as bugs, feature requests, questions, etc in this organization: ORGANIZATION_ID.
* and more...
4. **Debugging:**
* Add a comment using SDK and ask the MCP to fetch the comment.
* Tag a user in a comment using SDK and ask the MCP to fetch the notification for the user.
* and more...
5. **Use it as a tool for your AI Agent:**
* You could review a document (eg: essay, report, etc) and ask the Velt MCP to add comments providing contextual feedback on the document.
* Here is a sample code of using MCP tool in AI agent with Google AI SDK:
```python theme={null}
TARGET_FOLDER_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), "")
root_agent = Agent(
name="AI Comment Agent",
model="gemini-2.5-flash",
description="Agent that adds comments for the product",
instruction="""
You are a reviewer who will review the text given and add the comment to improve the content
""",
tools=[
MCPToolset(
connection_params=StdioServerParameters(
command='npx',
args=[
"-y",
"@veltdev/api-mcp",
os.path.abspath(TARGET_FOLDER_PATH),
],
stderr=subprocess.STDOUT,
timeout=60,
env={
"VELT_API_KEY": api_key,
"VELT_AUTH_TOKEN": auth_token,
}
),
tool_filter=[
'get-comment-annotations',
'get-comments',
'add-comments',
'update-comments',
'delete-comments',
'add-comment-annotations',
'update-comment-annotations',
'delete-comment-annotations',
]
)
],
)
```
# Managing Different Environments
Source: https://velt.dev/docs/migration/environments
Manage production, staging, and development environments with Velt API keys
Each API key in Velt represents a separate environment with completely isolated data and settings.
## Environment types
### Production
When you upgrade to a production plan, you receive a production API key.
#### Setup in 4 quick steps
##### **1. Upgrade your plan**
Select a production plan in the Velt Console. A production API key is generated automatically.
##### **2. Configure production environment**
Manually replicate your staging configurations:
* Feature settings
* UI customization
* Webhooks
* Permissions
##### **3. Update your application**
Replace the development API key with your production API key in all locations.
> [!WARNING]
>
> Update environment variables, config files, and any hardcoded references.
##### **4. Test**
Verify all features work with the production API key before going live.
#### **Regional keys (Enterprise only)**
Enterprise customers can create production API keys for specific regions to reduce latency and meet data residency requirements. See [Supported Regions](/docs/security/supported-regions) for all available regions.
Example use cases:
* North America key for US/Canadian users
* EU key for GDPR compliance
* Additional regional keys as needed
### Staging and development
Create up to **10 API keys** for non-production environments. Use these for:
* Staging environments per team or feature
* Individual developer environments
* Testing and QA
# Migrate from Cord to Velt
Source: https://velt.dev/docs/migration/migrate-from-cord-to-velt
Cord has shut down their service. We are providing a migration path for all the Cord users to migrate to Velt.
## Migration Process Overview
* Download the cord data in JSON format using their REST APIs. Send it to us using a secure file-sharing system.
* We have an internal service written to transform that data and add it to your Velt account. You need not use our APIs for this. We will do it for you.
* It will take about a week for the end-to-end migration process. We can expedite it to be 1-2 days if it's more urgent for you.
* If you prefer, we can also help you migrate over to Velt on production over a weekend so that your customers don't notice any changes.
## Migration Steps
### 1. Step 1: Provide Test Account Access
Give us access to a test account in your app where Cord is implemented. It should contain some cord comments.
### 2. Step 2: Export Test Data
Export the Cord data from the above test account and send it to us. [Learn more](#exporting-cord-data)
### 3. Step 3: Sample Migration
We will migrate that small sample first and verify it with you.
### 4. Step 4: Full Data Export
Once everything looks good, you will send all of the Cord data as JSON files. We will do a test run on the entire dataset.
### 5. Step 5: Schedule Migration
Schedule a migration date: On this date, all your cord production data (as of this date) with Velt implemented in your app will go live.
## Exporting Cord Data
> [!WARNING]
>
> ### Note:
>
> * These APIs have pagination built-in and return 1000 entries by default. Either extend the limit or loop over the pages to get all the data.
> * Send data pulled from each API in a separate JSON file.
## Comments
Use the following Cord REST APIs to pull all the comments-related data and export it as a JSON file:
• [Threads](https://docs.cord.com/rest-apis/threads)
• [Messages](https://docs.cord.com/rest-apis/messages)
• [Users](https://docs.cord.com/rest-apis/users)
• [Groups](https://docs.cord.com/rest-apis/groups)
## Comment File Attachments
When you pull thread and message data using the above APIs, the file attachment URL is also present in the data. However, those URLs expire. You have two options for migration:
**Option 1**: You can use the URL to download the files and upload them to your cloud. Send us the new file attachment URLs in the following format in a JSON file:
Sample Format:
```jsx theme={null}
[{
"documentId": "",
"userId": "",
"messageId": "",
"type": "file",
"fileData": {
"id": "",
"type": "file",
"name": "",
"url": "",
"mimeType": "MIME_TYPE",
"size": 6278949,
"uploadStatus": "uploaded"
},
"fileUrl": ""
}]
```
**Option 2**: Schedule file migration date with us so you can pull the latest comments data, which will have fresh file access tokens. Then we can download/store it on our end, and update the URLs ourselves.
## Notifications
Given the ephemeral nature of notifications, we don't think you need to migrate them. However, if you do want us to migrate your notifications data, you could use this API to get the notifications data from Cord:
* [Notifications](https://docs.cord.com/rest-apis/notifications)
# Migrate from Liveblocks to Velt
Source: https://velt.dev/docs/migration/migrate-from-liveblocks-to-velt
For customers facing limitations with Liveblocks (eg: features, security, pricing, etc.), we provide an easy path to migrate to Velt.
## Migration Process Overview
* Export your Liveblocks data in JSON format using [their REST APIs](https://liveblocks.io/docs/api-reference/rest-api-endpoints#get-rooms-roomId-threads) and send it to us through a secure file-sharing system.
* You have two options for migration: (1) Transform the data yourself and use [our REST APIs](/docs/api-reference/rest-apis/v2/comments-feature/comment-annotations/add-comment-annotations) to migrate it, or (2) Send us the raw Liveblocks data and we'll handle the transformation and migration for you.
* The complete migration process typically takes about a week or so.
* We can coordinate the production migration over a weekend to ensure zero downtime and a seamless transition for your users.
## Migration Steps
### 1. Step 1: Provide Test Account Access
Provide us with access to a test account in your application where Liveblocks is currently implemented. This test account should contain existing Liveblocks comments and collaboration data for validation purposes.
### 2. Step 2: Export Sample Data
Export the Liveblocks data from your test account and securely share it with us. This allows us to understand your data structure and perform initial validation. [Learn more](#exporting-liveblocks-data)
### 3. Step 3: Sample Migration & Validation
We will perform a migration on your sample data and work with you to verify that all comments, user data, and collaboration features have been accurately migrated to Velt.
### 4. Step 4: Full Data Export & Testing
After successful validation of the test migration, export your complete Liveblocks production dataset as JSON files. We will perform a comprehensive test migration on the full dataset to ensure data integrity.
### 5. Step 5: Production Migration
Schedule your production migration date. On the agreed date, we will migrate all your Liveblocks production data to Velt and coordinate the go-live process to ensure a seamless transition for your users.
## Exporting Liveblocks Data
### Comments
Use the following Liveblocks REST APIs to pull all the comments-related data and export it as a JSON file:
• [Threads](https://liveblocks.io/docs/api-reference/rest-api-endpoints#get-rooms-roomId-threads)
• [Comments](https://liveblocks.io/docs/api-reference/rest-api-endpoints#get-rooms-roomId-threads-threadId-comments-commentId)
### Users
Use the following Liveblocks REST APIs to pull all the users-related data and export it as a JSON file:
• [Users](https://liveblocks.io/docs/api-reference/rest-api-endpoints#get-rooms-roomId-active-users)
### Notifications
Given the ephemeral nature of notifications, we don't think you need to migrate them. However, if you do want us to migrate your notifications data, you could use this API to get the notifications data from Liveblocks:
* [Notifications](https://liveblocks.io/docs/api-reference/rest-api-endpoints#get-users-userId-inboxNotifications)
# Parts
Source: https://velt.dev/docs/permission-management/share-and-invite/customize-ui/parts
## 1. Select the part you want to modify
We offer several parts which can be used like classes. Full list below.
The component is encapsulated in Shadow DOM, which is isolated from the normal DOM.
## 2. Apply your CSS rules
Set whatever CSS rules you want.
The part lets you target a specific element within a Shadow DOM.
## 3. Check out the table below
Reference the table below to see what parts we expose.
Alternatively, you can directly inspect the component HTML to see what parts are available.
| property | description |
| - | - |
| `container` | Targets the comment tool container |
| `button-container` | Targets the comment tool button container |
| `button-icon` | Targets the comment tool button SVG icon |
```css Tool theme={null}
velt-user-invite-tool::part(button-icon) {
width: 1.5rem;
height: 1.5rem;
}
```
# Slots
Source: https://velt.dev/docs/permission-management/share-and-invite/customize-ui/slots
> [tab] React / Next.js
>
> ## 1. Replace the User Invite Tool
>
> Provide a template for the User Invite Tool.
>
> Target the `button` slot with your own custom template.
>
> ```js theme={null}
>
> User Invite
>
> ```
> [tab] Other Frameworks
>
> ## 1. Replace the User Invite Tool
>
> Provide a template for the User Invite Tool.
>
> Target the `button` slot with your own custom template.
>
> ```html theme={null}
>
> User Invite
>
> ```
```js React / Next.js theme={null}
import {
VeltUserInviteTool
} from '@veltdev/react';
export default function App() {
return (
<>
User Invite
>
);
}
```
```html HTML theme={null}
User Invite documentation
User Invite
```
# Variables
Source: https://velt.dev/docs/permission-management/share-and-invite/customize-ui/variables
To update CSS variables for the User Invite Tool, please refer to [Global Styles](/docs/global-styles/global-styles)
# Invite
Source: https://velt.dev/docs/permission-management/share-and-invite/overview
A widget to invite others to collaborate together on a project
[https://landing-page-demo-velt.vercel.app/?feature=user-invite](https://landing-page-demo-velt.vercel.app/?feature=user-invite)
[Open in larger window](https://landing-page-demo-velt.vercel.app/?feature=user-invite)
# Setup
Source: https://velt.dev/docs/permission-management/share-and-invite/setup
> [tab] React / Next.js
>
> ## 1. Import VeltUserInviteTool from @veltdev/react
>
> Import the `VeltUserInviteTool` component
>
> ```js theme={null}
> import { VeltUserInviteTool } from '@veltdev/react';
> ```
>
> ## 2. Place the VeltUserInviteTool component
>
> Place the component wherever you want the invite button to appear.
>
> ```js theme={null}
>
> ```
> [tab] Other Frameworks
>
> ## 1. Place the \ component
>
> Place the component wherever you want the invite button to appear.
>
> ```html theme={null}
>
> ```
```js React / Next.js theme={null}
import { VeltUserInviteTool } from '@veltdev/react';
function YourComponent() {
return (
//
//
)
}
```
```html HTML theme={null}
Collaboration App
```
# Overview
Source: https://velt.dev/docs/realtime-collaboration/crdt/overview
Build collaborative editors, whiteboards, and shared app state with Velt's Yjs-based CRDT stores, version history, and editor integrations.
CRDT (Yjs) based collaborative editing. This feature is useful for building collaborative features like shared forms, whiteboards, or any real-time state that needs to be synced across all users.
* This is framework agnostic.
* Use our [Core guide](./setup/core) to create custom integrations if a purpose built library is not listed below
* Out of box support for the following libraries:
* [Tiptap Editor](./setup/tiptap)
* [ReactFlow](./setup/reactflow)
* [CodeMirror](./setup/codemirror)
* [BlockNote](./setup/blocknote)
* [SuperDoc React](./setup/superdoc)
* [Lexical React](./setup/lexical)
* [Slate](./setup/slate)
* [Draft.js](./setup/draftjs)
* [TinyMCE React](./setup/tinymce)
* [Monaco React](./setup/monaco)
* [ProseMirror React](./setup/prosemirror)
* [CKEditor React](./setup/ckeditor)
* [Apryse React](./setup/apryse)
* [SpreadJS React](./setup/spreadjs)
* [Nutrient React](./setup/nutrient)
* [Ace React](./setup/ace)
* [Quill React](./setup/quill)
## What you can build
* **Collaborative text editing**: rich text editors, notes, documents
* **Visual collaboration**: whiteboards, diagrams, flow editors
* **Shared app state**: forms, lists, dashboards synchronized across users
## Packages at a glance
* **Core library (`@veltdev/crdt`)**: Framework-agnostic CRDT stores (array, map, text, xml), versioning, subscriptions, and syncing via the Velt client. See setup: [`Core`](./setup/core).
* **React Hook Wrapper (`@veltdev/crdt-react`)**: A typed React hook for creating and consuming CRDT stores with minimal boilerplate. See setup: [`Core`](./setup/core).
* **Editor integrations**:
* **Tiptap**: Collaborative text editing with cursors and history. See setup: [`Tiptap`](./setup/tiptap).
* **ReactFlow**: Collaborative node/edge graphs. See setup: [`ReactFlow`](./setup/reactflow).
* **CodeMirror**: Collaborative code editing. See setup: [`CodeMirror`](./setup/codemirror).
* **BlockNote**: Collaborative block-based editor. See setup: [`BlockNote`](./setup/blocknote).
* **SuperDoc React**: Collaborative DOCX editing. See setup: [`SuperDoc`](./setup/superdoc).
* **Lexical React**: Collaborative structured rich-text editing. See setup: [`Lexical`](./setup/lexical).
* **Slate**: Collaborative customizable rich-text editing. See setup: [`Slate`](./setup/slate).
* **Draft.js**: Collaborative Draft.js content editing. See setup: [`Draft.js`](./setup/draftjs).
* **TinyMCE React**: Collaborative HTML rich-text editing. See setup: [`TinyMCE`](./setup/tinymce).
* **Monaco React**: Collaborative code editing with Monaco. See setup: [`Monaco`](./setup/monaco).
* **ProseMirror React**: Collaborative schema-driven rich-text editing. See setup: [`ProseMirror`](./setup/prosemirror).
* **CKEditor React**: Collaborative CKEditor content editing. See setup: [`CKEditor`](./setup/ckeditor).
* **Apryse React**: Collaborative PDF annotation review. See setup: [`Apryse`](./setup/apryse).
* **SpreadJS React**: Collaborative spreadsheet editing. See setup: [`SpreadJS`](./setup/spreadjs).
* **Nutrient React**: Collaborative document annotation review. See setup: [`Nutrient`](./setup/nutrient).
* **Ace React**: Collaborative code editing with Ace. See setup: [`Ace`](./setup/ace).
* **Quill React**: Collaborative rich-text editing with Quill. See setup: [`Quill`](./setup/quill).
## Why Velt CRDT
* **Conflict‑free sync**: Yjs ensures eventual consistency without merge conflicts.
* **Low latency, offline‑first**: Local writes with automatic re‑sync when back online.
* **Batteries included**: Version history, subscriptions, presence, and editor integrations.
* **Use anywhere**: Core library for any framework; React Hook wrapper for the fastest React integration.
## Key capabilities
* **Low latency**: Optimized for snappy, real-time updates.
* **Offline-first**: Local-first reads/writes with automatic re-sync when back online.
* **Conflict-free**: Yjs CRDT ensures eventual consistency without merge conflicts.
* **Multi-tab support**: Same user can edit in multiple tabs simultaneously with full synchronization.
* **Version history**: Create checkpoints and restore prior states when needed.
* **Framework agnostic**: Use anywhere; React hook available for faster integration.
## Version history
Every Velt CRDT store supports saving named snapshots and restoring the document to any previous version. This works for plain stores (array, map, text, xml) and for the editor integrations built on top of them (Tiptap, BlockNote, CodeMirror, ReactFlow).
Core methods exposed on the store (or via `useStore` in React):
* `saveVersion(name)` — save a named snapshot of the current state.
* `getVersions()` — list all saved versions.
* `getVersionById(id)` — fetch a specific version.
* `restoreVersion(id)` — restore the document to a saved version.
* `setStateFromVersion(version)` — apply a version's state locally.
See full usage and examples in:
* [Core library](./setup/core#version-methods) — generic version APIs for any store type
* [Text store](./setup/core-stores/text) and [XML store](./setup/core-stores/xml) — version save/restore for text-based documents
* [Tiptap](./setup/tiptap), [BlockNote](./setup/blocknote), [CodeMirror](./setup/codemirror), [ReactFlow](./setup/reactflow) — editor-specific version history
## How it works
* You initialize the Velt client in your app.
* You create a CRDT store (core or via the React hook) with a unique `id` and a data `type`.
* Components subscribe to the store to render the latest value and push updates.
* Yjs merges concurrent edits; Velt handles synchronization between connected clients.
## Choose your path
* **React apps**: Start with the React Hook wrapper in [`setup/core`](./setup/core#react-hook-wrapper-%40veltdev%2Fcrdt-react) (React tab).
* **Other frameworks / vanilla**: Use the core library in [`setup/core`](./setup/core#other-frameworks-%40veltdev%2Fcrdt) (Non‑React tab).
* **Editor and document integrations**: Choose a dedicated guide from the supported integrations listed above.
## Try it yourself!
[https://sample-apps-tiptap-crdt-demo.vercel.app/](https://sample-apps-tiptap-crdt-demo.vercel.app/)
[Open in larger window](https://sample-apps-tiptap-crdt-demo.vercel.app/)
# INTEGRATION GUIDELINES
Source: https://velt.dev/docs/realtime-collaboration/crdt/setup/INTEGRATION_GUIDELINES
# CRDT Editor Integration Documentation Guidelines
Use this guide when creating or updating CRDT editor integration pages in this
directory. The goal is to keep React and framework-agnostic instructions on one
page while preserving the initialization and cleanup requirements of each
editor.
## Scope
These guidelines currently cover:
1. SuperDoc
2. Lexical
3. TinyMCE
4. Monaco
5. ProseMirror
6. CKEditor
7. Apryse
8. SpreadJS
9. Nutrient
10. Ace
11. Quill
## Verified framework-agnostic sources
Treat the matching `INTEGRATION.md` as the source of truth for package names,
public APIs, editor lifecycle, supported options, and cleanup behavior.
| Library | Repository | Path within repository |
| - | - | - |
| SuperDoc | `superdoc-crdt` | `demo/INTEGRATION.md` |
| Lexical | `lexical-crdt` | `demo/INTEGRATION.md` |
| TinyMCE | `tinymce-crdt` | `demo/INTEGRATION.md` |
| Monaco | `monaco-crdt` | `demo/INTEGRATION.md` |
| ProseMirror | `prosemirror-crdt` | `demo/INTEGRATION.md` |
| CKEditor | `ckeditor-crdt` | `demo/INTEGRATION.md` |
| Apryse | `apryse-crdt` | `demo/INTEGRATION.md` |
| SpreadJS | `spreadjs-crdt` | `demo/INTEGRATION.md` |
| Nutrient | `nutrient-crdt` | `demo/INTEGRATION.md` |
| Ace | `ace-crdt` | `demo/INTEGRATION.md` |
| Quill | `quill-crdt` | `demo/INTEGRATION.md` |
When information differs between a source integration and an existing docs
example, verify the current package implementation before changing behavior.
Do not infer framework-agnostic behavior by mechanically removing React hooks.
## Page strategy
Each library MUST have one combined documentation page. Do not create separate
React and non-React pages.
Use the established patterns in these pages:
* `core.mdx`
* `tiptap.mdx`
* `codemirror.mdx`
Use these labels consistently:
* `React / Next.js`
* `Other Frameworks`
Use **Other Frameworks**, not **Non-React**. The imperative packages can be used
with Vue, Angular, Svelte, vanilla JavaScript, and other environments.
## When to use tabs
Tabs MUST represent a real framework or API boundary. Do not duplicate every
step merely to maintain two parallel versions.
Use `React / Next.js` and `Other Frameworks` tabs for:
* Installing framework-specific packages
* Initializing Velt
* Authenticating users and setting document context
* Creating or binding an editor when construction differs
* Subscribing through hooks versus client or manager callbacks
* Configuring encryption through `VeltProvider` versus the client API
* Cleaning up automatically versus explicitly destroying resources
* Complete working examples
Keep content outside tabs when it is identical, including:
* Conceptual explanations
* Shared configuration options
* Required CSS that does not depend on the framework
* Collaboration behavior
* Troubleshooting guidance
* Shared manager methods and types
* Testing requirements
Do not nest tabs. For the main collaboration initialization step, use one tab
group with the applicable variants:
1. `React Component`
2. `React Hook`
3. `Other Frameworks`
If a page currently has an `Imperative API` tab, rename it to `Other Frameworks`
and expand it into a complete framework-agnostic lifecycle. A factory call by
itself is not a usable integration example.
## Required page structure
Use this order unless the editor has a documented lifecycle requirement that
makes a different order necessary:
1. Frontmatter, introduction, and shared prerequisites
2. Setup
3. Install dependencies
4. Initialize Velt
5. Authenticate the user and set document context
6. Create or load the editor/viewer
7. Initialize collaboration
8. Monitor connection and initialization status
9. Configure initial content and version management
10. Add cursor, selection, or overlay styling
11. Add editor-specific collaboration features
12. Subscribe to CRDT events
13. Configure encryption when applicable
14. Handle errors
15. Clean up resources
16. Notes
17. Testing and debugging
18. Complete example
19. How it works
20. API reference and types
The complete examples MUST follow the same ordering and APIs shown in the
individual steps.
## Content rules
### Prerequisites and terminology
* Keep shared browser, package-manager, Velt account, and editor-license
requirements outside tabs.
* Keep React-specific prerequisites inside the React tab or label them clearly.
* Do not describe a combined page or navigation title as React-only.
* Use the editor's official product name and capitalization consistently.
### Velt initialization
* Initialize the Velt client before creating a collaboration manager.
* Authenticate the user before establishing document collaboration.
* Set a stable document ID and editor ID before initializing collaboration.
* Use the same IDs across all collaborators for the same document/editor.
* Describe only readiness conditions that the source implementation actually
checks. Do not claim that a hook waits for document context unless it does.
* Prefer the current authenticated provider pattern in React examples. Do not
introduce deprecated identification APIs.
### Collaboration initialization
* Use the package and exported API from the matching integration source.
* Preserve the editor-specific initialization order.
* Do not initialize or bind the same editor twice.
* If an editor can be attached later, show that as an alternative—not an
additional required step.
* Explain whether initial content is applied only to a new collaborative
document and how force-reset behavior affects existing state.
### Yjs behavior
* Use the Yjs-aware undo/redo implementation required by the binding.
* Disable or omit the editor's native history plugin when it conflicts with
collaborative history.
* Do not create a second Y.Doc or provider when the manager supplies them.
* Avoid multiple bundled copies of Yjs. Duplicate Yjs imports can break shared
type identity and synchronization.
* Treat awareness and cursor state as ephemeral presence data, not persisted
document content.
### Styling
* Include all CSS needed for remote cursors, selections, overlays, and editor
content modes used by the example.
* A remote caret MUST remain visibly distinguishable without relying on a later
optional snippet.
* When an editor supports iframe and inline modes, explain which styles each
mode requires.
### Cleanup
* React examples MUST state whether the wrapper or hook performs cleanup.
* Other Frameworks examples MUST explicitly unsubscribe callbacks and destroy
the collaboration manager.
* Unless a library-specific source requires another order, unsubscribe
callbacks, destroy the collaboration manager so it releases editor listeners,
and then dispose or unload the application-owned editor or viewer.
* Preserve source-documented exceptions explicitly. SuperDoc is the inverse:
destroy SuperDoc while it can still release the manager-owned provider, then
destroy the collaboration manager.
### Source filtering
Translate consumer-facing integration behavior, not repository-maintenance
material. Exclude the following unless they are necessary for using the SDK:
* Demo build commands
* Test selectors and automated test internals
* Repository file maps
* Release and publishing checklists
* Internal implementation details not exposed by the public API
## Library-specific requirements
### SuperDoc
* Create the collaboration manager before constructing SuperDoc.
* Obtain the Y.Doc and provider through `getCollaborationConfig()`.
* Pass that configuration to the SuperDoc document.
* Destroy SuperDoc before destroying the collaboration manager.
### Lexical
* Create and configure the Lexical editor before collaboration initialization.
* Do not register Lexical's normal history plugin when collaborative history is
active.
* Explain that collaborative undo/redo is backed by Yjs.
* Preserve the automatic remote-cursor overlay behavior.
### TinyMCE
* Initialize TinyMCE before creating the collaboration manager.
* State that the package supports both inline and iframe-mode editors.
* Do not prescribe mode-specific skin or content CSS unless a verified source
documents those requirements.
* Destroy the collaboration manager before removing the TinyMCE editor.
### Monaco
* Show either automatic binding by passing the editor to
`createCollaboration()` or attach-later binding with `bindEditor()`.
* Never show both binding paths in the same initialization flow.
* Include a visible border or equivalent treatment for remote carets.
* Destroy the collaboration manager before disposing the Monaco editor.
### ProseMirror
* Direct plugin wiring MUST use `autoInitialize: false`.
* Create the collaboration plugins before creating `EditorState` and
`EditorView`.
* Attach the completed view with `attachEditorView()`.
* Call `initialize()` only after the view has been attached so remote content
can hydrate correctly.
* Destroy both the view and collaboration manager during cleanup.
### CKEditor
* Create the CKEditor instance before creating the collaboration manager.
* Supplement the source integration with the shared Core Velt initialization,
authentication, and document-context flow where needed.
* Do not claim the wrapper waits for conditions that its implementation does
not check.
### Apryse
* Initialize the WebViewer instance before creating collaboration.
* Destroy the collaboration manager before disposing WebViewer.
* Exclude demo commands, test selectors, repository maps, and release-checklist
sections from the public guide.
### SpreadJS
* Create the workbook before creating the collaboration manager.
* Recommend passing `GC.Spread.Sheets.Events`, and note that fallback event
strings are available for simple setups.
* Document attach/detach behavior as an alternative lifecycle.
* Destroy the collaboration manager before disposing the workbook.
### Nutrient
* Load the viewer before creating collaboration.
* Pass the viewer host as `overlayContainer` when remote overlays are needed.
* Document viewer attach/detach behavior when applicable.
* Destroy the collaboration manager before unloading the Nutrient viewer.
* Do not claim the hook waits for document context unless verified in source.
### Ace
* Create the Ace editor before creating collaboration.
* Explain that the wrapper can resolve Ace's global Range module and that an
explicit `rangeFactory` is optional.
* Document attach/detach behavior when applicable.
* Destroy the manager before destroying the editor and removing its DOM.
### Quill
* Load the required Quill styles and register `quill-cursors` before creating
the editor.
* Use the Yjs-aware undo/redo path rather than Quill's standalone history.
* Ensure the application resolves only one compatible Yjs instance.
* Unsubscribe callbacks before destroying the collaboration manager.
## Navigation rules
* Keep exactly one `docs.json` navigation entry per library.
* Keep the CRDT/Multiplayer integration entries alphabetical.
* Do not add separate Other Frameworks navigation entries.
* Remove `React` from combined-page titles and navigation labels unless React is
genuinely the only supported integration.
* Keep the existing page slug when combining content so published links remain
stable.
## Recommended implementation order
Update and review the pages one at a time in this order:
1. SuperDoc
2. Lexical
3. TinyMCE
4. Monaco
5. ProseMirror
6. CKEditor
7. Apryse
8. SpreadJS
9. Nutrient
10. Ace
11. Quill
Use SuperDoc as the initial combined-page template. Treat Monaco and
ProseMirror as explicit lifecycle review checkpoints because binding order is
especially important in those integrations.
## Review checklist
Before considering a page complete, verify all of the following:
* [ ] The package names and imports match the integration source.
* [ ] React and Other Frameworks instructions live on the same page.
* [ ] Tab labels and ordering match the established docs convention.
* [ ] Shared prose and API tables are not duplicated across tabs.
* [ ] Velt initialization, authentication, and document setup occur in the
correct order.
* [ ] Editor/viewer creation and collaboration initialization follow the source
lifecycle.
* [ ] The example does not bind the editor twice.
* [ ] Initial-content and version behavior is described accurately.
* [ ] Undo/redo uses the collaboration-aware implementation.
* [ ] Cursor, selection, overlay, skin, and content CSS is complete.
* [ ] Framework-agnostic cleanup is explicit and ordered correctly.
* [ ] The complete examples agree with the smaller setup snippets.
* [ ] Demo-only, test-only, and release-only source material is excluded.
* [ ] Troubleshooting includes testing with two authenticated users in separate
browser profiles or sessions.
* [ ] The page title and navigation label are no longer React-only.
* [ ] `docs.json` contains one alphabetical entry for the page.
* [ ] Formatting and link checks pass.
# Ace Editor
Source: https://velt.dev/docs/realtime-collaboration/crdt/setup/ace
Setup Multiplayer Editing for Ace Editor.
The `@veltdev/ace-crdt-react` and `@veltdev/ace-crdt` libraries connect Ace Editor to a Velt CRDT text Store backed by [Yjs](https://docs.yjs.dev/). Shared content lives in one `Y.Text`; cursors, selections, and attention highlights use transient awareness state.
## Prerequisites
* Node.js (v14 or higher)
* A Velt account with an API key ([sign up](https://console.velt.dev/))
* React (v18 or higher) when using the React wrapper
* Optional: TypeScript for type safety
## Setup
### Step 1: Install Dependencies
> [tab] React / Next.js
>
> ```bash theme={null}
> npm install @veltdev/ace-crdt-react @veltdev/ace-crdt react-ace ace-builds @veltdev/react @veltdev/types react react-dom
> ```
> [tab] Other Frameworks
>
> ```bash theme={null}
> npm install @veltdev/ace-crdt ace-builds @veltdev/client @veltdev/crdt @veltdev/types yjs y-protocols
> ```
The current base wrapper peer range targets `ace-builds@^1.44.0`. Keep one copy of `@veltdev/crdt`, `yjs`, and `y-protocols` in the final application bundle.
### Step 2: Setup Velt
Initialize Velt, authenticate a user, and set stable document identity before constructing the collaboration manager. Follow the [Velt Setup Docs](/docs/get-started/quickstart) for the production token endpoint used by `authProvider`.
> [tab] React / Next.js
>
> ```tsx theme={null}
> import { useEffect, useState } from 'react';
> import {
> VeltProvider,
> useCurrentUser,
> useSetDocuments,
> } from '@veltdev/react';
>
> const DOCUMENT_ID = 'shared-code-file';
> const USER = {
> userId: 'ada',
> name: 'Ada Lovelace',
> email: 'ada@example.com',
> organizationId: 'my-org-id',
> };
>
> const authProvider = {
> user: USER,
> retryConfig: { retryCount: 3, retryDelay: 1000 },
> generateToken: async () => {
> const response = await fetch('/api/velt/token', {
> method: 'POST',
> headers: { 'Content-Type': 'application/json' },
> body: JSON.stringify(USER),
> });
> const { token } = await response.json();
> return token;
> },
> };
>
> function DocumentScope() {
> const user = useCurrentUser();
> const { setDocuments } = useSetDocuments();
> const [documentReady, setDocumentReady] = useState(false);
>
> useEffect(() => {
> if (!user) return;
> setDocuments([{
> id: DOCUMENT_ID,
> metadata: { documentName: 'Shared Ace file' },
> }]);
> setDocumentReady(true);
> }, [user, setDocuments]);
>
> return user && documentReady
> ?
> : Preparing collaboration...
;
> }
>
>
>
>
> ```
> [tab] Other Frameworks
>
> ```ts theme={null}
> import { initVelt } from '@veltdev/client';
>
> const DOCUMENT_ID = 'shared-code-file';
> const client = await initVelt('YOUR_VELT_API_KEY');
>
> await client.identify({
> userId: 'ada',
> name: 'Ada Lovelace',
> email: 'ada@example.com',
> organizationId: 'my-org-id',
> });
> await client.setDocument(DOCUMENT_ID, {
> documentName: 'Shared Ace file',
> });
>
> let resolveVeltReady!: () => void;
> const veltReady = new Promise((resolve) => {
> resolveVeltReady = resolve;
> });
> const initSubscription = client.getVeltInitState().subscribe((isReady) => {
> if (isReady) resolveVeltReady();
> });
> await veltReady;
> initSubscription.unsubscribe();
> ```
All users editing the same file must use the same Velt document ID and Ace `editorId`.
### Step 3: Create the Ace Editor
The host needs stable dimensions. Import each mode and theme before selecting it.
```html theme={null}
```
```css theme={null}
.ace-host {
width: 100%;
height: 520px;
min-height: 360px;
}
```
> [tab] React / Next.js
>
> `AceCrdtEditor` creates a `react-ace` editor. When using the hook with an editor your application owns, create Ace normally and pass the instance to the hook:
>
> ```tsx theme={null}
> import ace from 'ace-builds/src-noconflict/ace';
> import 'ace-builds/src-noconflict/mode-typescript';
> import 'ace-builds/src-noconflict/theme-textmate';
>
> const editor = ace.edit(hostElement);
> editor.setTheme('ace/theme/textmate');
> editor.session.setMode('ace/mode/typescript');
> editor.session.setUseWorker(false);
> ```
> [tab] Other Frameworks
>
> ```ts theme={null}
> import ace from 'ace-builds/src-noconflict/ace';
> import 'ace-builds/src-noconflict/mode-typescript';
> import 'ace-builds/src-noconflict/theme-textmate';
>
> const host = document.querySelector('#ace-editor')!;
> const editor = ace.edit(host);
> editor.setTheme('ace/theme/textmate');
> editor.session.setMode('ace/mode/typescript');
> editor.session.setUseWorker(false);
> editor.setOptions({
> fontSize: 14,
> tabSize: 2,
> useSoftTabs: true,
> showPrintMargin: false,
> wrap: true,
> });
> ```
### Step 4: Initialize Collaboration
Ace markers require a real Ace `Range`. The factory below also widens a collapsed cursor by one column so the remote caret stays visible.
> [tab] React Component
>
> ```tsx theme={null}
> import ace from 'ace-builds/src-noconflict/ace';
> import { AceCrdtEditor } from '@veltdev/ace-crdt-react';
>
> const Range = ace.require('ace/range').Range;
>
> function CollaborativeEditor() {
> return (
>
>
documentId="shared-code-file"
> mode="typescript"
> theme="textmate"
> initialContent={'export const greeting = "Hello";\n'}
> cursorData={{
> name: 'Ada Lovelace',
> email: 'ada@example.com',
> color: '#0f766e',
> colorLight: '#0f766e33',
> }}
> rangeFactory={(start, end) => {
> const visibleEnd = start.row === end.row && start.column === end.column
> ? { row: end.row, column: end.column + 1 }
> : end;
> return new Range(
> start.row,
> start.column,
> visibleEnd.row,
> visibleEnd.column,
> );
> }}
> onError={(error) => console.error('Ace collaboration:', error)}
> />
>
> );
> }
> ```
>
> Do not pass `value` or `defaultValue` to `AceCrdtEditor`. The shared `Y.Text` is the content source of truth.
> [tab] React Hook
>
> ```tsx theme={null}
> import ace from 'ace-builds/src-noconflict/ace';
> import { useCollaboration } from '@veltdev/ace-crdt-react';
>
> const Range = ace.require('ace/range').Range;
> const collaboration = useCollaboration({
> editorId: 'shared-code-file',
> editor,
> initialContent: '// Start writing here\n',
> cursorData: { name: 'Ada', color: '#0f766e' },
> rangeFactory: (start, end) => {
> const visibleEnd = start.row === end.row && start.column === end.column
> ? { row: end.row, column: end.column + 1 }
> : end;
> return new Range(start.row, start.column, visibleEnd.row, visibleEnd.column);
> },
> onError: (error) => console.error('Ace collaboration:', error),
> });
> ```
>
> Passing `editor` creates and binds collaboration once. Do not also call `attachEditor(editor)`.
>
> If Ace is created after the hook renders, omit `editor` from the options and pass it through the returned callback instead:
>
> ```tsx theme={null}
> const collaboration = useCollaboration({
> editorId: 'shared-code-file',
> rangeFactory,
> });
>
> collaboration.editorRef(editor);
>
> // Before replacing or destroying Ace:
> collaboration.editorRef(null);
> ```
> [tab] Other Frameworks
>
> ```ts theme={null}
> import { createCollaboration } from '@veltdev/ace-crdt';
>
> const Range = ace.require('ace/range').Range;
> const manager = await createCollaboration({
> editorId: DOCUMENT_ID,
> veltClient: client,
> editor,
> initialContent: '// Start writing here\n',
> cursorData: {
> name: 'Ada Lovelace',
> email: 'ada@example.com',
> color: '#0f766e',
> colorLight: '#0f766e33',
> },
> rangeFactory: (start, end) => {
> const visibleEnd = start.row === end.row && start.column === end.column
> ? { row: end.row, column: end.column + 1 }
> : end;
> return new Range(
> start.row,
> start.column,
> visibleEnd.row,
> visibleEnd.column,
> );
> },
> onError: (error) => console.error('Ace collaboration:', error),
> });
> ```
#### React Context Provider (Optional)
React applications can expose one hook-managed collaboration value through context:
```tsx theme={null}
import { AceCrdtProvider } from '@veltdev/ace-crdt-react';
{(collaboration) => (
collaboration.saveVersion('Checkpoint')}>
Save version
)}
```
`CollaborationProvider` is an alias of `AceCrdtProvider`. Use one provider or one hook for an editor, not both.
### Step 5: Add Remote Marker Styles
The manager injects per-user marker colors and labels dynamically. Keep the editor sized and add a shared shape rule:
```css theme={null}
.ace-host {
width: 100%;
height: 520px;
min-height: 360px;
}
.ace_marker-layer [class*="velt-ace-remote-marker"] {
border-radius: 2px;
}
```
Cursor markers receive a visible two-pixel left border; selections and highlights receive a border plus a translucent background. Do not override those injected borders with `border: none`.
### Step 6: Monitor Status and Remote Selections
> [tab] React / Next.js
>
> The component render function and hook expose reactive `status`, `synced`, `remoteSelections`, and `stats` values:
>
> ```tsx theme={null}
>
> {(collaboration) => (
>
> {collaboration.status} · {collaboration.synced ? 'Synced' : 'Syncing'}
> {' · '}{collaboration.remoteSelections.length} remote selections
>
> )}
>
> ```
> [tab] Other Frameworks
>
> ```ts theme={null}
> const offStatus = manager.onStatusChange((status) => {
> document.querySelector('#status')!.textContent = status;
> });
> const offSynced = manager.onSynced((synced) => {
> document.querySelector('#synced')!.textContent = synced ? 'Yes' : 'No';
> });
> const offRemote = manager.onRemoteSelectionsChange((selections) => {
> console.log('Remote cursor, selection, and highlight state:', selections);
> });
> ```
Ace cursor and selection events are published automatically after attachment, and awareness changes trigger remote marker rendering. Custom UI can publish explicitly:
```ts theme={null}
manager.publishCurrentSelection('cursor');
manager.publishCurrentSelection('selection');
manager.addHighlight({
start: { row: 0, column: 0 },
end: { row: 0, column: 10 },
}, '#f59e0b');
```
Cursor, selection, and highlight awareness is ephemeral. It is not part of the shared file or a saved version.
### Step 7: Initial Content and Force Reset
Initial content is plain text and is applied only when the shared text is new and uninitialized:
```ts theme={null}
const initialContent = [
'function add(a, b) {',
' return a + b;',
'}',
].join('\n');
```
Use a reset only for an explicit destructive action:
```ts theme={null}
await manager.forceReset('// Reset file\n');
```
> [!WARNING]
>
> `forceResetInitialContent` and `forceReset()` replace the shared file for every collaborator.
### Step 8: Work with Shared Text
```ts theme={null}
const currentValue = manager.getValue();
manager.setValue('const answer = 42;', 'toolbar-set');
manager.insertText(' // note');
manager.flushEditorToStore('manual-save');
```
`insertText()` accepts an optional character index. Without one, the manager uses the current Ace cursor when available.
### Step 9: Configure Collaborative Undo and Redo
The manager creates one Yjs `UndoManager` for the shared text.
> [tab] React / Next.js
>
> ```tsx theme={null}
> collaboration.undo()}>Undo
> collaboration.redo()}>Redo
> ```
> [tab] Other Frameworks
>
> ```ts theme={null}
> const undoManager = manager.getUndoManager();
>
> undoManager?.undo();
> manager.flushEditorToStore('undo');
>
> undoManager?.redo();
> manager.flushEditorToStore('redo');
> ```
Use these controls as the user-facing collaborative history. Mixing Ace's local history commands with Yjs undo can produce a history that does not match the shared document.
### Step 10: Save and Restore Versions
```ts theme={null}
const versionId = await manager.saveVersion('Before refactor');
const versions = await manager.getVersions();
await manager.restoreVersion(versionId);
```
Saving flushes Ace before the checkpoint. Restoring updates the Store and reapplies the shared text to Ace.
### Step 11: Subscribe to CRDT Events
> [tab] React / Next.js
>
> ```tsx theme={null}
> import { useVeltClient } from '@veltdev/react';
>
> const { client } = useVeltClient();
>
> useEffect(() => {
> if (!client) return;
> const subscription = client.getCrdtElement()
> .on('updateData')
> .subscribe((event) => console.log('CRDT update:', event));
> return () => subscription.unsubscribe();
> }, [client]);
> ```
> [tab] Other Frameworks
>
> ```ts theme={null}
> const crdtSubscription = client.getCrdtElement()
> .on('updateData')
> .subscribe((event) => console.log('CRDT update:', event));
> ```
### Step 12: Attach or Replace an Editor (Alternative)
Use the attach-later lifecycle only when the Store must initialize before Ace:
> [tab] React / Next.js
>
> ```tsx theme={null}
> const collaboration = useCollaboration({
> editorId: 'shared-code-file',
> initializeWithoutEditor: true,
> rangeFactory,
> });
>
> collaboration.attachEditor(editor, { rangeFactory });
> collaboration.detachEditor();
> ```
> [tab] Other Frameworks
>
> ```ts theme={null}
> const manager = await createCollaboration({
> editorId: DOCUMENT_ID,
> veltClient: client,
> rangeFactory,
> });
>
> manager.attachEditor(editor, { rangeFactory });
> manager.detachEditor();
> ```
This replaces passing `editor` to `createCollaboration()`. Do not use both paths in one initialization flow.
### Step 13: Custom Encryption (Optional)
> [tab] React / Next.js
>
> ```tsx theme={null}
> apiKey="YOUR_VELT_API_KEY"
> authProvider={authProvider}
> encryptionProvider={encryptionProvider}
> >
>
>
> ```
> [tab] Other Frameworks
>
> ```ts theme={null}
> client.setEncryptionProvider(encryptionProvider);
> ```
See [setEncryptionProvider()](/docs/api-reference/sdk/api/api-methods#setencryptionprovider-encryptionprovider) and [VeltEncryptionProvider](/docs/api-reference/sdk/models/data-models#veltencryptionprovider).
### Step 14: Clean Up
> [tab] React / Next.js
>
> `useCollaboration()` and `AceCrdtEditor` unsubscribe and destroy their collaboration manager on unmount. When an app owns the Ace instance, use an explicit manager-first cleanup before destroying Ace:
>
> ```tsx theme={null}
> useEffect(() => {
> return () => {
> collaboration.destroy();
> editor.destroy();
> editor.container.remove();
> };
> }, [collaboration.destroy, editor]);
> ```
>
> The hook's later unmount cleanup is idempotent, so the explicit `destroy()` safely preserves the required order.
> [tab] Other Frameworks
>
> Unsubscribe first, destroy collaboration so it releases Ace listeners and markers, then destroy Ace and remove its DOM:
>
> ```ts theme={null}
> offStatus();
> offSynced();
> offRemote();
> crdtSubscription.unsubscribe();
> manager.destroy();
> editor.destroy();
> editor.container.remove();
> ```
## Notes
* **Plain-text model**: Ace modes and themes are local presentation; only text is stored in `Y.Text`.
* **One binding**: Passing `editor` to the factory attaches it automatically.
* **Range factory**: Use Ace's verified `Range` constructor for remote markers.
* **Automatic selections**: The manager attaches Ace selection listeners and publishes cursor/selection state through awareness.
* **Advanced escape hatches**: `getDoc()`, `getYText()`, `getProvider()`, `getAwareness()`, and `getUndoManager()` are for diagnostics or advanced integrations. `getText()` and `getYText()` return the same shared `Y.Text`; internally, `getYText()` delegates to `getText()`. Do not create a second Y.Doc, provider, or shared text.
* **Production authentication**: Use a server-backed React `authProvider` and never expose privileged server tokens in browser code.
## Testing and Debugging
1. Open the same Velt document and Ace `editorId` as two different authenticated users in separate browser profiles.
2. Type and delete concurrently at different positions.
3. Verify visible cursor carets, selected ranges, attention highlights, Yjs undo/redo, versions, reconnect behavior, and persistence.
4. Repeat with the production mode, theme, worker, and bundler configuration.
Common issues:
* Mode or theme is missing: import the matching `ace-builds/src-noconflict` module before creating Ace.
* Text does not sync: remove React `value`/`defaultValue` and confirm both clients use the same IDs.
* Markers do not appear: provide `cursorData`, the complete `rangeFactory`, a sized host, and marker CSS.
* Duplicate Yjs warning: deduplicate `yjs` and `@veltdev/crdt` in the application bundle.
> [!TIP]
>
> Use the [VeltCrdtStoreMap debugging interface](/docs/realtime-collaboration/crdt/setup/core#veltcrdtstoremap) to inspect shared text and provider status.
## Complete Example
> [tab] React / Next.js
>
> ```tsx Complete App.tsx expandable lines theme={null}
> import { useEffect, useMemo, useState } from 'react';
> import ace from 'ace-builds/src-noconflict/ace';
> import 'ace-builds/src-noconflict/mode-typescript';
> import 'ace-builds/src-noconflict/theme-textmate';
> import {
> VeltProvider,
> useCurrentUser,
> useSetDocuments,
> } from '@veltdev/react';
> import { AceCrdtEditor } from '@veltdev/ace-crdt-react';
> import './styles.css';
>
> const DOCUMENT_ID = 'shared-code-file';
> const USER = {
> userId: 'ada',
> organizationId: 'my-org-id',
> name: 'Ada Lovelace',
> email: 'ada@example.com',
> };
> const Range = ace.require('ace/range').Range;
>
> function CollaborativeEditor() {
> const user = useCurrentUser();
> const { setDocuments } = useSetDocuments();
> const [documentReady, setDocumentReady] = useState(false);
>
> useEffect(() => {
> if (!user) return;
> setDocuments([{
> id: DOCUMENT_ID,
> metadata: { documentName: 'Shared Ace file' },
> }]);
> setDocumentReady(true);
> }, [user, setDocuments]);
>
> if (!user || !documentReady) return Preparing collaboration...
;
>
> return (
>
>
>
documentId={DOCUMENT_ID}
> mode="typescript"
> theme="textmate"
> initialContent={'export const greeting = "Hello";\n'}
> cursorData={{
> name: user.name,
> email: user.email,
> color: '#0f766e',
> colorLight: '#0f766e33',
> }}
> rangeFactory={(start, end) => {
> const visibleEnd = start.row === end.row && start.column === end.column
> ? { row: end.row, column: end.column + 1 }
> : end;
> return new Range(
> start.row,
> start.column,
> visibleEnd.row,
> visibleEnd.column,
> );
> }}
> onStatusChange={(status) => console.log('Status:', status)}
> onError={console.error}
> >
> {(collaboration) => (
>
> collaboration.undo()}>Undo
> collaboration.redo()}>Redo
> collaboration.saveVersion('Checkpoint')}>
> Save version
>
> {collaboration.synced ? 'Synced' : collaboration.status}
>
> )}
>
>
>
> );
> }
>
> export default function App() {
> const authProvider = useMemo(() => ({
> user: USER,
> retryConfig: { retryCount: 3, retryDelay: 1000 },
> generateToken: async () => {
> const response = await fetch('/api/velt/token', {
> method: 'POST',
> headers: { 'Content-Type': 'application/json' },
> body: JSON.stringify(USER),
> });
> const { token } = await response.json();
> return token;
> },
> }), []);
>
> return (
>
>
>
> );
> }
> ```
>
> ```css Complete styles.css expandable lines theme={null}
> .ace-host {
> width: 100%;
> height: 520px;
> min-height: 360px;
> }
>
> .ace_marker-layer [class*="velt-ace-remote-marker"] {
> border-radius: 2px;
> }
> ```
> [tab] Other Frameworks
>
> ```html Complete index.html expandable lines theme={null}
> Status: connecting
> Synced: No
> Undo
> Redo
> Save version
>
> ```
>
> ```ts Complete app.ts expandable lines theme={null}
> import ace from 'ace-builds/src-noconflict/ace';
> import 'ace-builds/src-noconflict/mode-typescript';
> import 'ace-builds/src-noconflict/theme-textmate';
> import { initVelt } from '@veltdev/client';
> import {
> createCollaboration,
> type CollaborationManager,
> } from '@veltdev/ace-crdt';
> import './styles.css';
>
> const DOCUMENT_ID = 'shared-code-file';
> const client = await initVelt('YOUR_VELT_API_KEY');
>
> await client.identify({
> userId: 'ada',
> name: 'Ada Lovelace',
> email: 'ada@example.com',
> organizationId: 'my-org-id',
> });
> await client.setDocument(DOCUMENT_ID, {
> documentName: 'Shared Ace file',
> });
>
> let resolveVeltReady!: () => void;
> const veltReady = new Promise((resolve) => {
> resolveVeltReady = resolve;
> });
> const initSubscription = client.getVeltInitState().subscribe((isReady) => {
> if (isReady) resolveVeltReady();
> });
> await veltReady;
> initSubscription.unsubscribe();
>
> const host = document.querySelector('#ace-editor')!;
> const editor = ace.edit(host);
> editor.setTheme('ace/theme/textmate');
> editor.session.setMode('ace/mode/typescript');
> editor.session.setUseWorker(false);
>
> const Range = ace.require('ace/range').Range;
> let manager: CollaborationManager | null = await createCollaboration({
> editorId: DOCUMENT_ID,
> veltClient: client,
> editor,
> initialContent: 'export const greeting = "Hello";\n',
> cursorData: {
> name: 'Ada Lovelace',
> email: 'ada@example.com',
> color: '#0f766e',
> colorLight: '#0f766e33',
> },
> rangeFactory: (start, end) => {
> const visibleEnd = start.row === end.row && start.column === end.column
> ? { row: end.row, column: end.column + 1 }
> : end;
> return new Range(
> start.row,
> start.column,
> visibleEnd.row,
> visibleEnd.column,
> );
> },
> onError: console.error,
> });
>
> document.querySelector('#status')!.textContent = manager.status;
> document.querySelector('#synced')!.textContent = manager.synced ? 'Yes' : 'No';
>
> const offStatus = manager.onStatusChange((status) => {
> document.querySelector('#status')!.textContent = status;
> });
> const offSynced = manager.onSynced((synced) => {
> document.querySelector('#synced')!.textContent = synced ? 'Yes' : 'No';
> });
> const offRemote = manager.onRemoteSelectionsChange((selections) => {
> console.log('Remote selections:', selections);
> });
> const crdtSubscription = client.getCrdtElement()
> .on('updateData')
> .subscribe((event) => console.log('CRDT update:', event));
>
> document.querySelector('#undo')!.addEventListener('click', () => {
> manager?.getUndoManager()?.undo();
> manager?.flushEditorToStore('undo');
> });
> document.querySelector('#redo')!.addEventListener('click', () => {
> manager?.getUndoManager()?.redo();
> manager?.flushEditorToStore('redo');
> });
> document.querySelector('#save-version')!.addEventListener('click', () => {
> void manager?.saveVersion('Manual checkpoint');
> });
>
> let cleanedUp = false;
> function cleanup() {
> if (cleanedUp) return;
> cleanedUp = true;
> offStatus();
> offSynced();
> offRemote();
> crdtSubscription.unsubscribe();
> manager?.destroy();
> manager = null;
> editor.destroy();
> editor.container.remove();
> }
>
> window.addEventListener('pagehide', cleanup, { once: true });
> ```
>
> ```css Complete styles.css expandable lines theme={null}
> .ace-host {
> width: 100%;
> height: 520px;
> min-height: 360px;
> }
>
> .ace_marker-layer [class*="velt-ace-remote-marker"] {
> border-radius: 2px;
> }
> ```
## How It Works
1. The app initializes Velt, authenticates the user, sets the document, and creates one Ace editor.
2. The manager creates a Velt text Store, shared `Y.Text`, provider, awareness bridge, and Yjs `UndoManager`.
3. Ace deltas are converted to character offsets and applied as Yjs insert/delete transactions.
4. Remote Yjs updates are applied back to Ace without echoing into a second local transaction.
5. Ace selection events publish awareness state; the range factory converts remote row/column data into visible Ace markers.
6. Cleanup removes subscriptions and markers before the app destroys Ace and its DOM.
## APIs
### React: AceCrdtEditor
| Prop group | Important props |
| - | - |
| Collaboration | `editorId`, `documentId`, `initialContent`, `forceResetInitialContent`, `cursorData`, `rangeFactory`, `debounceMs`, `enabled` |
| Ace | `mode`, `theme`, `name`, `width`, `height`, `setOptions`, and other React Ace props |
| Lifecycle | `onLoad`, `onEditorReady`, `onManagerReady`, `onStatusChange`, `onError` |
| UI | `children` render function |
### React: useCollaboration()
The hook returns `editorRef`, editor and manager state, shared text helpers, selection/highlight helpers, collaborative `undo()`/`redo()`, versions, statistics, attachment methods, and `destroy()`. It includes `isSynced`, `versions`, `refreshSnapshots()`, and `refreshVersions()` alongside the save and restore helpers. `value`, `remoteSelections`, and `stats` are reactive snapshots.
### CollaborationManager Methods
| Method group | Methods |
| - | - |
| Lifecycle | `initialize()`, `destroy()`, `attachEditor()`, `detachEditor()` |
| Text | `getValue()`, `setValue()`, `insertText()`, `flushEditorToStore()`, `forceReset()` |
| Awareness | `setLocalSelection()`, `publishCurrentSelection()`, `addHighlight()`, `getRemoteSelections()`, `renderRemoteSelections()`, `clearRemoteMarkers()` |
| Status | `initialized`, `synced`, `status`, `onStatusChange()`, `onSynced()`, `getStats()` |
| Versions | `saveVersion()`, `getVersions()`, `getVersionById()`, `restoreVersion()`, `setStateFromVersion()` |
| Advanced | `getCollaborationPrimitives()`, `getDoc()`, `getText()`, `getYText()`, `getProvider()`, `getAwareness()`, `getUndoManager()`, `getEditor()`, `getStore()` |
### Exported Types and Helpers
* `AceEditorLike`, `AcePosition`, `AceSelectionRange`, `AceDelta`, `AceRangeFactory`
* `AceCursorData`, `AceAwarenessSelection`, `RemoteSelection`
* `CollaborationConfig`, `CollaborationPrimitives`, `CollaborationStats`, `BindEditorOptions`
* `normalizeText()`, `positionToIndex()`, `indexToPosition()`, `rangeToOffsets()`, `offsetsToRange()`
# Apryse WebViewer
Source: https://velt.dev/docs/realtime-collaboration/crdt/setup/apryse
Setup Multiplayer Collaboration for Apryse WebViewer.
The `@veltdev/apryse-crdt-react` and `@veltdev/apryse-crdt` libraries enable real-time collaborative annotations, XFDF state, form fields, selections, and cursors in Apryse WebViewer. The collaboration engine is built on [Yjs](https://docs.yjs.dev/) and the Velt SDK.
## Prerequisites
* Node.js (v14 or higher)
* An Apryse WebViewer license and deployed WebViewer assets
* A Velt account with an API key ([sign up](https://console.velt.dev/))
* React (v18 or higher) when using the React wrapper
* Optional: TypeScript for type safety
## Setup
### Step 1: Install Dependencies
> [tab] React / Next.js
>
> ```bash theme={null}
> npm install @veltdev/apryse-crdt-react @veltdev/apryse-crdt @veltdev/react @veltdev/types @pdftron/webviewer
> ```
> [tab] Other Frameworks
>
> ```bash theme={null}
> npm install @veltdev/apryse-crdt @pdftron/webviewer @veltdev/client
> ```
The React package provides lifecycle hooks and provider components. The base package owns annotation records, XFDF import/export, the Velt CRDT Store, awareness, and version management.
The collaboration package does not ship Apryse workers or UI assets. Deploy WebViewer's `lib` directory, configure its `path`, and supply a valid Apryse license for your environment. If your dependency graph exposes Yjs directly, ensure the final bundle resolves only one compatible `yjs` instance.
### Step 2: Load Apryse WebViewer
The application owns WebViewer creation. Create it once and keep the completed instance stable until collaboration has been destroyed.
> [tab] React / Next.js
>
> ```tsx theme={null}
> import WebViewer from '@pdftron/webviewer';
> import { useEffect, useRef, useState } from 'react';
> import type { ApryseWebViewerInstanceLike } from '@veltdev/apryse-crdt-react';
>
> const hostRef = useRef(null);
> const [instance, setInstance] = useState(null);
>
> useEffect(() => {
> if (!hostRef.current) return;
> let active = true;
>
> void WebViewer({
> path: '/webviewer/lib',
> licenseKey: 'YOUR_APRYSE_LICENSE_KEY',
> initialDoc: '/documents/contract.pdf',
> }, hostRef.current).then((nextInstance) => {
> if (!active) {
> nextInstance.UI?.dispose?.();
> return;
> }
> setInstance(nextInstance);
> });
>
> return () => {
> active = false;
> };
> }, []);
> ```
>
> Dispose WebViewer only after the collaboration manager has been destroyed, as shown in Cleanup and the complete example.
> [tab] Other Frameworks
>
> ```ts theme={null}
> import WebViewer from '@pdftron/webviewer';
>
> const host = document.querySelector('#apryse-viewer')!;
> const instance = await WebViewer({
> path: '/webviewer/lib',
> licenseKey: 'YOUR_APRYSE_LICENSE_KEY',
> initialDoc: '/documents/contract.pdf',
> }, host);
> ```
>
> The resolved `instance` must expose `Core.annotationManager` unless you pass `annotationManager` explicitly to the collaboration wrapper. The manager also uses `Core.documentViewer` when available, including to reapply shared state after Apryse emits `documentLoaded`.
### Step 3: Setup Velt
React applications initialize Velt at the app root while WebViewer loads. Other Frameworks integrations initialize Velt after the viewer is available. In both cases, authenticate the user and set a stable document before creating collaboration. Follow the [Velt Setup Docs](/docs/get-started/quickstart) for the production token endpoint used by `authProvider`.
> [tab] React / Next.js
>
> ```tsx theme={null}
> import { useEffect, useState } from 'react';
> import {
> VeltProvider,
> useCurrentUser,
> useSetDocuments,
> } from '@veltdev/react';
>
> const DOCUMENT_ID = 'apryse-contract-123';
> const USER = {
> userId: 'ada',
> name: 'Ada Lovelace',
> email: 'ada@example.com',
> organizationId: 'my-org-id',
> };
>
> const authProvider = {
> user: USER,
> retryConfig: { retryCount: 3, retryDelay: 1000 },
> generateToken: async () => {
> const response = await fetch('/api/velt/token', {
> method: 'POST',
> headers: { 'Content-Type': 'application/json' },
> body: JSON.stringify(USER),
> });
> const { token } = await response.json();
> return token;
> },
> };
>
> function DocumentScope() {
> const user = useCurrentUser();
> const { setDocuments } = useSetDocuments();
> const [documentReady, setDocumentReady] = useState(false);
>
> useEffect(() => {
> if (!user) {
> setDocumentReady(false);
> return;
> }
> setDocuments([{
> id: DOCUMENT_ID,
> metadata: { documentName: 'Contract review' },
> }]);
> setDocumentReady(true);
> }, [user, setDocuments]);
>
> return user && documentReady
> ?
> : Preparing collaboration...
;
> }
>
>
>
>
> ```
> [tab] Other Frameworks
>
> ```ts theme={null}
> import { initVelt } from '@veltdev/client';
>
> const DOCUMENT_ID = 'apryse-contract-123';
> const client = await initVelt('YOUR_API_KEY');
>
> await client.identify({
> userId: 'ada',
> name: 'Ada Lovelace',
> email: 'ada@example.com',
> organizationId: 'my-org-id',
> });
>
> await client.setDocument(DOCUMENT_ID, {
> documentName: 'Contract review',
> });
>
> let resolveVeltReady!: () => void;
> const veltReady = new Promise((resolve) => {
> resolveVeltReady = resolve;
> });
> const initSubscription = client.getVeltInitState().subscribe((isReady) => {
> if (isReady) resolveVeltReady();
> });
> await veltReady;
> initSubscription.unsubscribe();
> ```
### Step 4: Initialize Collaboration
> [tab] React Component
>
> Use `ApryseCrdtProvider` to share one hook result across a component tree. It manages collaboration around an existing WebViewer instance; it does not create or render WebViewer.
>
> ```tsx theme={null}
> import { ApryseCrdtProvider } from '@veltdev/apryse-crdt-react';
>
> editorId={DOCUMENT_ID}
> instance={instance}
> onManagerReady={(manager) => console.log(manager.getMap())}
> >
> {(collaboration) => (
> {collaboration.isSynced ? 'Synced' : collaboration.status}
> )}
>
> ```
>
> `ApryseCrdtViewer` and `ApryseCollaborationProvider` are aliases of this provider.
> [tab] React Hook
>
> `useApryseCrdt()` is the primary integration. `useCollaboration()` and `useApryseCollaboration()` are aliases.
>
> ```tsx theme={null}
> import { useApryseCrdt } from '@veltdev/apryse-crdt-react';
>
> const collaboration = useApryseCrdt({
> editorId: DOCUMENT_ID,
> instance,
> initialXfdf: ' ',
> cursorData: { name: 'Ada Lovelace', color: '#2563eb' },
> debounceMs: 125,
> onError: (error) => console.error('Collaboration error:', error),
> });
>
> return (
>
> {collaboration.isLoading ? 'loading' : collaboration.status}
>
>
> );
> ```
>
> The hook explicitly waits for Velt initialization, an authenticated user, a non-empty `editorId`, and an Apryse instance. Document context must already be set, but it is not an explicit hook wait condition.
> [tab] Other Frameworks
>
> ```ts theme={null}
> import WebViewer from '@pdftron/webviewer';
> import { initVelt } from '@veltdev/client';
> import { createCollaboration } from '@veltdev/apryse-crdt';
>
> const DOCUMENT_ID = 'apryse-contract-123';
> const host = document.querySelector('#apryse-viewer')!;
> const instance = await WebViewer({
> path: '/webviewer/lib',
> licenseKey: 'YOUR_APRYSE_LICENSE_KEY',
> initialDoc: '/documents/contract.pdf',
> }, host);
>
> const client = await initVelt('YOUR_API_KEY');
> await client.identify({
> userId: 'ada',
> name: 'Ada Lovelace',
> email: 'ada@example.com',
> organizationId: 'my-org-id',
> });
> await client.setDocument(DOCUMENT_ID, {
> documentName: 'Contract review',
> });
>
> let resolveVeltReady!: () => void;
> const veltReady = new Promise((resolve) => {
> resolveVeltReady = resolve;
> });
> const initSubscription = client.getVeltInitState().subscribe((isReady) => {
> if (isReady) resolveVeltReady();
> });
> await veltReady;
> initSubscription.unsubscribe();
>
> const manager = await createCollaboration({
> editorId: DOCUMENT_ID,
> veltClient: client,
> instance,
> initialXfdf: ' ',
> cursorData: { name: 'Ada', color: '#2563eb' },
> onError: (error) => console.error('Apryse collaboration:', error),
> });
>
> const offStatus = manager.onStatusChange(console.log);
> const offSynced = manager.onSynced(console.log);
> const offAnnotations = manager.onAnnotationsChange(console.log);
> const offCursors = manager.onRemoteCursorsChange(console.log);
>
> // Route or page teardown:
> offCursors();
> offAnnotations();
> offSynced();
> offStatus();
> manager.destroy();
> instance.UI?.dispose?.();
> ```
### Step 5: Synchronize Annotations and XFDF
Apryse annotation changes are captured automatically. Use XFDF helpers for imports, exports, and explicit snapshots:
> [tab] React / Next.js
>
> ```tsx theme={null}
> const currentXfdf = await collaboration.exportXfdf();
> await collaboration.setXfdf(importedXfdf);
> await collaboration.importXfdf(importedXfdf); // Alias of setXfdf
> await collaboration.flushAnnotationsToShared();
> ```
> [tab] Other Frameworks
>
> ```ts theme={null}
> const currentXfdf = await manager.exportXfdf();
> await manager.setXfdf(importedXfdf);
> await manager.importXfdf(importedXfdf); // Alias of setXfdf
> await manager.flushAnnotationsToShared();
> ```
`sharedState` contains the normalized annotation records currently stored in the CRDT map. Deleted annotations remain represented as tombstone records so concurrent changes merge consistently.
The manager listens to Apryse's public `annotationChanged` event for add, modify, and delete actions. It exports the affected annotation as XFDF and stores a normalized record containing its ID, action, page, author, timestamp, and XFDF. Remote records are combined and imported back into Apryse while imported-event echoes are suppressed.
When the annotation manager exposes `fieldChanged`, the manager writes a full XFDF snapshot so form values and field metadata remain together. The adapter does not synchronize arbitrary PDF binary mutations.
> [!NOTE]
>
> Apryse collaboration synchronizes annotations and XFDF state. The underlying PDF file remains an Apryse document input and is not uploaded through this CRDT adapter.
### Step 6: Status Monitoring (Optional)
> [tab] React / Next.js
>
> ```tsx theme={null}
> const { manager, status, isSynced, error } = collaboration;
>
> useEffect(() => {
> if (!manager) return;
>
> const offStatus = manager.onStatusChange(console.log);
> const offSynced = manager.onSynced(console.log);
>
> return () => {
> offStatus();
> offSynced();
> };
> }, [manager]);
> ```
>
> The provider also supports `onStatusChange`, `onSyncedChange`, `onAnnotationsChange`, and `onUpdateData` callbacks.
> [tab] Other Frameworks
>
> ```ts theme={null}
> console.log(manager.initialized, manager.status, manager.synced);
>
> const offStatus = manager.onStatusChange((status) => {
> console.log('Status:', status);
> });
> const offSynced = manager.onSynced((synced) => {
> console.log('Synced:', synced);
> });
> ```
>
> Keep both unsubscribe functions for teardown.
### Step 7: Version Management (Optional)
> [tab] React / Next.js
>
> ```tsx theme={null}
> const {
> versions,
> saveVersion,
> restoreVersion,
> refreshVersions,
> } = collaboration;
>
> const versionId = await saveVersion('Legal review complete');
> await refreshVersions();
> await restoreVersion(versionId);
> ```
> [tab] Other Frameworks
>
> ```ts theme={null}
> const versionId = await manager.saveVersion('Legal review complete');
> let versions = await manager.getVersions();
>
> await manager.restoreVersion(versionId);
> versions = await manager.getVersions();
> ```
`saveVersion()` flushes the current annotations before creating the checkpoint. Restoring a version updates the shared annotation map and reapplies the resulting XFDF to Apryse for every collaborator.
### Step 8: Force Reset Initial Content (Optional)
`initialContent` and `initialXfdf` accept XFDF for a brand-new shared annotation document:
> [tab] React / Next.js
>
> ```tsx theme={null}
> useApryseCrdt({
> editorId: DOCUMENT_ID,
> instance,
> initialXfdf,
> forceResetInitialContent: true,
> });
> ```
> [tab] Other Frameworks
>
> Add the same options to the manager creation call:
>
> ```ts theme={null}
> const manager = await createCollaboration({
> editorId: DOCUMENT_ID,
> veltClient: client,
> instance,
> initialXfdf,
> forceResetInitialContent: true,
> });
> ```
Without `forceResetInitialContent`, existing persisted annotation records win on reconnect and the XFDF seed is used only for a new, empty collaborative document. `initialContent` is an alias for XFDF input; it is not plain PDF text or PDF bytes.
> [!WARNING]
>
> `forceResetInitialContent` replaces the existing shared annotation state. Enable it only for deliberate reset or fixture workflows.
### Step 9: Publish Remote Cursors (Optional)
Apryse page coordinates are awareness state rather than persisted annotations. Publish them from your viewer interaction layer:
> [tab] React / Next.js
>
> ```tsx theme={null}
> collaboration.updateCursor({
> pageNumber: 1,
> x: 240,
> y: 360,
> selectionText: 'Payment terms',
> selection: { x: 220, y: 345, width: 180, height: 24 },
> });
>
> // When the pointer leaves the document
> collaboration.clearCursor();
> ```
>
> Render custom cursor overlays from the reactive `remoteCursors` array:
>
> ```tsx theme={null}
> {collaboration.remoteCursors.map((cursor) => (
>
> {cursor.name} · page {cursor.pageNumber}
>
> ))}
> ```
> [tab] Other Frameworks
>
> ```ts theme={null}
> manager.updateCursor({
> pageNumber: 1,
> x: 240,
> y: 360,
> selectionText: 'Payment terms',
> selection: { x: 220, y: 345, width: 180, height: 24 },
> });
>
> const offCursors = manager.onRemoteCursorsChange((remoteCursors) => {
> renderApryseCursors(remoteCursors);
> });
>
> // When the pointer leaves the document:
> manager.clearCursor();
> ```
Your Apryse integration is responsible for converting screen coordinates into page coordinates and positioning the overlay in the current viewport.
Mount remote cursor elements in an Apryse page overlay that moves with the active page. Apply the current zoom, scroll, and page transform when converting the stored page-space coordinates to CSS pixels:
```css theme={null}
.app-apryse-cursor-layer {
inset: 0;
pointer-events: none;
position: absolute;
z-index: 30;
}
.app-apryse-remote-cursor {
border-left: 2px solid currentColor;
min-height: 18px;
position: absolute;
}
.app-apryse-remote-cursor-label {
background: currentColor;
border-radius: 4px;
color: white;
font-size: 12px;
left: -2px;
padding: 2px 6px;
position: absolute;
top: -22px;
white-space: nowrap;
}
.app-apryse-remote-selection {
border: 2px solid currentColor;
opacity: 0.2;
position: absolute;
}
```
These class names are application-owned. The source demo uses `.cursor-layer`, `.apryse-remote-cursor`, and `.apryse-remote-cursor-label`; either naming scheme works as long as the renderer and CSS agree.
Awareness is ephemeral: cursor and selection records disappear when a peer disconnects and are not included in XFDF or saved versions. Throttle pointer updates in high-frequency interactions.
### Step 10: CRDT Event Subscription (Optional)
Subscribe through the manager for normalized Apryse update events:
> [tab] React / Next.js
>
> ```tsx theme={null}
> useEffect(() => {
> if (!collaboration.manager) return;
> return collaboration.manager.onUpdateData((event) => {
> console.log('Apryse CRDT update:', event);
> });
> }, [collaboration.manager]);
> ```
> [tab] Other Frameworks
>
> ```ts theme={null}
> const offUpdateData = manager.onUpdateData((event) => {
> console.log('Apryse CRDT update:', event);
> });
>
> const crdtSubscription = client
> .getCrdtElement()
> .on('updateData')
> .subscribe((event) => {
> if (event) console.log('Application CRDT update:', event);
> });
> ```
For application-wide Velt CRDT events:
```tsx theme={null}
import { useEffect } from 'react';
import { useVeltClient } from '@veltdev/react';
const { client } = useVeltClient();
useEffect(() => {
if (!client) return;
const subscription = client.getCrdtElement().on('updateData').subscribe((event) => {
if (event) console.log('CRDT update:', event);
});
return () => subscription?.unsubscribe?.();
}, [client]);
```
### Step 11: Custom Encryption (Optional)
> [tab] React / Next.js
>
> ```tsx theme={null}
> const encryptionProvider = {
> encrypt: async ({ data }) => data.map((n) => n.toString()).join('__'),
> decrypt: async ({ data }) => data.split('__').map((s) => parseInt(s, 10)),
> };
>
> apiKey="YOUR_API_KEY"
> authProvider={authProvider}
> encryptionProvider={encryptionProvider}
> >
> ...
>
> ```
> [tab] Other Frameworks
>
> Configure encryption before creating the collaboration manager:
>
> ```ts theme={null}
> client.setEncryptionProvider({
> encrypt: async ({ data }) => data.map((n) => n.toString()).join('__'),
> decrypt: async ({ data }) => data.split('__').map((s) => parseInt(s, 10)),
> });
> ```
See also: [setEncryptionProvider()](/docs/api-reference/sdk/api/api-methods#setencryptionprovider-encryptionprovider)
· [VeltEncryptionProvider](/docs/api-reference/sdk/models/data-models#veltencryptionprovider)
### Step 12: Error Handling (Optional)
> [tab] React / Next.js
>
> ```tsx theme={null}
> const collaboration = useApryseCrdt({
> editorId: DOCUMENT_ID,
> instance,
> onError: (error) => console.error('Apryse collaboration:', error),
> });
>
> if (collaboration.error) {
> return Error: {collaboration.error.message}
;
> }
> ```
> [tab] Other Frameworks
>
> ```ts theme={null}
> const manager = await createCollaboration({
> editorId: DOCUMENT_ID,
> veltClient: client,
> instance,
> onError: (error) => {
> console.error('Apryse collaboration:', error);
> },
> });
>
> if (!manager.getMap()) {
> manager.destroy();
> instance.UI?.dispose?.();
> throw new Error('Apryse collaboration did not initialize');
> }
> ```
Public wrapper and manager methods catch integration errors and return safe fallback values.
### Step 13: Access Yjs Internals (Advanced)
> [tab] React / Next.js
>
> ```tsx theme={null}
> const { primitives } = collaboration;
>
> const viewer = primitives?.instance;
> const annotationManager = primitives?.annotationManager;
> const documentViewer = primitives?.documentViewer;
> const doc = primitives?.doc;
> const map = primitives?.map;
> const annotationsMap = primitives?.annotationsMap;
> const xmlFragment = primitives?.xmlFragment;
> const provider = primitives?.provider;
> const awareness = primitives?.awareness;
> const store = primitives?.store;
> ```
> [tab] Other Frameworks
>
> ```ts theme={null}
> const doc = manager.getDoc();
> const map = manager.getMap();
> const annotationsMap = manager.getAnnotationsMap();
> const xmlFragment = manager.getXmlFragment();
> const provider = manager.getProvider();
> const awareness = manager.getAwareness();
> const store = manager.getStore();
> ```
The manager owns these Yjs and provider objects. Do not construct a second document, provider, or awareness instance, and prefer the XFDF/annotation methods over direct shared-type mutation.
Internally, Apryse uses a map Store with `contentKey: 'apryse'` and `source: 'apryse'`. `getXmlFragment()` is a compatibility view for generic XML-based harnesses, and direct inserts into it are translated into Apryse XFDF annotation records. Application code should normally use `getMap()`, `getAnnotationsMap()`, and the XFDF helpers.
### Step 14: Cleanup
> [tab] React / Next.js
>
> The hook and provider destroy the collaboration manager automatically. Call `destroy()` before disposing an application-owned WebViewer when you need to guarantee teardown order:
>
> ```tsx theme={null}
> useEffect(() => {
> return () => {
> collaboration.destroy();
> viewerRef.current?.UI?.dispose?.();
> viewerRef.current = null;
> };
> }, [collaboration.destroy]);
> ```
> [tab] Other Frameworks
>
> Remove every callback before destroying the manager. Dispose WebViewer only after the manager has released Apryse listeners:
>
> ```ts theme={null}
> crdtSubscription.unsubscribe();
> offUpdateData();
> offCursors();
> offAnnotations();
> offSynced();
> offStatus();
>
> manager.destroy();
> instance.UI?.dispose?.();
> ```
## Notes
* **Annotation scope**: The adapter synchronizes annotation/XFDF state, not PDF file bytes.
* **Stable instance**: Create WebViewer once per mount and pass the same instance to the hook.
* **Data model**: Individual annotation records live in a Yjs map, with XFDF snapshots used for Apryse import/export.
* **Cursor ownership**: The adapter publishes cursor awareness, while the application maps Apryse page coordinates to overlay DOM.
* **Unique editorId**: Collaborators must share the same Velt document context and `editorId`.
* **React readiness**: The hook checks Velt initialization, an authenticated user, a non-empty editor ID, and an Apryse instance. It does not explicitly wait for document context.
* **Viewer ownership**: The application loads PDFs, owns WebViewer assets and licensing, and disposes the viewer after collaboration is destroyed.
* **Form fields**: When Apryse emits `fieldChanged`, the manager captures a full XFDF snapshot to retain field metadata and values.
* **Initial XFDF**: Seed data is applied once unless force reset is explicitly enabled.
* **Security and performance**: XFDF can contain user-generated content. Sanitize custom renderers, throttle cursor updates, tune `debounceMs`, and test realistic annotation volumes.
* **Production authentication**: Use `VeltProvider` with a server-backed `authProvider`; never expose privileged server tokens in browser code.
## Testing and Debugging
**To test collaboration:**
1. Open the same PDF, Velt document, and Apryse `editorId` as two different users.
2. Add, modify, and delete annotations in both clients.
3. Verify XFDF imports, remote cursor awareness, version restore, and persistence after reload.
4. Test concurrent changes to separate annotations and to the same annotation.
**Common issues:**
* Viewer not loading: Confirm `/webviewer/lib` contains the deployed Apryse assets and the license is valid.
* Manager remains loading: Confirm the document context was set first, Velt is initialized, a user is authenticated, the editor ID is non-empty, and `instance` is non-null. Document context is a prerequisite, not an explicit hook wait condition.
* Annotations do not sync: Confirm both clients use the same Velt document and `editorId`.
* Cursor position is incorrect: Convert pointer and selection positions to Apryse page coordinates before calling `updateCursor()`.
* Existing annotations reset: Disable `forceResetInitialContent` during normal loads.
> [!TIP]
>
> Use the [VeltCrdtStoreMap debugging interface](/docs/realtime-collaboration/crdt/setup/core#veltcrdtstoremap) to inspect annotation records and provider state.
## Complete Example
> [tab] React / Next.js
>
> ```tsx Complete App.tsx expandable lines theme={null}
> import { useEffect, useMemo, useRef, useState } from 'react';
> import WebViewer from '@pdftron/webviewer';
> import {
> VeltProvider,
> useCurrentUser,
> useSetDocuments,
> } from '@veltdev/react';
> import {
> useApryseCrdt,
> type ApryseWebViewerInstanceLike,
> } from '@veltdev/apryse-crdt-react';
>
> const DOCUMENT_ID = 'apryse-contract-123';
> const USER = {
> userId: 'ada',
> organizationId: 'my-org-id',
> name: 'Ada Lovelace',
> email: 'ada@example.com',
> };
>
> function ApryseDocument() {
> const hostRef = useRef(null);
> const viewerRef = useRef(null);
> const user = useCurrentUser();
> const [instance, setInstance] = useState(null);
> const [versionName, setVersionName] = useState('');
> const [documentReady, setDocumentReady] = useState(false);
> const { setDocuments } = useSetDocuments();
>
> useEffect(() => {
> if (!user) {
> setDocumentReady(false);
> return;
> }
> setDocuments([{
> id: DOCUMENT_ID,
> metadata: { documentName: 'Contract review' },
> }]);
> setDocumentReady(true);
> }, [user, setDocuments]);
>
> useEffect(() => {
> if (!hostRef.current) return;
> let active = true;
>
> void WebViewer({
> path: '/webviewer/lib',
> licenseKey: 'YOUR_APRYSE_LICENSE_KEY',
> initialDoc: '/documents/contract.pdf',
> }, hostRef.current).then((nextInstance) => {
> if (!active) {
> nextInstance.UI?.dispose?.();
> return;
> }
> viewerRef.current = nextInstance;
> setInstance(nextInstance);
> });
>
> return () => {
> active = false;
> };
> }, []);
>
> const collaboration = useApryseCrdt({
> editorId: DOCUMENT_ID,
> instance,
> enabled: Boolean(user && documentReady),
> initialXfdf: ' ',
> cursorData: { name: user?.name, color: '#2563eb' },
> onError: console.error,
> });
>
> useEffect(() => {
> return () => {
> collaboration.destroy();
> viewerRef.current?.UI?.dispose?.();
> viewerRef.current = null;
> };
> }, [collaboration.destroy]);
>
> const saveVersion = async () => {
> if (!versionName.trim()) return;
> await collaboration.saveVersion(versionName.trim());
> setVersionName('');
> };
>
> return (
>
> Status: {collaboration.status} | Synced: {collaboration.isSynced ? 'Yes' : 'No'}
> setVersionName(event.target.value)} />
> Save version
>
>
> );
> }
>
> export default function App() {
> const authProvider = useMemo(() => ({
> user: USER,
> retryConfig: { retryCount: 3, retryDelay: 1000 },
> generateToken: async () => {
> const response = await fetch('/api/velt/token', {
> method: 'POST',
> headers: { 'Content-Type': 'application/json' },
> body: JSON.stringify(USER),
> });
> const { token } = await response.json();
> return token;
> },
> }), []);
>
> return (
>
>
>
> );
> }
> ```
>
> ```css Complete styles.css expandable lines theme={null}
> .apryse-host {
> width: 100%;
> height: 720px;
> min-height: 520px;
> }
> ```
> [tab] Other Frameworks
>
> ```html Complete index.html expandable lines theme={null}
>
> Status: connecting
> Synced: No
> ```
>
> ```ts Complete app.ts expandable lines theme={null}
> import WebViewer from '@pdftron/webviewer';
> import { initVelt } from '@veltdev/client';
> import {
> createCollaboration,
> type ApryseRemoteCursor,
> type CollaborationManager,
> } from '@veltdev/apryse-crdt';
> import './styles.css';
>
> const DOCUMENT_ID = 'apryse-contract-123';
>
> function renderApryseCursors(cursors: ApryseRemoteCursor[]) {
> const layer = document.querySelector('#apryse-cursor-layer')!;
> layer.replaceChildren();
>
> for (const cursor of cursors) {
> // This assumes the layer already uses Apryse page-space coordinates.
> // Apply WebViewer's current page, zoom, and scroll transform here when it does not.
> const marker = document.createElement('div');
> marker.className = 'app-apryse-remote-cursor';
> marker.style.color = cursor.color;
> marker.style.left = `${cursor.x}px`;
> marker.style.top = `${cursor.y}px`;
>
> const label = document.createElement('span');
> label.className = 'app-apryse-remote-cursor-label';
> label.textContent = `${cursor.name} · page ${cursor.pageNumber}`;
> marker.appendChild(label);
> layer.appendChild(marker);
>
> if (cursor.selection) {
> const selection = document.createElement('div');
> selection.className = 'app-apryse-remote-selection';
> selection.style.color = cursor.color;
> selection.style.left = `${cursor.selection.x}px`;
> selection.style.top = `${cursor.selection.y}px`;
> selection.style.width = `${cursor.selection.width}px`;
> selection.style.height = `${cursor.selection.height}px`;
> layer.appendChild(selection);
> }
> }
> }
>
> const host = document.querySelector('#apryse-viewer')!;
> const instance = await WebViewer({
> path: '/webviewer/lib',
> licenseKey: 'YOUR_APRYSE_LICENSE_KEY',
> initialDoc: '/documents/contract.pdf',
> }, host);
>
> const client = await initVelt('YOUR_VELT_API_KEY');
> await client.identify({
> userId: 'ada',
> name: 'Ada Lovelace',
> email: 'ada@example.com',
> organizationId: 'my-org-id',
> });
> await client.setDocument(DOCUMENT_ID, {
> documentName: 'Contract review',
> });
>
> let resolveVeltReady!: () => void;
> const veltReady = new Promise((resolve) => {
> resolveVeltReady = resolve;
> });
> const initSubscription = client.getVeltInitState().subscribe((isReady) => {
> if (isReady) resolveVeltReady();
> });
> await veltReady;
> initSubscription.unsubscribe();
>
> const manager: CollaborationManager = await createCollaboration({
> editorId: DOCUMENT_ID,
> veltClient: client,
> instance,
> initialXfdf: ' ',
> cursorData: { name: 'Ada Lovelace', color: '#2563eb' },
> debounceMs: 125,
> onError: (error) => console.error('Apryse collaboration:', error),
> });
>
> const offStatus = manager.onStatusChange((status) => {
> document.querySelector('#status')!.textContent = status;
> });
> const offSynced = manager.onSynced((synced) => {
> document.querySelector('#synced')!.textContent = synced ? 'Yes' : 'No';
> });
> const offAnnotations = manager.onAnnotationsChange((state) => {
> console.log('Annotation records:', Object.keys(state).length);
> });
> const offCursors = manager.onRemoteCursorsChange(renderApryseCursors);
> renderApryseCursors(manager.getRemoteCursors());
> const offUpdateData = manager.onUpdateData((event) => {
> console.log('Apryse update:', event);
> });
> const crdtSubscription = client
> .getCrdtElement()
> .on('updateData')
> .subscribe((event) => {
> if (event) console.log('Application CRDT update:', event);
> });
>
> manager.updateCursor({
> pageNumber: 1,
> x: 240,
> y: 360,
> selection: { x: 220, y: 345, width: 180, height: 24 },
> });
>
> const versionId = await manager.saveVersion('Legal review complete');
> console.log('Saved version:', versionId, await manager.getVersions());
>
> window.addEventListener('beforeunload', () => {
> crdtSubscription.unsubscribe();
> offUpdateData();
> offCursors();
> offAnnotations();
> offSynced();
> offStatus();
>
> manager.destroy();
> instance.UI?.dispose?.();
> });
> ```
>
> ```css Complete styles.css expandable lines theme={null}
> .apryse-shell {
> height: 720px;
> min-height: 520px;
> position: relative;
> width: 100%;
> }
>
> .apryse-host {
> height: 100%;
> width: 100%;
> }
>
> .app-apryse-cursor-layer {
> inset: 0;
> pointer-events: none;
> position: absolute;
> z-index: 30;
> }
>
> .app-apryse-remote-cursor {
> border-left: 2px solid currentColor;
> min-height: 18px;
> position: absolute;
> }
>
> .app-apryse-remote-cursor-label {
> background: currentColor;
> border-radius: 4px;
> color: white;
> font-size: 12px;
> left: -2px;
> padding: 2px 6px;
> position: absolute;
> top: -22px;
> white-space: nowrap;
> }
>
> .app-apryse-remote-selection {
> border: 2px solid currentColor;
> opacity: 0.2;
> position: absolute;
> }
> ```
## How It Works
1. The application loads Apryse assets, initializes WebViewer, and retains the completed instance.
2. React uses an authenticated `VeltProvider`; other frameworks initialize one Velt client, authenticate the user, and set the document before creating collaboration.
3. The React hook checks Velt initialization, an authenticated user, a non-empty editor ID, and an Apryse instance. It does not explicitly wait for document context.
4. The base manager stores normalized annotation records in a Velt-backed Yjs map. Apryse `annotationChanged` events create XFDF records and deletion tombstones; `fieldChanged` schedules a full XFDF snapshot.
5. Remote records are rebuilt as XFDF and imported into the viewer with echo suppression.
6. Awareness carries transient page coordinates, selections, and cursor identity, while versions save and restore the persistent annotation state.
## APIs
### React: useApryseCrdt()
| Config | Type | Description |
| - | - | - |
| `editorId` | `string` | Stable collaborative annotation ID. |
| `instance` | `ApryseWebViewerInstanceLike \| null` | Existing WebViewer instance. |
| `veltClient` | `Velt` | Optional context override. |
| `initialContent` / `initialXfdf` | `string` | First-load XFDF seed. |
| `cursorData` | `ApryseCursorData` | Cursor label and colors. |
| `debounceMs` | `number` | Debounces annotation and XFDF writes to the CRDT Store. |
| `forceResetInitialContent` | `boolean` | Replaces shared annotations on initialization. |
| `enabled` | `boolean` | Delays or disables manager creation. |
| `onError` | `(error: Error) => void` | Receives non-fatal errors. |
| Return | Description |
| - | - |
| `instanceRef()` / `setInstance()` | Captures a viewer created later. |
| `manager`, `primitives`, `sharedState` | Manager and shared state access. |
| `status`, `synced`, `isSynced`, `isLoading`, `error` | Reactive lifecycle state. |
| `versions`, `saveVersion()`, `restoreVersion()`, `refreshVersions()` | Version management. |
| `remoteCursors`, `updateCursor()`, `clearCursor()` | Awareness cursor APIs. |
| `exportXfdf()`, `setXfdf()`, `importXfdf()` | XFDF APIs. |
| `flushAnnotationsToShared()` | Writes a full annotation snapshot. |
| `destroy()` | Ends collaboration early. |
### React: ApryseCrdtProvider
Accepts the hook configuration plus callbacks for manager readiness, status, sync, cursors, annotations, update events, and versions. Children can be a React node or render function.
### Other Frameworks: createCollaboration()
```ts theme={null}
import { createCollaboration } from '@veltdev/apryse-crdt';
const manager = await createCollaboration({
editorId: DOCUMENT_ID,
veltClient: client,
instance,
initialXfdf: ' ',
cursorData: { name: 'Ada', color: '#2563eb' },
debounceMs: 125,
onError: console.error,
});
```
Create WebViewer first, then initialize and authenticate Velt, set the document, and call this factory with the completed instance.
| Config | Type | Required | Description |
| - | - | - | - |
| `editorId` | `string` | Yes | Stable annotation document ID shared by collaborators. |
| `veltClient` | `Velt` | Yes | Initialized, authenticated client with a current document. |
| `instance` | `ApryseWebViewerInstanceLike` | Yes | Completed, application-owned WebViewer instance. |
| `annotationManager` | `ApryseAnnotationManagerLike` | No | Overrides `instance.Core.annotationManager` for custom wrappers. |
| `documentViewer` | `ApryseDocumentViewerLike` | No | Overrides `instance.Core.documentViewer`. |
| `initialContent` / `initialXfdf` | `string` | No | XFDF seed for a new, empty shared annotation state. |
| `forceResetInitialContent` | `boolean` | No | Explicitly replaces existing shared annotations. |
| `cursorData` | `ApryseCursorData` | No | Awareness identity and colors. |
| `debounceMs` | `number` | No | Debounces annotation and XFDF writes to the CRDT Store. |
| `onError` | `(error: Error) => void` | No | Receives non-fatal integration errors. |
### CollaborationManager Methods
| Method or property | Description |
| - | - |
| `initialize()` / `destroy()` | Starts or destroys collaboration. |
| `initialized`, `synced`, `status` | Manager state. |
| `getDoc()`, `getMap()`, `getAnnotationsMap()`, `getXmlFragment()` | Yjs data access. |
| `getProvider()`, `getAwareness()`, `getStore()` | Provider and Store access. |
| `getSharedState()` | Reads normalized annotation records. |
| `exportXfdf()`, `setXfdf()`, `importXfdf()` | Reads or replaces XFDF. |
| `flushAnnotationsToShared()` | Captures current Apryse annotations. |
| `updateCursor()`, `clearCursor()`, `getRemoteCursors()` | Awareness cursor methods. |
| `onAnnotationsChange()`, `onRemoteCursorsChange()`, `onUpdateData()` | Data subscriptions. |
| `onStatusChange()`, `onSynced()`, `onVersionsInvalidated()` | Lifecycle subscriptions. |
| `saveVersion()`, `getVersions()`, `restoreVersion()` | Version methods. |
| `setStateFromVersion()` | Applies a supplied version object. |
### Exported Types and Helpers
* `UseApryseCrdtConfig`, `ApryseCrdtHookResult`, `ApryseCrdtProviderProps`
* `ApryseWebViewerInstanceLike`, `ApryseAnnotationManagerLike`, `ApryseDocumentViewerLike`
* `ApryseAnnotationRecord`, `ApryseSharedState`, `ApryseCursorData`, `ApryseCursorState`, `ApryseRemoteCursor`
* `CrdtUpdateDataEvent`, `SyncStatus`, `Unsubscribe`, `Version`
* `normalizeXfdf()`, `buildXfdf()`, `createAnnotationRecord()`, `recordsFromState()`
* `getAnnotationId()`, `hasSharedAnnotations()`, `SNAPSHOT_RECORD_ID`
# BlockNote Editor
Source: https://velt.dev/docs/realtime-collaboration/crdt/setup/blocknote
Setup Multiplayer Editing for BlockNote Editor.
The `@veltdev/blocknote-crdt-react` and `@veltdev/blocknote-crdt` libraries enable real-time collaborative editing on BlockNote Editors. The collaboration editing engine is built on top of [Yjs](https://docs.yjs.dev/) and Velt SDK.
## Prerequisites
* Node.js (v14 or higher)
* React (v16.8 or higher for hooks)
* A Velt account with an API key ([sign up](https://console.velt.dev/))
* Optional: TypeScript for type safety
## Setup
### Step 1: Install Dependencies
Install the required packages:
> [tab] React / Next.js
>
> ```bash theme={null}
> npm install @veltdev/blocknote-crdt-react @veltdev/blocknote-crdt @veltdev/react @veltdev/types @blocknote/core @blocknote/react @blocknote/mantine yjs
> ```
> [tab] Other Frameworks
>
> ```bash theme={null}
> npm install @veltdev/blocknote-crdt @veltdev/client @blocknote/core yjs
> ```
### Step 2: Setup Velt
Initialize the Velt client by following the [Velt Setup Docs](/docs/get-started/quickstart). This is required for the collaboration engine to work.
### Step 3: Initialize Collaborative Editor
* Initialize the collaboration manager and use it to create the BlockNote editor.
* Pass an `editorId` to uniquely identify each editor instance you have in your app. This is especially important when you have multiple editors in your app.
> [tab] React / Next.js
>
> Use the `useCollaboration` hook to manage the entire CRDT lifecycle. It creates a `CollaborationManager`, initializes the CRDT store, and returns a `BlockNoteCollaborationConfig`. You pass this config to `useCreateBlockNote({ collaboration: ... })` when creating your BlockNote editor.
>
> ```tsx theme={null}
> import { useCollaboration } from '@veltdev/blocknote-crdt-react';
> import { useCreateBlockNote } from '@blocknote/react';
> import { BlockNoteView } from '@blocknote/mantine';
> import '@blocknote/mantine/style.css';
>
> function BlockNoteEditorComponent() {
> const {
> collaborationConfig,
> isLoading,
> isSynced,
> status,
> error,
> manager,
> saveVersion,
> getVersions,
> restoreVersion,
> } = useCollaboration({
> editorId: 'my-blocknote-editor',
> onError: (err) => console.error('Collaboration error:', err),
> });
>
> const editor = useCreateBlockNote(
> collaborationConfig
> ? { collaboration: collaborationConfig }
> : {},
> [collaborationConfig],
> );
>
> if (error) return Error: {error.message}
;
> if (isLoading || !collaborationConfig) return Connecting...
;
>
> return ;
> }
> ```
>
> > [!NOTE]
> >
> > When the `collaboration` config is provided, BlockNote automatically uses the Y.XmlFragment as the document source, enables remote cursor rendering, and switches undo/redo to Yjs UndoManager. No additional configuration is needed.
> [tab] Other Frameworks
>
> Use `createCollaboration()` to create a `CollaborationManager`, then call `manager.getCollaborationConfig()` to get the config object for BlockNote. Pass this to `BlockNoteEditor.create({ collaboration: ... })`.
>
> ```js theme={null}
> import { createCollaboration } from '@veltdev/blocknote-crdt';
> import { BlockNoteEditor } from '@blocknote/core';
>
> // Wait for the SDK to be ready
> client.getVeltInitState().subscribe(async (isReady) => {
> if (!isReady) return;
>
> // Create the CollaborationManager
> const manager = await createCollaboration({
> editorId: 'my-blocknote-editor',
> veltClient: client,
> initialContent: [
> { type: 'paragraph', content: 'Welcome to the collaborative editor!' },
> ],
> onError: (error) => console.error('Collaboration error:', error),
> });
>
> // Get the collaboration config for BlockNote
> const collabConfig = manager.getCollaborationConfig();
>
> // Create the BlockNote editor
> const editor = BlockNoteEditor.create({
> collaboration: collabConfig,
> });
>
> editor.mount(document.getElementById('editor'));
> });
> ```
>
> > [!NOTE]
> >
> > `initialContent` is applied exactly once — only when the document is brand new (empty). On subsequent loads, the persisted content is used instead.
>
> > [!NOTE]
> >
> > When the `collaboration` config is provided, BlockNote automatically uses the Y.XmlFragment as the document source, enables remote cursor rendering, and switches undo/redo to Yjs UndoManager.
### Step 4: Status Monitoring (Optional)
Monitor the connection status and sync state to display UI indicators.
> [tab] React / Next.js
>
> The `useCollaboration` hook returns reactive `status`, `isSynced`, and `error` state:
>
> ```tsx theme={null}
> const { collaborationConfig, isLoading, isSynced, status, error } = useCollaboration({
> editorId: 'my-blocknote-editor',
> });
>
> if (error) return Error: {error.message}
;
> if (isLoading) return Connecting...
;
>
> // In your JSX
> Status: {status} | Synced: {isSynced ? 'Yes' : 'No'}
> ```
> [tab] Other Frameworks
>
> Subscribe to status and sync changes on the `manager`:
>
> ```js theme={null}
> // Connection status: 'connecting' | 'connected' | 'disconnected'
> manager.onStatusChange((status) => {
> console.log('Status:', status);
> });
>
> // Sync state: true when initial sync is complete
> manager.onSynced((synced) => {
> console.log('Synced:', synced);
> });
>
> // Read current values at any time
> console.log(manager.status); // 'connected'
> console.log(manager.synced); // true
> console.log(manager.initialized); // true
> ```
### Step 5: Version Management (Optional)
Save and restore named snapshots of the document state.
> [tab] React / Next.js
>
> Version methods are returned directly from `useCollaboration` as first-class APIs:
>
> ```tsx theme={null}
> // Save a version
> const versionId = await saveVersion('Before major edit');
>
> // List all versions
> const versions = await getVersions();
>
> // Restore a specific version
> await restoreVersion(versions[0].versionId);
> ```
> [tab] Other Frameworks
>
> ```js theme={null}
> // Save a named snapshot
> const versionId = await manager.saveVersion('Draft v1');
>
> // List all saved versions
> const versions = await manager.getVersions();
> // Returns: [{ versionId, versionName, timestamp }, ...]
>
> // Restore to a saved version
> await manager.restoreVersion(versionId);
> ```
### Step 6: Force Reset Initial Content (Optional)
By default, `initialContent` is applied exactly once — only when the document is brand new. Pass `forceResetInitialContent: true` to always overwrite remote data with `initialContent` on initialization.
> [!WARNING]
>
> `forceResetInitialContent` wipes all existing content every time the page loads with this flag. Do not use it in production user flows — it is intended for development and admin use only.
> [tab] React / Next.js
>
> ```tsx theme={null}
> const collab = useCollaboration({
> editorId: 'my-blocknote-editor',
> initialContent: [{ type: 'paragraph', content: 'Fresh start!' }],
> forceResetInitialContent: true,
> });
> ```
> [tab] Other Frameworks
>
> ```js theme={null}
> const manager = await createCollaboration({
> editorId: 'my-blocknote-editor',
> veltClient: client,
> initialContent: [{ type: 'paragraph', content: 'Fresh start' }],
> forceResetInitialContent: true,
> });
> ```
### Step 7: CRDT Event Subscription (Optional)
Listen for real-time sync events using `getCrdtElement().on()` from the Velt client.
> [tab] React / Next.js
>
> ```tsx theme={null}
> import { useVeltClient } from '@veltdev/react';
>
> const { client } = useVeltClient();
>
> useEffect(() => {
> if (!client) return;
> const crdtElement = client.getCrdtElement();
> const sub = crdtElement.on('updateData').subscribe((event) => {
> if (event) console.log('CRDT update:', event);
> });
> return () => sub?.unsubscribe?.();
> }, [client]);
> ```
> [tab] Other Frameworks
>
> ```js theme={null}
> const crdtElement = client.getCrdtElement();
>
> crdtElement.on('updateData').subscribe((event) => {
> if (event) {
> console.log('CRDT data updated:', event);
> }
> });
> ```
### Step 8: Custom Encryption (Optional)
Encrypt CRDT data before it's stored in Velt by registering a custom encryption provider. For CRDT methods, input data is of type `Uint8Array | number[]`.
> [tab] React / Next.js
>
> ```ts theme={null}
> const encryptionProvider = {
> encrypt: async ({ data }) => data.map((n) => n.toString()).join('__'),
> decrypt: async ({ data }) => data.split('__').map((s) => parseInt(s, 10)),
> };
>
>
> ...
>
> ```
> [tab] Other Frameworks
>
> ```js theme={null}
> const encryptionProvider = {
> encrypt: async (config) => {
> return config.data.map((num) => num.toString()).join('__');
> },
> decrypt: async (config) => {
> return config.data.split('__').map((str) => parseInt(str, 10));
> },
> };
>
> client.setEncryptionProvider(encryptionProvider);
> ```
See also: [setEncryptionProvider()](/docs/api-reference/sdk/api/api-methods#setencryptionprovider-encryptionprovider)
· [VeltEncryptionProvider](/docs/api-reference/sdk/models/data-models#veltencryptionprovider)
· [EncryptConfig](/docs/api-reference/sdk/models/data-models#encryptconfig)
· [DecryptConfig](/docs/api-reference/sdk/models/data-models#decryptconfig)
### Step 9: Error Handling (Optional)
> [tab] React / Next.js
>
> Pass an `onError` callback to handle initialization or runtime errors. The `error` reactive state is also available for rendering.
>
> ```tsx theme={null}
> const collab = useCollaboration({
> editorId: 'my-blocknote-editor',
> onError: (error) => console.error('Collaboration error:', error),
> });
>
> if (collab.error) {
> return Error: {collab.error.message}
;
> }
> ```
> [tab] Other Frameworks
>
> Pass an `onError` callback when creating the CollaborationManager:
>
> ```js theme={null}
> const manager = await createCollaboration({
> editorId: 'my-blocknote-editor',
> veltClient: client,
> onError: (error) => console.error('Collaboration error:', error),
> });
> ```
### Step 10: Access Yjs Internals (Advanced)
The manager exposes escape hatches for direct Yjs manipulation when needed.
> [tab] React / Next.js
>
> ```tsx theme={null}
> // From the manager returned by useCollaboration
> const doc = manager.getDoc();
> const xml = manager.getXmlFragment();
> const awareness = manager.getAwareness();
> const provider = manager.getProvider();
> const store = manager.getStore();
> ```
> [tab] Other Frameworks
>
> ```js theme={null}
> import * as Y from 'yjs';
>
> const doc = manager.getDoc();
> const xml = manager.getXmlFragment();
> const provider = manager.getProvider();
> const awareness = manager.getAwareness();
> const store = manager.getStore();
> ```
### Step 11: Cleanup
Cleanup is handled by calling `manager.destroy()`, which cascades to the store, provider, and all listeners. Safe to call multiple times.
> [tab] React / Next.js
>
> ```tsx theme={null}
> // Automatic on component unmount via useEffect cleanup
> // Or manually:
> manager.destroy();
> ```
> [tab] Other Frameworks
>
> ```js theme={null}
> manager.destroy();
> ```
## Notes
* **Unique editorId**: Use a unique `editorId` per editor instance.
* **Pass collaborationConfig**: Provide the `collaboration` config from `useCollaboration` (React) or `manager.getCollaborationConfig()` (non-React) to the BlockNote editor.
* **Undo/redo**: Automatically switches to Yjs UndoManager when collaboration is enabled.
## Testing and Debugging
**To test collaboration:**
1. Login two unique users on two browser profiles and open the same page in both.
2. Edit in one window and verify changes and cursors appear in the other.
**Common issues:**
* Cursors not appearing: Ensure each editor has a unique `editorId` and users are authenticated. Also ensure that you are logged in with two different users in two different browser profiles.
* Editor not loading: Confirm the Velt client is initialized and the API key is valid.
> [!TIP]
>
> Use the [VeltCrdtStoreMap debugging interface](/docs/realtime-collaboration/crdt/setup/core#veltcrdtstoremap) to inspect and monitor your CRDT stores in real-time from the browser console.
## Complete Example
> [tab] React / Next.js
>
> A complete collaborative BlockNote editor with user login, status display, and version management.
>
> **App.tsx**
>
> ```tsx Complete App.tsx expandable lines theme={null}
> import { useMemo } from 'react';
> import { VeltProvider, useSetDocument, useCurrentUser } from '@veltdev/react';
> import { Header } from './Header';
> import { EditorComponent } from './Editor';
>
> const API_KEY = 'YOUR_API_KEY';
>
> function getDocumentParams() {
> const params = new URLSearchParams(window.location.search);
> return {
> documentId: params.get('documentId') || 'blocknote-crdt-react-demo-doc-1',
> documentName: params.get('documentName') || 'BlockNote CRDT React Demo',
> };
> }
>
> function AppContent() {
> const veltUser = useCurrentUser();
> const { documentId, documentName } = useMemo(() => getDocumentParams(), []);
> useSetDocument(documentId, { documentName });
>
> return (
>
>
>
>
>
>
> );
> }
>
> export const App = () => (
>
>
>
> );
> ```
>
> **Editor.tsx**
>
> ```tsx Complete Editor.tsx expandable lines theme={null}
> import { useEffect, useState, useCallback, useMemo } from 'react';
> import { useVeltClient, useCurrentUser } from '@veltdev/react';
> import { useCollaboration } from '@veltdev/blocknote-crdt-react';
> import { useCreateBlockNote } from '@blocknote/react';
> import { BlockNoteView } from '@blocknote/mantine';
> import '@blocknote/mantine/style.css';
> import type { Version } from '@veltdev/crdt';
>
> function getEditorParams() {
> const params = new URLSearchParams(window.location.search);
> return {
> documentId: params.get('documentId') || 'blocknote-crdt-react-demo-doc-1',
> forceReset: params.get('forceResetInitialContent') === 'true',
> };
> }
>
> export const EditorComponent = () => {
> const veltUser = useCurrentUser();
> const [versions, setVersions] = useState([]);
> const [versionInput, setVersionInput] = useState('');
>
> const params = useMemo(() => getEditorParams(), []);
>
> const {
> collaborationConfig,
> isLoading,
> isSynced,
> status,
> manager,
> saveVersion,
> getVersions,
> restoreVersion,
> } = useCollaboration({
> editorId: params.documentId,
> forceResetInitialContent: params.forceReset,
> onError: (err) => console.error('Collaboration error:', err),
> });
>
> const editor = useCreateBlockNote(
> collaborationConfig
> ? {
> collaboration: collaborationConfig,
> placeholders: { default: '', emptyDocument: '' },
> }
> : {},
> [collaborationConfig],
> );
>
> const refreshVersions = useCallback(async () => {
> const v = await getVersions();
> setVersions(v);
> }, [getVersions]);
>
> useEffect(() => {
> if (manager) refreshVersions();
> }, [manager, refreshVersions]);
>
> const handleSaveVersion = useCallback(async (e: React.FormEvent) => {
> e.preventDefault();
> if (!versionInput.trim()) return;
> await saveVersion(versionInput.trim());
> setVersionInput('');
> await refreshVersions();
> }, [versionInput, saveVersion, refreshVersions]);
>
> const handleRestoreVersion = useCallback(async (versionId: string) => {
> await restoreVersion(versionId);
> await refreshVersions();
> }, [restoreVersion, refreshVersions]);
>
> const getStatusText = () => {
> if (isLoading) return 'Connecting...';
> switch (status) {
> case 'connected': return isSynced ? 'Connected & Synced' : 'Connected, syncing...';
> case 'connecting': return 'Connecting...';
> case 'disconnected': return 'Disconnected';
> default: return status;
> }
> };
>
> return (
>
>
>
{getStatusText()}
>
> {editor && collaborationConfig ? (
>
> ) : (
>
Loading editor...
> )}
>
>
>
>
> {versions.map((v) => (
>
> {v.versionName}
> handleRestoreVersion(v.versionId)}>
> Restore
>
>
> ))}
>
>
>
> );
> };
> ```
> [tab] Other Frameworks
>
> A complete collaborative BlockNote editor with SDK initialization, user login, status display, and version management.
>
> **HTML structure**
>
> ```html theme={null}
>
>
>
>
>
> Connecting...
>
>
>
>
>
> ```
>
> **velt.ts**
>
> ```ts Complete velt.ts expandable lines theme={null}
> import { initVelt } from '@veltdev/client';
> import type { Velt } from '@veltdev/types';
>
> let client: Velt | null = null;
> let veltInitialized = false;
>
> const veltInitSubscribers = new Map void>();
>
> async function initializeVelt() {
> client = await initVelt('YOUR_API_KEY');
>
> client.setDocument('my-document-id', { documentName: 'My Document' });
>
> client.getVeltInitState().subscribe((isReady) => {
> veltInitialized = !!isReady;
> if (isReady && client) {
> veltInitSubscribers.forEach((callback) => callback(client));
> }
> });
> }
>
> export const subscribeToVeltInit = (id: string, callback: (velt: Velt) => void) => {
> veltInitSubscribers.set(id, callback);
> if (veltInitialized && client) {
> callback(client);
> }
> };
>
> export async function loginWithUser(userId: string, name: string) {
> await client?.identify({ userId, name });
> }
>
> initializeVelt();
> ```
>
> **editor.ts**
>
> ```ts Complete editor.ts expandable lines theme={null}
> import { BlockNoteEditor } from '@blocknote/core';
> import { createCollaboration } from '@veltdev/blocknote-crdt';
> import type { CollaborationManager } from '@veltdev/blocknote-crdt';
> import type { Velt } from '@veltdev/types';
> import { subscribeToVeltInit } from './velt';
>
> let manager: CollaborationManager | null = null;
> let editor: BlockNoteEditor | null = null;
>
> async function initEditor(veltClient: Velt) {
> // Create the collaboration manager
> manager = await createCollaboration({
> editorId: 'my-document-id',
> veltClient,
> initialContent: [
> { type: 'heading', props: { level: 1 }, content: 'Welcome' },
> { type: 'paragraph', content: 'Start collaborating here...' },
> ],
> onError: (error) => console.error('Collaboration error:', error),
> });
>
> // Get the collaboration config for BlockNote
> const collabConfig = manager.getCollaborationConfig();
>
> // Create the BlockNote editor with collaboration enabled
> editor = BlockNoteEditor.create({
> collaboration: collabConfig,
> placeholders: { default: '', emptyDocument: '' },
> });
>
> // Mount the editor to the DOM
> editor.mount(document.getElementById('editor'));
>
> // Wire up status display
> updateStatus(manager.status, manager.synced);
> manager.onStatusChange((status) => updateStatus(status, manager!.synced));
> manager.onSynced((synced) => updateStatus(manager!.status, synced));
> }
>
> function updateStatus(status: string, synced: boolean) {
> const el = document.getElementById('status');
> if (!el) return;
>
> if (status === 'connected') {
> el.textContent = synced ? 'Connected & Synced' : 'Connected, syncing...';
> } else if (status === 'connecting') {
> el.textContent = 'Connecting...';
> } else {
> el.textContent = 'Disconnected';
> }
> }
>
> // Wait for SDK to be ready
> subscribeToVeltInit('editor', (velt) => initEditor(velt));
>
> // Version management
> export async function saveVersion(name: string) {
> await manager?.saveVersion(name);
> }
>
> export async function getVersions() {
> return await manager?.getVersions() ?? [];
> }
>
> export async function restoreVersion(versionId: string) {
> await manager?.restoreVersion(versionId);
> }
> ```
> [tab] Live Demo
>
> [Open in larger window](https://velt-blocknote-crdt-demo.vercel.app/)
>
> [https://velt-blocknote-crdt-demo.vercel.app/](https://velt-blocknote-crdt-demo.vercel.app/)
## How It Works
1. **`useCollaboration` (React) / `createCollaboration` (non-React)** creates a `CollaborationManager`. This initializes a CRDT Store (`type: 'xml'`, content key `'document-store'`), a Yjs `Y.XmlFragment`, and a `SyncProvider`.
2. **The collaboration config** (returned by the hook or `manager.getCollaborationConfig()`) contains the `SyncProvider`, `Y.XmlFragment`, user info, and cursor label settings. This config is passed to `useCreateBlockNote({ collaboration: ... })` (React) or `BlockNoteEditor.create({ collaboration: ... })` (non-React).
3. **User types** -> BlockNote/ProseMirror transaction -> `Y.XmlFragment` mutation -> Yjs CRDT broadcasts via Velt backend -> all connected clients see the change.
4. **Remote cursors** are tracked via Yjs Awareness. BlockNote renders colored cursor labels at each remote user's selection position using its built-in collaboration cursor support.
5. **Undo/redo** automatically switches to Yjs UndoManager when collaboration is enabled — no need to disable any history extension.
6. **Initial content** is applied only once for brand-new documents. The manager waits for remote content before deciding the document is new.
7. **Conflict resolution** is handled by Yjs CRDTs — concurrent typing at different positions merges correctly, and formatting changes on different text ranges are independent.
8. **Version management** saves the full Yjs state as a named snapshot. Restoring a version replaces the current state and broadcasts to all clients.
9. **Cleanup** is automatic — the manager destroys the store, provider, and all listeners when destroyed or the component unmounts.
## APIs
### React: useCollaboration()
The primary React hook for collaborative BlockNote editing. Creates a `CollaborationManager`, initializes the CRDT store, and returns a `BlockNoteCollaborationConfig` with cursor support.
* Signature: `useCollaboration(config: UseCollaborationConfig)`
* Params: [UseCollaborationConfig](/docs/api-reference/sdk/models/data-models#usecollaborationconfig-blocknote)
* `editorId`: Unique identifier for this collaborative session.
* `initialContent`: Block content applied once for brand-new documents.
* `debounceMs`: Throttle interval (ms) for backend writes. Default: `0`.
* `forceResetInitialContent`: If `true`, always clear and re-apply `initialContent`. Default: `false`.
* `veltClient`: Explicit Velt client. Falls back to `VeltProvider` context.
* `showCursorLabels`: Cursor label display mode. Default: `'activity'`.
* `onError`: Error callback.
* Returns: [UseCollaborationReturn](/docs/api-reference/sdk/models/data-models#usecollaborationreturn-blocknote)
* `collaborationConfig`: BlockNote collaboration config. `null` while loading.
* `isLoading`: `true` until CollaborationManager is initialized.
* `isSynced`: `true` after the initial sync with the backend completes.
* `status`: Connection status: `'connecting'`, `'connected'`, or `'disconnected'`.
* `error`: Most recent error, or `null`.
* `manager`: The underlying `CollaborationManager`. `null` before initialization.
* `saveVersion`: Save a named version snapshot. Returns the version ID, or empty string on failure.
* `getVersions`: List all saved versions. Returns empty array on failure.
* `restoreVersion`: Restore to a saved version. Returns `true` on success, `false` on failure.
```tsx theme={null}
const {
collaborationConfig,
isLoading,
isSynced,
status,
error,
manager,
saveVersion,
getVersions,
restoreVersion,
} = useCollaboration({
editorId: 'my-blocknote-editor',
onError: (err) => console.error('Collaboration error:', err),
});
```
### Non-React: createCollaboration()
Factory function that creates a `CollaborationManager`, calls `initialize()`, and returns a ready-to-use instance.
* Signature: `createCollaboration(config: CollaborationConfig): Promise`
* Params: [CollaborationConfig](/docs/api-reference/sdk/models/data-models#collaborationconfig-blocknote)
* `editorId`: Unique editor/document identifier for syncing.
* `veltClient`: Velt client instance — must have an authenticated user.
* `initialContent`: Block content applied once for brand-new documents.
* `debounceMs`: Throttle interval (ms) for backend writes. Default: `0`.
* `onError`: Callback for non-fatal errors.
* `forceResetInitialContent`: If `true`, always reset to `initialContent`. Default: `false`.
* Returns: `Promise`
```js theme={null}
import { createCollaboration } from '@veltdev/blocknote-crdt';
const manager = await createCollaboration({
editorId: 'my-document-id',
veltClient: client,
onError: (error) => console.error(error),
});
```
### CollaborationManager Methods
Once the `manager` is available (non-null from the hook, or returned from `createCollaboration`), you can use its full API:
#### manager.getCollaborationConfig()
Returns the collaboration config object that BlockNote expects. Pass this to `BlockNoteEditor.create({ collaboration: ... })` or `useCreateBlockNote({ collaboration: ... })`.
* Params: `options?: { showCursorLabels?: 'activity' | 'always' }` — Optional cursor display overrides
* Returns: `BlockNoteCollaborationConfig | null`
```js theme={null}
const collabConfig = manager.getCollaborationConfig();
const editor = BlockNoteEditor.create({
collaboration: collabConfig,
});
```
#### manager.onStatusChange()
Subscribe to connection status changes.
* Signature: `manager.onStatusChange(callback: (status: SyncStatus) => void): Unsubscribe`
* Returns: `Unsubscribe` (call to stop listening)
```js theme={null}
const unsubscribe = manager.onStatusChange((status) => {
console.log('Connection:', status);
});
unsubscribe(); // Stop listening
```
#### manager.onSynced()
Subscribe to sync state changes.
* Signature: `manager.onSynced(callback: (synced: boolean) => void): Unsubscribe`
* Returns: `Unsubscribe`
```js theme={null}
const unsubscribe = manager.onSynced((synced) => {
if (synced) console.log('Initial sync complete');
});
```
#### manager.initialized
Whether `initialize()` has completed.
* Returns: `boolean`
#### manager.synced
Whether initial sync with the backend has completed.
* Returns: `boolean`
#### manager.status
Current connection status.
* Returns: `SyncStatus` (`'connecting' | 'connected' | 'disconnected'`)
#### manager.saveVersion()
Save a named snapshot of the current document state.
* Signature: `manager.saveVersion(name: string): Promise`
* Returns: `Promise` (version ID, or empty string on failure)
```js theme={null}
const versionId = await manager.saveVersion('Before major edit');
```
#### manager.getVersions()
List all saved versions for this document.
* Returns: `Promise` (empty array on failure)
```js theme={null}
const versions = await manager.getVersions();
```
#### manager.restoreVersion()
Restore the document to a previously saved version. The restored state is pushed to all connected clients.
* Signature: `manager.restoreVersion(versionId: string): Promise`
* Returns: `Promise` (`true` on success, `false` on failure)
```js theme={null}
await manager.restoreVersion(versions[0].versionId);
```
#### manager.setStateFromVersion()
Apply a Version object's state locally to the current document.
* Signature: `manager.setStateFromVersion(version: Version): Promise`
* Returns: `Promise`
```js theme={null}
await manager.setStateFromVersion(version);
```
#### manager.getDoc()
Get the underlying Yjs document.
* Returns: `Y.Doc | null`
```js theme={null}
const doc = manager.getDoc();
```
#### manager.getXmlFragment()
Get the XmlFragment bound to BlockNote's `document-store` key.
* Returns: `Y.XmlFragment | null`
```js theme={null}
const xml = manager.getXmlFragment();
```
#### manager.getProvider()
Get the sync provider.
* Returns: `SyncProvider | null`
```js theme={null}
const provider = manager.getProvider();
```
#### manager.getAwareness()
Get the Yjs Awareness instance.
* Returns: `Awareness | null`
```js theme={null}
const awareness = manager.getAwareness();
```
#### manager.getStore()
Get the core CRDT Store.
* Returns: `Store | null`
```js theme={null}
const crdtStore = manager.getStore();
```
#### manager.destroy()
Full cleanup (automatic on editor destroy or component unmount). Safe to call multiple times.
* Returns: `void`
```js theme={null}
manager.destroy();
```
### Custom Encryption
Encrypt CRDT data before it's stored in Velt by registering a custom encryption provider. For CRDT methods, input data is of type `Uint8Array | number[]`.
> [tab] React / Next.js
>
> ```ts theme={null}
> async function encryptData(config: EncryptConfig): Promise {
> const encryptedData = await yourEncryptDataMethod(config.data);
> return encryptedData;
> }
>
> async function decryptData(config: DecryptConfig): Promise {
> const decryptedData = await yourDecryptDataMethod(config.data);
> return decryptedData;
> }
>
> const encryptionProvider: VeltEncryptionProvider = {
> encrypt: encryptData,
> decrypt: decryptData,
> };
>
> apiKey="YOUR_API_KEY"
> encryptionProvider={encryptionProvider}
> />
> ```
> [tab] Other Frameworks
>
> ```ts theme={null}
> async function encryptData(config: EncryptConfig): Promise {
> const encryptedData = await yourEncryptDataMethod(config.data);
> return encryptedData;
> }
>
> async function decryptData(config: DecryptConfig): Promise {
> const decryptedData = await yourDecryptDataMethod(config.data);
> return decryptedData;
> }
>
> const encryptionProvider: VeltEncryptionProvider = {
> encrypt: encryptData,
> decrypt: decryptData,
> };
>
> client.setEncryptionProvider(encryptionProvider);
> ```
See also: [setEncryptionProvider()](/docs/api-reference/sdk/api/api-methods#setencryptionprovider-encryptionprovider)
· [VeltEncryptionProvider](/docs/api-reference/sdk/models/data-models#veltencryptionprovider)
· [EncryptConfig](/docs/api-reference/sdk/models/data-models#encryptconfig)
· [DecryptConfig](/docs/api-reference/sdk/models/data-models#decryptconfig)
## Migration Guide: v1 to v2
### React
#### Overview
The v2 API replaces `useVeltBlockNoteCrdtExtension()` with `useCollaboration()`. The new hook provides richer reactive state (status, sync, error), returns version management methods directly, and exposes the `CollaborationManager` for advanced use.
#### Key Changes
| Aspect | v1 (deprecated) | v2 (current) |
| - | - | - |
| Entry point | `useVeltBlockNoteCrdtExtension(config)` | `useCollaboration(config)` |
| Collab config | `response.collaborationConfig` | `response.collaborationConfig` (same usage) |
| Store access | `response.store` (VeltBlockNoteStore) | `response.manager` (CollaborationManager) |
| Version management | Via `store` methods | `saveVersion`, `getVersions`, `restoreVersion` (first-class) |
| Status tracking | Not available | `response.status`, `response.isSynced` |
| Error handling | Not available | `onError` callback + `response.error` state |
| Cursor labels | Not configurable | `showCursorLabels: 'activity' \| 'always'` |
| Cleanup | Automatic on unmount | Automatic on unmount |
#### Step-by-Step
**1. Replace the hook:**
```tsx theme={null}
// Before (v1)
import { useVeltBlockNoteCrdtExtension } from '@veltdev/blocknote-crdt-react';
const { collaborationConfig, isLoading, store } = useVeltBlockNoteCrdtExtension({
editorId: 'my-doc',
});
// After (v2)
import { useCollaboration } from '@veltdev/blocknote-crdt-react';
const { collaborationConfig, isLoading, isSynced, status, error, manager, saveVersion, getVersions, restoreVersion } = useCollaboration({
editorId: 'my-doc',
onError: (err) => console.error(err),
});
```
**2. Editor creation (same pattern):**
```tsx theme={null}
const editor = useCreateBlockNote(
collaborationConfig ? { collaboration: collaborationConfig } : {},
[collaborationConfig],
);
```
**3. Use version management (new in v2):**
```tsx theme={null}
await saveVersion('Draft v1');
const versions = await getVersions();
await restoreVersion(versions[0].versionId);
```
**4. Add status monitoring (new in v2):**
```tsx theme={null}
if (error) return Error: {error.message}
;
Status: {status} | Synced: {isSynced ? 'Yes' : 'No'}
```
### Non-React
#### Overview
The non-React v2 API provides `createCollaboration()` from `@veltdev/blocknote-crdt`, replacing any previous callback-based patterns. The returned `CollaborationManager` provides `getCollaborationConfig()` for BlockNote editor creation.
#### Step-by-Step
**1. Create the manager:**
```js theme={null}
import { createCollaboration } from '@veltdev/blocknote-crdt';
const manager = await createCollaboration({ editorId: 'my-doc', veltClient: client });
```
**2. Create the editor:**
```js theme={null}
const collabConfig = manager.getCollaborationConfig();
const editor = BlockNoteEditor.create({ collaboration: collabConfig });
editor.mount(document.getElementById('editor'));
```
**3. Monitor status:**
```js theme={null}
manager.onStatusChange((status) => console.log('Status:', status));
manager.onSynced((synced) => console.log('Synced:', synced));
```
**4. Version management:**
```js theme={null}
await manager.saveVersion('Draft v1');
const versions = await manager.getVersions();
await manager.restoreVersion(versionId);
```
**5. Cleanup:**
```js theme={null}
manager.destroy();
```
## Legacy API (v1)
> [!WARNING]
>
> The v1 API is deprecated. Use the v2 `useCollaboration` hook (React) or `createCollaboration` (non-React) for all new integrations. The v1 API is still exported for backward compatibility.
### React: useVeltBlockNoteCrdtExtension() (deprecated)
A React hook that returns a collaboration config and store for BlockNote integration. Internally delegates to `useCollaboration` (v2) via a compatibility wrapper.
* Signature: `useVeltBlockNoteCrdtExtension(config: VeltBlockNoteCrdtExtensionConfig)`
* Params: [VeltBlockNoteCrdtExtensionConfig](/docs/api-reference/sdk/models/data-models#veltblocknotecrdtextensionconfig-deprecated)
* Returns: [VeltBlockNoteCrdtExtensionResponse](/docs/api-reference/sdk/models/data-models#veltblocknotecrdtextensionresponse-deprecated)
```tsx theme={null}
import { useVeltBlockNoteCrdtExtension } from '@veltdev/blocknote-crdt-react';
const { collaborationConfig, isLoading } = useVeltBlockNoteCrdtExtension({
editorId: 'my-document-id',
initialContent: JSON.stringify([{ type: 'paragraph', content: '' }]),
});
const editor = useCreateBlockNote({
collaboration: collaborationConfig,
}, [collaborationConfig]);
return (
);
```
### React: VeltBlockNoteCrdtExtensionConfig (deprecated)
| Property | Type | Required | Description |
| - | - | - | - |
| `editorId` | `string` | Yes | Unique editor identifier. |
| `initialContent` | `string` | No | JSON string of blocks for new documents. |
| `debounceMs` | `number` | No | Throttle interval (ms). |
### React: VeltBlockNoteCrdtExtensionResponse (deprecated)
| Property | Type | Description |
| - | - | - |
| `collaborationConfig` | `{ fragment: any; provider: any; user: { name: string; color: string } } \| null` | Config to pass to `useCreateBlockNote`. |
| `store` | `VeltBlockNoteStore \| null` | Store instance for version management. |
| `isLoading` | `boolean` | `true` until the store is ready. |
### VeltBlockNoteStore Methods (deprecated)
| Method | Returns | Description |
| - | - | - |
| `getStore()` | `Store` | Get the core CRDT Store. |
| `getYXml()` | `Y.XmlFragment \| null` | Get the Yjs XmlFragment. |
| `getYDoc()` | `Y.Doc` | Get the Yjs Doc. |
| `isConnected()` | `boolean` | Check if connected to backend. |
| `setStateFromVersion(v)` | `Promise` | Apply a version's state. |
| `destroy()` | `void` | Clean up all resources. |
# CKEditor 5 Editor
Source: https://velt.dev/docs/realtime-collaboration/crdt/setup/ckeditor
Setup Multiplayer Editing for CKEditor 5.
The `@veltdev/ckeditor-crdt-react` and `@veltdev/ckeditor-crdt` libraries enable real-time collaborative editing in CKEditor 5. The collaboration engine is built on [Yjs](https://docs.yjs.dev/) and the Velt SDK.
## Prerequisites
* Node.js (v14 or higher)
* A Velt account with an API key ([sign up](https://console.velt.dev/))
* React (v18 or higher) when using the React wrapper
* A CKEditor 5 license compatible with your build
* Optional: TypeScript for type safety
## Setup
### Step 1: Install Dependencies
> [tab] React / Next.js
>
> ```bash theme={null}
> npm install @veltdev/ckeditor-crdt-react @veltdev/ckeditor-crdt @veltdev/react @veltdev/types ckeditor5 @ckeditor/ckeditor5-react yjs y-protocols
> ```
> [tab] Other Frameworks
>
> ```bash theme={null}
> npm install @veltdev/ckeditor-crdt @veltdev/crdt @veltdev/client ckeditor5 yjs y-protocols
> ```
The React package provides the drop-in component and hook. The base package provides the imperative manager, provider adapter, and HTML content helpers.
```ts theme={null}
// vite.config.ts
import { defineConfig } from 'vite';
export default defineConfig({
resolve: {
dedupe: ['ckeditor5', 'yjs', 'y-protocols', 'lib0'],
},
optimizeDeps: {
include: ['ckeditor5'],
},
});
```
### Step 2: Setup Velt
Initialize Velt, authenticate a user, and set a stable document context before collaboration starts. Follow the [Velt Setup Docs](/docs/get-started/quickstart) for the production token endpoint used by `authProvider`.
> [tab] React / Next.js
>
> ```tsx theme={null}
> import { useEffect, useState } from 'react';
> import {
> VeltProvider,
> useCurrentUser,
> useSetDocuments,
> } from '@veltdev/react';
>
> const DOCUMENT_ID = 'article-123';
> const USER = {
> userId: 'user-1',
> name: 'Ada Lovelace',
> email: 'ada@example.com',
> organizationId: 'org-1',
> };
>
> const authProvider = {
> user: USER,
> retryConfig: { retryCount: 3, retryDelay: 1000 },
> generateToken: async () => {
> const response = await fetch('/api/velt/token', {
> method: 'POST',
> headers: { 'Content-Type': 'application/json' },
> body: JSON.stringify(USER),
> });
> const { token } = await response.json();
> return token;
> },
> };
>
> function CollaborationScope() {
> const user = useCurrentUser();
> const { setDocuments } = useSetDocuments();
> const [documentReady, setDocumentReady] = useState(false);
>
> useEffect(() => {
> if (!user) {
> setDocumentReady(false);
> return;
> }
> setDocuments([{
> id: DOCUMENT_ID,
> metadata: { documentName: 'Article 123' },
> }]);
> setDocumentReady(true);
> }, [user, setDocuments]);
>
> return user && documentReady
> ?
> : Preparing collaboration...
;
> }
>
>
>
>
> ```
> [tab] Other Frameworks
>
> Authenticate before setting the document. Wait for Velt readiness before creating CKEditor:
>
> ```ts theme={null}
> import { initVelt } from '@veltdev/client';
>
> const DOCUMENT_ID = 'article-123';
> const client = await initVelt('YOUR_API_KEY');
>
> await client.identify({
> userId: 'user-1',
> name: 'Ada Lovelace',
> email: 'ada@example.com',
> organizationId: 'org-1',
> });
>
> await client.setDocument(DOCUMENT_ID, {
> documentName: 'Article 123',
> });
>
> const initSubscription = client.getVeltInitState().subscribe((isReady) => {
> if (isReady) void initializeCKEditor(client);
> });
> ```
### Step 3: Configure CKEditor
Import the editor constructor, the features your build needs, and CKEditor styles:
```tsx theme={null}
import {
ClassicEditor,
Essentials,
Paragraph,
Bold,
Italic,
Underline,
Heading,
List,
Highlight,
FontColor,
FontBackgroundColor,
Undo,
GeneralHtmlSupport,
} from 'ckeditor5';
import 'ckeditor5/ckeditor5.css';
const editorConfig = {
licenseKey: 'GPL',
plugins: [
Essentials,
Paragraph,
Bold,
Italic,
Underline,
Heading,
List,
Highlight,
FontColor,
FontBackgroundColor,
Undo,
GeneralHtmlSupport,
],
toolbar: [
'undo', 'redo', '|',
'heading', '|',
'bold', 'italic', 'underline', '|',
'fontColor', 'fontBackgroundColor', 'highlight', '|',
'bulletedList', 'numberedList',
],
};
```
Use your commercial CKEditor license key instead of `GPL` when required by your distribution.
CKEditor serializes highlights as `` elements. This markup persists through realtime sync, force reset, and version restore:
```html theme={null}
Highlighted
```
### Step 4: Initialize Collaborative Editor
* Pass an `editorId` to uniquely identify the shared editor.
* Do not pass CKEditor React's `data` or `onReady` to the drop-in component; the CRDT wrapper owns content and editor capture.
* Use `initialContent` as HTML seed content for a new shared document.
The wrapper registers its Yjs fragment observer before the Store loads remote state. This ordering is required: attaching the observer after `Store.initialize()` can miss the initial server hydration.
> [tab] React Component
>
> ```tsx theme={null}
> import { CKEditorCrdtEditor } from '@veltdev/ckeditor-crdt-react';
>
> function CollaborativeEditor() {
> return (
> editor={ClassicEditor}
> editorId={DOCUMENT_ID}
> initialContent="Start writing here...
"
> config={editorConfig}
> cursorData={{ name: 'Ada', color: '#0f766e' }}
> debounceMs={125}
> onError={(error) => console.error('Collaboration error:', error)}
> />
> );
> }
> ```
>
> Standard CKEditor React props pass through except `data` and `onReady`. Use `onEditorReady` to receive the captured editor and `onCKEditorError` for CKEditor watchdog errors.
> [tab] React Hook
>
> Use `useCollaboration()` when you render CKEditor yourself:
>
> ```tsx theme={null}
> import { CKEditor } from '@ckeditor/ckeditor5-react';
> import { useCollaboration } from '@veltdev/ckeditor-crdt-react';
>
> function CollaborativeEditor() {
> const {
> editorRef,
> manager,
> primitives,
> isLoading,
> isSynced,
> status,
> error,
> } = useCollaboration({
> editorId: DOCUMENT_ID,
> initialContent: 'Start writing here...
',
> onError: (err) => console.error('Collaboration error:', err),
> });
>
> if (error) return Error: {error.message}
;
>
> return (
>
>
Status: {isLoading ? 'loading' : status} | Synced: {isSynced ? 'Yes' : 'No'}
>
editor={ClassicEditor}
> data=""
> config={editorConfig}
> onReady={(editor) => editorRef(editor)}
> onAfterDestroy={() => editorRef(null)}
> />
>
> );
> }
> ```
>
> > [!WARNING]
> >
> > When using the hook, keep `data` empty and do not update it from React state. Forward `onAfterDestroy` to `editorRef(null)` so the manager releases a destroyed editor instance.
> [tab] Other Frameworks
>
> ```ts theme={null}
> import { createCollaboration } from '@veltdev/ckeditor-crdt';
>
> async function initializeCKEditor(client) {
> const editor = await ClassicEditor.create(
> document.querySelector('#editor')!,
> editorConfig,
> );
>
> const manager = await createCollaboration({
> editorId: DOCUMENT_ID,
> veltClient: client,
> editor,
> initialContent: 'Start writing here...
',
> debounceMs: 125,
> cursorData: { name: 'Ada', color: '#0f766e' },
> cursorsContainer: document.querySelector('#editor-surface'),
> onError: (error) => console.error('Collaboration error:', error),
> });
>
> return { editor, manager };
> }
> ```
Set the Velt document context before rendering the editor. The React integration explicitly waits until Velt is initialized, a user is authenticated, the CKEditor instance is ready, and `enabled` is not `false`. Document context is a prerequisite, but the hook does not explicitly wait for it.
### Step 5: Status Monitoring (Optional)
The hook returns reactive `status`, `synced` / `isSynced`, `isLoading`, and `error` state. The component offers `onStatusChange` and `onManagerReady` callbacks.
> [tab] React / Next.js
>
> ```tsx theme={null}
> useEffect(() => {
> if (!manager) return;
>
> const offStatus = manager.onStatusChange(console.log);
> const offSynced = manager.onSynced(console.log);
>
> return () => {
> offStatus();
> offSynced();
> };
> }, [manager]);
> ```
> [tab] Other Frameworks
>
> ```ts theme={null}
> const offStatus = manager.onStatusChange((status) => {
> console.log('Status:', status);
> });
> const offSynced = manager.onSynced((synced) => {
> console.log('Synced:', synced);
> });
>
> // Cleanup:
> offStatus();
> offSynced();
> ```
> [!NOTE]
>
> Do not disable local editing simply because the provider is connecting. Local HTML changes synchronize when the connection returns.
### Step 6: Version Management (Optional)
The hook keeps version metadata in React state and refreshes it after saves and restores:
> [tab] React / Next.js
>
> ```tsx theme={null}
> const {
> versions,
> saveVersion,
> restoreVersion,
> refreshVersions,
> } = useCollaboration({ editorId: DOCUMENT_ID });
>
> const versionId = await saveVersion('Approved copy');
> await refreshVersions();
> await restoreVersion(versionId);
> ```
> [tab] Other Frameworks
>
> ```ts theme={null}
> const versionId = await manager.saveVersion('Approved copy');
> let versions = await manager.getVersions();
>
> await manager.restoreVersion(versionId);
> versions = await manager.getVersions();
> ```
The methods are no-throw: when unavailable they resolve to `''`, `false`, or `[]`. A restore updates the shared HTML for every collaborator.
### Step 7: Force Reset Initial Content (Optional)
`initialContent` is normalized HTML and is applied once to a new empty shared document:
> [tab] React / Next.js
>
> ```tsx theme={null}
> editor={ClassicEditor}
> editorId={DOCUMENT_ID}
> config={editorConfig}
> initialContent="Project brief Start collaborating...
"
> />
> ```
>
> For an explicit reset:
>
> ```tsx theme={null}
> editor={ClassicEditor}
> editorId={DOCUMENT_ID}
> config={editorConfig}
> initialContent="Fresh template
"
> forceResetInitialContent
> />
> ```
> [tab] Other Frameworks
>
> Add the reset options to the manager creation call from Step 4:
>
> ```ts theme={null}
> const editor = await ClassicEditor.create(
> document.querySelector('#editor')!,
> editorConfig,
> );
>
> const manager = await createCollaboration({
> editorId: DOCUMENT_ID,
> veltClient: client,
> editor,
> initialContent: 'Fresh template
',
> forceResetInitialContent: true,
> });
> ```
> [!WARNING]
>
> `forceResetInitialContent` replaces existing shared HTML. Do not enable it during normal initialization.
### Step 8: Configure Remote Cursors (Optional)
Remote carets and selections render in an overlay anchored to CKEditor's editable surface.
> [tab] React / Next.js
>
> ```tsx theme={null}
> editor={ClassicEditor}
> editorId={DOCUMENT_ID}
> config={editorConfig}
> cursorData={{
> name: user.name,
> color: '#2563eb',
> colorLight: '#2563eb33',
> }}
> />
> ```
>
> Pass a custom `cursorsContainer`, or set it to `null` to disable overlay DOM while retaining awareness data.
>
> The hook also returns reactive `remoteCursors`:
>
> ```tsx theme={null}
> const { remoteCursors } = useCollaboration({
> editorId: DOCUMENT_ID,
> cursorData: { name: user.name, color: '#2563eb' },
> });
>
> return (
>
> {remoteCursors.map((cursor) => (
>
> {cursor.name}
>
> ))}
>
> );
> ```
> [tab] Other Frameworks
>
> Pass cursor identity and an optional overlay container when creating the manager:
>
> ```ts theme={null}
> const editor = await ClassicEditor.create(
> document.querySelector('#editor')!,
> editorConfig,
> );
>
> const manager = await createCollaboration({
> editorId: DOCUMENT_ID,
> veltClient: client,
> editor,
> cursorData: {
> name: 'Ada Lovelace',
> color: '#2563eb',
> colorLight: '#2563eb33',
> },
> cursorsContainer: document.querySelector('#editor-surface'),
> });
>
> const offRemoteCursors = manager.onRemoteCursorsChange((cursors) => {
> console.log('Remote cursors:', cursors);
> });
> ```
>
> Set `cursorsContainer: null` to keep awareness data without rendering the overlay. Call `offRemoteCursors()` during cleanup.
Optional host styling:
```css theme={null}
.velt-ckeditor-cursor-overlay {
pointer-events: none;
}
.velt-ckeditor-remote-selection {
border-radius: 2px;
mix-blend-mode: multiply;
pointer-events: none;
position: absolute;
}
.velt-ckeditor-remote-cursor,
.velt-ckeditor-remote-cursor-caret {
border-radius: 999px;
min-height: 18px;
pointer-events: none;
position: absolute;
width: 2px;
}
.velt-ckeditor-remote-cursor-label {
background: white;
border: 1px solid;
border-left-width: 4px;
border-radius: 6px;
font-size: 12px;
font-weight: 700;
padding: 3px 8px;
pointer-events: none;
position: absolute;
white-space: nowrap;
}
```
The built-in overlay creates `.velt-ckeditor-remote-cursor`, `.velt-ckeditor-remote-cursor-caret`, `.velt-ckeditor-remote-cursor-label`, and `.velt-ckeditor-remote-selection` elements. Cursor labels also carry the collaborator name in `data-velt-cursor-name` for selectors, tests, or custom styling.
### Step 9: CRDT Event Subscription (Optional)
> [tab] React / Next.js
>
> ```tsx theme={null}
> import { useEffect } from 'react';
> import { useVeltClient } from '@veltdev/react';
>
> const { client } = useVeltClient();
>
> useEffect(() => {
> if (!client) return;
>
> const subscription = client.getCrdtElement().on('updateData').subscribe((event) => {
> if (event) console.log('CRDT update:', event);
> });
>
> return () => subscription?.unsubscribe?.();
> }, [client]);
> ```
> [tab] Other Frameworks
>
> ```ts theme={null}
> const crdtSubscription = client
> .getCrdtElement()
> .on('updateData')
> .subscribe((event) => {
> if (event) console.log('CRDT update:', event);
> });
>
> // Cleanup:
> crdtSubscription.unsubscribe();
> ```
### Step 10: Custom Encryption (Optional)
> [tab] React / Next.js
>
> ```tsx theme={null}
> const encryptionProvider = {
> encrypt: async ({ data }) => data.map((n) => n.toString()).join('__'),
> decrypt: async ({ data }) => data.split('__').map((s) => parseInt(s, 10)),
> };
>
> apiKey="YOUR_API_KEY"
> authProvider={authProvider}
> encryptionProvider={encryptionProvider}
> >
> ...
>
> ```
> [tab] Other Frameworks
>
> Set encryption before creating CKEditor collaboration:
>
> ```ts theme={null}
> client.setEncryptionProvider({
> encrypt: async ({ data }) => data.map((n) => n.toString()).join('__'),
> decrypt: async ({ data }) => data.split('__').map((s) => parseInt(s, 10)),
> });
> ```
See also: [setEncryptionProvider()](/docs/api-reference/sdk/api/api-methods#setencryptionprovider-encryptionprovider)
· [VeltEncryptionProvider](/docs/api-reference/sdk/models/data-models#veltencryptionprovider)
· [EncryptConfig](/docs/api-reference/sdk/models/data-models#encryptconfig)
· [DecryptConfig](/docs/api-reference/sdk/models/data-models#decryptconfig)
### Step 11: Error Handling (Optional)
Use `onError` for collaboration errors and `onCKEditorError` for official CKEditor React watchdog errors:
> [tab] React / Next.js
>
> ```tsx theme={null}
> editor={ClassicEditor}
> editorId={DOCUMENT_ID}
> config={editorConfig}
> onError={(error) => console.error('Collaboration:', error)}
> onCKEditorError={(error, details) => console.error('CKEditor:', error, details)}
> />
> ```
> [tab] Other Frameworks
>
> The direct manager reports collaboration errors through `onError`. Handle CKEditor creation errors separately:
>
> ```ts theme={null}
> try {
> const editor = await ClassicEditor.create(
> document.querySelector('#editor')!,
> editorConfig,
> );
>
> const manager = await createCollaboration({
> editorId: DOCUMENT_ID,
> veltClient: client,
> editor,
> onError: (error) => {
> console.error('CKEditor collaboration error:', error);
> },
> });
> } catch (error) {
> console.error('CKEditor creation failed:', error);
> }
> ```
### Step 12: Access Yjs Internals (Advanced)
The hook's `primitives` object groups lower-level resources:
> [tab] React / Next.js
>
> ```tsx theme={null}
> const { primitives } = useCollaboration({ editorId: DOCUMENT_ID });
>
> const editor = primitives?.editor;
> const doc = primitives?.doc;
> const xmlFragment = primitives?.xmlFragment;
> const provider = primitives?.provider;
> const providerAdapter = primitives?.providerAdapter;
> const awareness = primitives?.awareness;
> const undoManager = primitives?.undoManager;
> const store = primitives?.store;
> ```
>
> Read or replace normalized shared HTML with the manager:
>
> ```tsx theme={null}
> const html = manager.getHtml();
> manager.setHtml('Replacement content
');
> ```
> [tab] Other Frameworks
>
> ```ts theme={null}
> const doc = manager.getDoc();
> const xmlFragment = manager.getXmlFragment();
> const provider = manager.getProvider();
> const providerAdapter = manager.getProviderAdapter();
> const awareness = manager.getAwareness();
> const undoManager = manager.getUndoManager();
> const store = manager.getStore();
>
> const html = manager.getHtml();
> manager.setHtml('Replacement content
');
>
> // Collaboration-aware application controls:
> undoManager?.undo();
> undoManager?.redo();
> ```
The CKEditor source build includes its `Undo` plugin for the native toolbar. For custom collaboration-aware controls, use the manager's Yjs `UndoManager`; do not trigger both history paths from the same action.
### Step 13: Enable, Disable, and Cleanup
> [tab] React / Next.js
>
> ```tsx theme={null}
> const collaboration = useCollaboration({
> editorId: DOCUMENT_ID,
> enabled: Boolean(user && documentReady),
> });
> ```
>
> Changing `enabled` to `false` destroys the current manager; changing it back reinitializes collaboration. The component and hook also clean up automatically on unmount or dependency changes, and the hook exposes `destroy()` for early teardown.
>
> If you render CKEditor yourself, the editor remains application-owned. Forward `onAfterDestroy` to `editorRef(null)` and destroy CKEditor according to its normal lifecycle.
> [tab] Other Frameworks
>
> Keep every disposer. Destroy the manager before destroying the application-owned CKEditor instance:
>
> ```ts theme={null}
> crdtSubscription.unsubscribe();
> offRemoteCursors();
> offStatus();
> offSynced();
> initSubscription.unsubscribe();
>
> manager.destroy();
> await editor.destroy();
> ```
## Notes
* **Uncontrolled content**: The CRDT manager owns CKEditor data; do not synchronize it through React state.
* **CKEditor configuration**: Include every plugin used by the toolbar and provide the correct CKEditor license key.
* **Unique editorId**: Collaborators must share the same Velt document context and editor ID.
* **HTML data model**: The adapter stores normalized HTML in a Yjs XML fragment and preserves local selection while applying remote content.
* **Initial remote hydration**: The manager registers its Yjs fragment observer before `Store.initialize()`. Preserve that ordering in custom integrations so server state loaded during initialization is not missed.
* **Remote cursors**: The adapter renders an overlay and also exposes normalized cursor state for custom UI.
* **StrictMode-safe**: The hook destroys stale managers during React remounts and dependency changes.
* **React readiness**: The hook waits for Velt initialization, an authenticated user, the CKEditor instance, and `enabled`. It does not explicitly wait for document context, so set the document first.
* **Editor-first direct setup**: Other frameworks create CKEditor before creating the collaboration manager.
* **Other Frameworks lifecycle**: Unsubscribe callbacks, destroy the manager, and then destroy the application-owned CKEditor instance.
* **One dependency instance**: Deduplicate `ckeditor5`, `yjs`, `y-protocols`, and `lib0` in linked or monorepo builds.
* **Initial content**: Seed HTML is applied once unless an explicit reset is requested.
* **Production authentication**: Use Velt's recommended server-backed authentication flow.
## Testing and Debugging
**To test collaboration:**
1. Log in as two unique users in separate browser profiles.
2. Open the same Velt document and CKEditor `editorId`.
3. Edit text, headings, marks, and lists in both windows.
4. Verify remote selections, version restore, reconnection, and persistence after reload.
**Common issues:**
* Toolbar item unavailable: Add its CKEditor plugin to `config.plugins`.
* License error: Provide `GPL` only for a GPL-compatible use, otherwise use your commercial license key.
* Content does not sync: Remove controlled `data` updates and confirm both clients use the same document and `editorId`.
* Manager never appears: Confirm the document context was set first, Velt is initialized, a user is identified, and CKEditor's `onReady` fired. The document is a prerequisite, not an explicit hook wait condition.
* Cursors not visible: Ensure `cursorsContainer` is not `null` and the editable element is mounted.
* Stale manager after watchdog restart: Forward `onAfterDestroy` when using the hook directly.
> [!TIP]
>
> Use the [VeltCrdtStoreMap debugging interface](/docs/realtime-collaboration/crdt/setup/core#veltcrdtstoremap) to inspect the shared XML and provider state.
## Complete Example
> [tab] React / Next.js
>
> ```tsx Complete App.tsx expandable lines theme={null}
> import { useEffect, useState } from 'react';
> import { CKEditorCrdtEditor } from '@veltdev/ckeditor-crdt-react';
> import type { CollaborationManager, SyncStatus } from '@veltdev/ckeditor-crdt-react';
> import {
> VeltProvider,
> useCurrentUser,
> useSetDocuments,
> } from '@veltdev/react';
> import {
> ClassicEditor,
> Essentials,
> Paragraph,
> Bold,
> Italic,
> Underline,
> Heading,
> List,
> Highlight,
> FontColor,
> FontBackgroundColor,
> Undo,
> GeneralHtmlSupport,
> } from 'ckeditor5';
> import 'ckeditor5/ckeditor5.css';
>
> const DOCUMENT_ID = 'ckeditor-crdt-demo-doc-1';
>
> const editorConfig = {
> licenseKey: 'GPL',
> plugins: [
> Essentials,
> Paragraph,
> Bold,
> Italic,
> Underline,
> Heading,
> List,
> Highlight,
> FontColor,
> FontBackgroundColor,
> Undo,
> GeneralHtmlSupport,
> ],
> toolbar: [
> 'undo', 'redo', '|',
> 'heading', '|',
> 'bold', 'italic', 'underline', '|',
> 'fontColor', 'fontBackgroundColor', 'highlight', '|',
> 'bulletedList', 'numberedList',
> ],
> };
>
> const USER = {
> userId: 'ada',
> name: 'Ada Lovelace',
> email: 'ada@example.com',
> organizationId: 'my-org-id',
> color: '#2563eb',
> };
>
> const authProvider = {
> user: USER,
> retryConfig: { retryCount: 3, retryDelay: 1000 },
> generateToken: async () => {
> const response = await fetch('/api/velt/token', {
> method: 'POST',
> headers: { 'Content-Type': 'application/json' },
> body: JSON.stringify(USER),
> });
> const { token } = await response.json();
> return token;
> },
> };
>
> function CollaborativeEditor() {
> const user = useCurrentUser();
> const [status, setStatus] = useState('connecting');
> const [manager, setManager] = useState(null);
> const [versionName, setVersionName] = useState('');
> const { setDocuments } = useSetDocuments();
> const [documentReady, setDocumentReady] = useState(false);
>
> useEffect(() => {
> if (!user) {
> setDocumentReady(false);
> return;
> }
> setDocuments([{
> id: DOCUMENT_ID,
> metadata: { documentName: 'CKEditor CRDT Demo' },
> }]);
> setDocumentReady(true);
> }, [user, setDocuments]);
>
> if (!user || !documentReady) return Preparing collaboration...
;
>
> const saveVersion = async () => {
> if (!manager || !versionName.trim()) return;
> await manager.saveVersion(versionName.trim());
> setVersionName('');
> };
>
> return (
>
> Status: {status} | Synced: {manager?.synced ? 'Yes' : 'No'}
> value={versionName}
> onChange={(event) => setVersionName(event.target.value)}
> placeholder="Version name"
> />
> Save version
> editor={ClassicEditor}
> editorId={DOCUMENT_ID}
> config={editorConfig}
> initialContent="Shared document Start collaborating...
"
> cursorData={{ name: user.name, color: '#2563eb' }}
> onStatusChange={setStatus}
> onManagerReady={setManager}
> onError={console.error}
> />
>
> );
> }
>
> export default function App() {
> return (
> apiKey="YOUR_VELT_API_KEY"
> authProvider={authProvider}
> >
>
>
> );
> }
> ```
> [tab] Other Frameworks
>
> Create the CKEditor instance first. Only after it resolves should you pass that exact instance to the framework-agnostic collaboration manager.
>
> ```ts Complete app.ts expandable lines theme={null}
> import { initVelt } from '@veltdev/client';
> import {
> createCollaboration,
> type CollaborationManager,
> } from '@veltdev/ckeditor-crdt';
> import {
> ClassicEditor,
> Essentials,
> Paragraph,
> Bold,
> Italic,
> Underline,
> Heading,
> List,
> Highlight,
> FontColor,
> FontBackgroundColor,
> Undo,
> GeneralHtmlSupport,
> } from 'ckeditor5';
> import 'ckeditor5/ckeditor5.css';
>
> const DOCUMENT_ID = 'ckeditor-crdt-demo-doc-1';
>
> const editorConfig = {
> licenseKey: 'GPL',
> plugins: [
> Essentials,
> Paragraph,
> Bold,
> Italic,
> Underline,
> Heading,
> List,
> Highlight,
> FontColor,
> FontBackgroundColor,
> Undo,
> GeneralHtmlSupport,
> ],
> toolbar: [
> 'undo', 'redo', '|',
> 'heading', '|',
> 'bold', 'italic', 'underline', '|',
> 'fontColor', 'fontBackgroundColor', 'highlight', '|',
> 'bulletedList', 'numberedList',
> ],
> };
>
> let resources: {
> editor: Awaited>;
> manager: CollaborationManager;
> offStatus: () => void;
> offSynced: () => void;
> offRemoteCursors: () => void;
> crdtSubscription: { unsubscribe: () => void };
> } | null = null;
>
> async function initializeCKEditor(client) {
> const editor = await ClassicEditor.create(
> document.querySelector('#editor')!,
> editorConfig,
> );
>
> const manager = await createCollaboration({
> editorId: DOCUMENT_ID,
> veltClient: client,
> editor,
> initialContent: 'Shared document Start collaborating...
',
> debounceMs: 125,
> cursorData: {
> name: 'Ada Lovelace',
> color: '#2563eb',
> colorLight: '#2563eb33',
> },
> cursorsContainer: document.querySelector('#editor-surface'),
> onError: (error) => console.error('Collaboration error:', error),
> });
>
> if (!manager.getXmlFragment() || !manager.getEditor()) {
> manager.destroy();
> await editor.destroy();
> throw new Error('CKEditor collaboration did not initialize');
> }
>
> const offStatus = manager.onStatusChange((status) => {
> document.getElementById('status')!.textContent = status;
> });
> const offSynced = manager.onSynced((synced) => {
> document.getElementById('synced')!.textContent = synced ? 'Yes' : 'No';
> });
> const offRemoteCursors = manager.onRemoteCursorsChange((cursors) => {
> console.log('Remote cursors:', cursors);
> });
> const crdtSubscription = client
> .getCrdtElement()
> .on('updateData')
> .subscribe((event) => {
> if (event) console.log('CRDT update:', event);
> });
>
> document.getElementById('undo')?.addEventListener('click', () => {
> manager.getUndoManager()?.undo();
> });
> document.getElementById('redo')?.addEventListener('click', () => {
> manager.getUndoManager()?.redo();
> });
> document.getElementById('save-version')?.addEventListener('click', async () => {
> const versionId = await manager.saveVersion('Approved copy');
> console.log('Saved version:', versionId, await manager.getVersions());
> });
>
> resources = {
> editor,
> manager,
> offStatus,
> offSynced,
> offRemoteCursors,
> crdtSubscription,
> };
> }
>
> const client = await initVelt('YOUR_VELT_API_KEY');
>
> await client.identify({
> userId: 'ada',
> name: 'Ada Lovelace',
> email: 'ada@example.com',
> organizationId: 'my-org-id',
> });
>
> await client.setDocument(DOCUMENT_ID, {
> documentName: 'CKEditor CRDT Demo',
> });
>
> let initializationStarted = false;
> const initSubscription = client.getVeltInitState().subscribe((isReady) => {
> if (!isReady || initializationStarted) return;
> initializationStarted = true;
> void initializeCKEditor(client);
> });
>
> window.addEventListener('beforeunload', () => {
> resources?.crdtSubscription.unsubscribe();
> resources?.offRemoteCursors();
> resources?.offStatus();
> resources?.offSynced();
> initSubscription.unsubscribe();
>
> resources?.manager.destroy();
> void resources?.editor.destroy();
> });
> ```
## How It Works
1. React applications initialize Velt through an authenticated `VeltProvider`; other frameworks use `initVelt()`. Both authenticate before setting the shared document.
2. The React hook explicitly waits for Velt initialization, an authenticated user, the CKEditor instance, and `enabled`. The document remains a prerequisite but is not an explicit hook wait condition.
3. Direct integrations create CKEditor first and pass the resolved editor instance to `createCollaboration()`.
4. The manager opens a Velt CRDT store keyed by `editorId`, registers the fragment observer, and only then initializes the Store so initial remote HTML is observed.
5. CKEditor model changes are debounced into shared transactions; remote changes update CKEditor while preserving the local selection when possible.
6. Awareness carries user and selection metadata for remote cursor overlays, and Velt persists CRDT updates and named versions.
## APIs
### React: CKEditorCrdtEditor
| Prop | Type | Required | Description |
| - | - | - | - |
| `editor` | `unknown` | Yes | CKEditor constructor, usually `ClassicEditor`. |
| `editorId` | `string` | No\* | Unique key for the shared editor. |
| `documentId` | `string` | No\* | Used as `editorId` when omitted. |
| `config` | `Record` | No | CKEditor plugins, toolbar, and license configuration. |
| `veltClient` | `Velt` | No | Overrides the context client. |
| `initialContent` | `string` | No | Initial HTML for a new document. |
| `forceResetInitialContent` | `boolean` | No | Replaces shared HTML during initialization. |
| `cursorData` | `CKEditorCursorData` | No | Local cursor identity and colors. |
| `cursorsContainer` | `HTMLElement \| null` | No | Overlay container; `null` disables overlay DOM. |
| `debounceMs` | `number` | No | Editor-to-CRDT write debounce. |
| `onError` | `(error: Error) => void` | No | Collaboration errors. |
| `onCKEditorError` | `function` | No | CKEditor React watchdog errors. |
| `onStatusChange` | `(status: SyncStatus) => void` | No | Status callback. |
| `onManagerReady` / `onEditorReady` | `function` | No | Receives manager or editor. |
\*Provide either `editorId` or `documentId`. Other CKEditor React props pass through except CRDT-owned `data` and `onReady`.
### React: useCollaboration()
| Return | Type | Description |
| - | - | - |
| `editorRef` | `(editor \| null) => void` | Captures or releases CKEditor. |
| `manager` | `CollaborationManager \| null` | Base manager. |
| `primitives` | `CKEditorCollaborationPrimitives \| null` | CKEditor, Yjs, and Velt resources. |
| `isLoading` | `boolean` | Initialization state. |
| `synced` / `isSynced` | `boolean` | Initial backend sync state. |
| `status` | `SyncStatus` | Connection status. |
| `error` | `Error \| null` | Latest error. |
| `versions` | `Version[]` | Saved versions. |
| `remoteCursors` | `CKEditorRemoteCursor[]` | Reactive remote cursor metadata. |
| `saveVersion(name)` | `Promise` | Saves a version. |
| `restoreVersion(id)` | `Promise` | Restores a version. |
| `refreshVersions()` | `Promise` | Reloads versions. |
| `destroy()` | `void` | Destroys collaboration early. |
### Other Frameworks: createCollaboration()
```ts theme={null}
import { createCollaboration } from '@veltdev/ckeditor-crdt';
const editor = await ClassicEditor.create(
document.querySelector('#editor')!,
editorConfig,
);
const manager = await createCollaboration({
editorId: DOCUMENT_ID,
veltClient: client,
editor,
initialContent: 'Start writing here...
',
debounceMs: 125,
cursorData: { name: 'Ada', color: '#0f766e' },
cursorsContainer: document.querySelector('#editor-surface'),
onError: console.error,
});
```
| Config | Type | Required | Description |
| - | - | - | - |
| `editorId` | `string` | Yes | Stable key for the shared CKEditor document. |
| `veltClient` | `Velt` | Yes | Initialized, authenticated Velt client with a current document. |
| `editor` | `CKEditorEditorLike` | Yes | CKEditor instance created before the manager. |
| `initialContent` | `string` | No | Normalized HTML seed for a new, empty shared document. |
| `forceResetInitialContent` | `boolean` | No | Explicitly replaces existing shared HTML. |
| `cursorData` | `CKEditorCursorData` | No | Awareness identity and cursor colors. |
| `cursorsContainer` | `HTMLElement \| null` | No | Cursor overlay host; `null` disables overlay DOM. |
| `debounceMs` | `number` | No | Editor-to-CRDT write debounce. |
| `onError` | `(error: Error) => void` | No | Receives non-fatal initialization and runtime errors. |
### CollaborationManager Methods
| Method or property | Description |
| - | - |
| `initialize()` / `destroy()` | Starts or destroys collaboration. |
| `initialized`, `synced`, `status` | Current manager state. |
| `onStatusChange(callback)` / `onSynced(callback)` | Status subscriptions. |
| `getHtml()` / `setHtml(html)` | Reads or replaces normalized HTML. |
| `getRemoteCursors()` | Reads remote cursor metadata. |
| `onRemoteCursorsChange(callback)` | Subscribes to cursor metadata. |
| `getDoc()` / `getXmlFragment()` | Returns shared Yjs data. |
| `getProvider()` / `getProviderAdapter()` | Returns provider objects. |
| `getAwareness()` / `getUndoManager()` | Returns awareness and undo manager. |
| `getStore()` / `getEditor()` | Returns Velt store and CKEditor instance. |
| `saveVersion(name)` / `getVersions()` | Saves or lists versions. |
| `restoreVersion(id)` / `setStateFromVersion(version)` | Restores shared state. |
### Exported Types and Helpers
* `CollaborationConfig`, `UseCollaborationConfig` / `UseCKEditorCrdtConfig`
* `UseCollaborationReturn` / `CKEditorCrdtHookResult`
* `CKEditorCrdtEditorProps`, `CKEditorCollaborationPrimitives`, `CKEditorEditorLike`
* `CKEditorCursorData`, `CKEditorCursorRect`, `CKEditorCursorSelection`, `CKEditorRemoteCursor`
* `SyncStatus`, `Unsubscribe`, `Version`
* `normalizeHtml()`, `readHtmlFromXmlFragment()`, `writeHtmlToXmlFragment()`
* `hasSharedHtml()`, `applyInitialContent()`
# CodeMirror Editor
Source: https://velt.dev/docs/realtime-collaboration/crdt/setup/codemirror
Setup Multiplayer Editing for CodeMirror Editor.
The `@veltdev/codemirror-crdt-react` and `@veltdev/codemirror-crdt` libraries enable real-time collaborative editing on CodeMirror Editors. The collaboration editing engine is built on top of [Yjs](https://docs.yjs.dev/) and Velt SDK.
## Prerequisites
* Node.js (v14 or higher)
* React (v16.8 or higher for hooks)
* A Velt account with an API key ([sign up](https://console.velt.dev/))
* Optional: TypeScript for type safety
## Setup
### Step 1: Install Dependencies
Install the required packages:
> [tab] React / Next.js
>
> ```bash theme={null}
> npm install @veltdev/codemirror-crdt-react @veltdev/codemirror-crdt @veltdev/react @veltdev/types codemirror @codemirror/state @codemirror/view y-codemirror.next yjs
> ```
> [tab] Other Frameworks
>
> ```bash theme={null}
> npm install @veltdev/codemirror-crdt @veltdev/client codemirror @codemirror/state y-codemirror.next yjs
> ```
### Step 2: Setup Velt
Initialize the Velt client by following the [Velt Setup Docs](/docs/get-started/quickstart). This is required for the collaboration engine to work.
### Step 3: Initialize Collaborative Editor
* Initialize the collaboration manager and use it to create the CodeMirror editor.
* Pass an `editorId` to uniquely identify each editor instance you have in your app. This is especially important when you have multiple editors in your app.
> [tab] React / Next.js
>
> Use the `useCollaboration` hook to manage the entire CRDT lifecycle. It creates a `CollaborationManager`, initializes the CRDT store, and returns collaboration `primitives` (`ytext`, `awareness`, `undoManager`, `doc`) that you pass to `yCollab()` from `y-codemirror.next`.
>
> ```tsx theme={null}
> import { useCollaboration } from '@veltdev/codemirror-crdt-react';
> import { EditorState } from '@codemirror/state';
> import { EditorView, basicSetup } from 'codemirror';
> import { yCollab } from 'y-codemirror.next';
> import { useEffect, useRef } from 'react';
>
> function CodeMirrorEditor() {
> const editorElRef = useRef(null);
>
> const { primitives, isLoading, isSynced, status, error, manager } = useCollaboration({
> editorId: 'my-codemirror-editor',
> initialContent: 'console.log("Hello!");',
> onError: (err) => console.error('Collaboration error:', err),
> });
>
> useEffect(() => {
> if (!primitives?.ytext || !editorElRef.current) return;
>
> const state = EditorState.create({
> doc: primitives.ytext.toString(),
> extensions: [
> basicSetup,
> yCollab(primitives.ytext, primitives.awareness, {
> undoManager: primitives.undoManager,
> }),
> ],
> });
>
> const view = new EditorView({ state, parent: editorElRef.current });
> return () => view.destroy();
> }, [primitives]);
>
> if (error) return Error: {error.message}
;
> if (isLoading || !primitives) return Connecting...
;
>
> return
;
> }
> ```
> [tab] Other Frameworks
>
> Use `createCollaboration()` to create a `CollaborationManager`, then call `manager.getCollaborationPrimitives()` to get the Yjs primitives (`ytext`, `awareness`, `undoManager`) and pass them to `yCollab()` from `y-codemirror.next`.
>
> ```js theme={null}
> import { createCollaboration } from '@veltdev/codemirror-crdt';
> import { EditorState } from '@codemirror/state';
> import { EditorView, basicSetup } from 'codemirror';
> import { yCollab } from 'y-codemirror.next';
>
> // Wait for the SDK to be ready
> client.getVeltInitState().subscribe(async (isReady) => {
> if (!isReady) return;
>
> // Create the CollaborationManager
> const manager = await createCollaboration({
> editorId: 'my-codemirror-editor',
> veltClient: client,
> initialContent: 'console.log("Hello!");',
> onError: (error) => console.error('Collaboration error:', error),
> });
>
> // Get Yjs primitives for CodeMirror binding
> const { ytext, awareness, undoManager } = manager.getCollaborationPrimitives();
>
> // Create CodeMirror editor with yCollab extension
> const state = EditorState.create({
> doc: ytext.toString(),
> extensions: [
> basicSetup,
> yCollab(ytext, awareness, { undoManager }),
> ],
> });
>
> const editorView = new EditorView({
> state,
> parent: document.querySelector('#editor'),
> });
> });
> ```
### Step 4: Status Monitoring (Optional)
Monitor the connection status and sync state to display UI indicators.
> [tab] React / Next.js
>
> The `useCollaboration` hook returns reactive `status`, `isSynced`, and `error` state:
>
> ```tsx theme={null}
> const { primitives, isLoading, isSynced, status, error } = useCollaboration({
> editorId: 'my-codemirror-editor',
> });
>
> if (error) return Error: {error.message}
;
> if (isLoading) return Connecting...
;
>
> // In your JSX
> Status: {status} | Synced: {isSynced ? 'Yes' : 'No'}
> ```
> [tab] Other Frameworks
>
> Subscribe to status and sync changes on the `manager`:
>
> ```js theme={null}
> // Connection status: 'connecting' | 'connected' | 'disconnected'
> manager.onStatusChange((status) => {
> console.log('Status:', status);
> });
>
> // Sync state: true when initial sync is complete
> manager.onSynced((synced) => {
> console.log('Synced:', synced);
> });
>
> // Read current values at any time
> console.log(manager.status); // 'connected'
> console.log(manager.synced); // true
> console.log(manager.initialized); // true
> ```
### Step 5: Version Management (Optional)
Save and restore named snapshots of the document state.
> [tab] React / Next.js
>
> The `manager` returned by `useCollaboration` provides version management methods:
>
> ```tsx theme={null}
> // Save a version
> const versionId = await manager.saveVersion('Before major edit');
>
> // List all versions
> const versions = await manager.getVersions();
>
> // Restore a specific version
> await manager.restoreVersion(versions[0].versionId);
> ```
> [tab] Other Frameworks
>
> ```js theme={null}
> // Save a named snapshot
> const versionId = await manager.saveVersion('Draft v1');
>
> // List all saved versions
> const versions = await manager.getVersions();
> // Returns: [{ versionId, versionName, timestamp }, ...]
>
> // Restore to a saved version
> await manager.restoreVersion(versionId);
> ```
### Step 6: Force Reset Initial Content (Optional)
By default, `initialContent` is applied exactly once only when the document is brand new. Pass `forceResetInitialContent: true` to always overwrite remote data with `initialContent` on initialization.
> [tab] React / Next.js
>
> ```tsx theme={null}
> const collab = useCollaboration({
> editorId: 'my-codemirror-editor',
> initialContent: '// Fresh start',
> forceResetInitialContent: true,
> });
> ```
> [tab] Other Frameworks
>
> ```js theme={null}
> const manager = await createCollaboration({
> editorId: 'my-document-id',
> veltClient: client,
> initialContent: 'Fresh start',
> forceResetInitialContent: true,
> });
> ```
### Step 7: CRDT Event Subscription (Optional)
Listen for real-time sync events using `getCrdtElement().on()` from the Velt client.
> [tab] React / Next.js
>
> ```tsx theme={null}
> import { useVeltClient } from '@veltdev/react';
>
> const { client } = useVeltClient();
>
> useEffect(() => {
> if (!client) return;
> const crdtElement = client.getCrdtElement();
> const sub = crdtElement.on('updateData').subscribe((event) => {
> if (event) console.log('CRDT update:', event);
> });
> return () => sub?.unsubscribe?.();
> }, [client]);
> ```
> [tab] Other Frameworks
>
> ```js theme={null}
> const crdtElement = client.getCrdtElement();
>
> crdtElement.on('updateData').subscribe((event) => {
> if (event) {
> console.log('CRDT data updated:', event);
> }
> });
> ```
### Step 8: Custom Encryption (Optional)
Encrypt CRDT data before it's stored in Velt by registering a custom encryption provider. For CRDT methods, input data is of type `Uint8Array | number[]`.
> [tab] React / Next.js
>
> ```ts theme={null}
> const encryptionProvider = {
> encrypt: async ({ data }) => data.map((n) => n.toString()).join('__'),
> decrypt: async ({ data }) => data.split('__').map((s) => parseInt(s, 10)),
> };
>
>
> ...
>
> ```
> [tab] Other Frameworks
>
> ```js theme={null}
> const encryptionProvider = {
> encrypt: async (config) => {
> return config.data.map((num) => num.toString()).join('__');
> },
> decrypt: async (config) => {
> return config.data.split('__').map((str) => parseInt(str, 10));
> },
> };
>
> client.setEncryptionProvider(encryptionProvider);
> ```
See also: [setEncryptionProvider()](/docs/api-reference/sdk/api/api-methods#setencryptionprovider-encryptionprovider)
· [VeltEncryptionProvider](/docs/api-reference/sdk/models/data-models#veltencryptionprovider)
· [EncryptConfig](/docs/api-reference/sdk/models/data-models#encryptconfig)
· [DecryptConfig](/docs/api-reference/sdk/models/data-models#decryptconfig)
### Step 9: Error Handling (Optional)
> [tab] React / Next.js
>
> Pass an `onError` callback to handle initialization or runtime errors. The `error` reactive state is also available for rendering.
>
> ```tsx theme={null}
> const collab = useCollaboration({
> editorId: 'my-codemirror-editor',
> onError: (error) => console.error('Collaboration error:', error),
> });
>
> if (collab.error) {
> return Error: {collab.error.message}
;
> }
> ```
> [tab] Other Frameworks
>
> Pass an `onError` callback when creating the CollaborationManager:
>
> ```js theme={null}
> const manager = await createCollaboration({
> editorId: 'my-codemirror-editor',
> veltClient: client,
> onError: (error) => console.error('Collaboration error:', error),
> });
> ```
### Step 10: Access Yjs Internals (Advanced)
The manager exposes escape hatches for direct Yjs manipulation when needed.
> [tab] React / Next.js
>
> ```tsx theme={null}
> // From the manager returned by useCollaboration
> const doc = manager.getDoc();
> const text = manager.getText();
> const awareness = manager.getAwareness();
> const provider = manager.getProvider();
> const store = manager.getStore();
> ```
> [tab] Other Frameworks
>
> ```js theme={null}
> import * as Y from 'yjs';
>
> const doc = manager.getDoc();
> const ytext = manager.getYText();
> const provider = manager.getProvider();
> const awareness = manager.getAwareness();
> const store = manager.getStore();
> const undoManager = manager.getUndoManager();
> ```
### Step 11: Cleanup
Cleanup is handled by calling `manager.destroy()`, which cascades to the store, provider, undo manager, and all listeners. Safe to call multiple times.
> [tab] React / Next.js
>
> ```tsx theme={null}
> // Automatic on component unmount via useEffect cleanup
> // Or manually:
> manager.destroy();
> ```
> [tab] Other Frameworks
>
> ```js theme={null}
> manager.destroy();
> ```
## Notes
* **Unique editorId**: Use a unique `editorId` per editor instance.
* **Wait for auth**: Initialize the store only after the Velt client is ready.
* **Use yCollab**: Pass the Yjs text, awareness, and undo manager to `yCollab`.
* **Initialize and clean up**: Destroy the `EditorView` and manager on unmount to avoid leaks.
## Testing and Debugging
**To test collaboration:**
1. Login two unique users on two browser profiles and open the same page in both.
2. Edit in one window and verify changes and cursors appear in the other.
**Common issues:**
* Cursors not appearing: Ensure each editor has a unique `editorId` and users are authenticated. Also ensure that you are logged in with two different users in two different browser profiles.
* Editor not loading: Confirm the Velt client is initialized and the API key is valid.
* Disconnected session: Check network.
> [!TIP]
>
> Use the [VeltCrdtStoreMap debugging interface](/docs/realtime-collaboration/crdt/setup/core#veltcrdtstoremap) to inspect and monitor your CRDT stores in real-time from the browser console.
## Complete Example
> [tab] React / Next.js
>
> A complete collaborative CodeMirror editor with user login, status display, and version management.
>
> **App.tsx**
>
> ```tsx Complete App.tsx expandable lines theme={null}
> import { useMemo } from 'react';
> import { VeltProvider, useSetDocument, useCurrentUser } from '@veltdev/react';
> import { Header } from './Header';
> import { EditorComponent } from './Editor';
>
> const API_KEY = 'YOUR_API_KEY';
>
> function getDocumentParams() {
> const params = new URLSearchParams(window.location.search);
> return {
> documentId: params.get('documentId') || 'codemirror-crdt-react-demo-doc-1',
> documentName: params.get('documentName') || 'CodeMirror CRDT React Demo',
> };
> }
>
> function AppContent() {
> const veltUser = useCurrentUser();
> const { documentId, documentName } = useMemo(() => getDocumentParams(), []);
> useSetDocument(documentId, { documentName });
>
> return (
>
>
>
>
>
>
> );
> }
>
> export const App = () => (
>
>
>
> );
> ```
>
> **Editor.tsx**
>
> ```tsx Complete Editor.tsx expandable lines theme={null}
> import { useEffect, useRef, useState, useCallback } from 'react';
> import { useCurrentUser } from '@veltdev/react';
> import { useCollaboration } from '@veltdev/codemirror-crdt-react';
> import { EditorState } from '@codemirror/state';
> import { EditorView, basicSetup } from 'codemirror';
> import { javascript } from '@codemirror/lang-javascript';
> import { yCollab } from 'y-codemirror.next';
> import type { Version } from '@veltdev/crdt';
>
> const DEFAULT_INITIAL_CONTENT = 'console.log("Hello CodeMirror CRDT!");';
>
> export const EditorComponent = () => {
> const editorElRef = useRef(null);
> const viewRef = useRef(null);
> const [versions, setVersions] = useState([]);
> const [versionInput, setVersionInput] = useState('');
> const veltUser = useCurrentUser();
>
> const { primitives, isLoading, isSynced, status, error, manager } = useCollaboration({
> editorId: 'my-document-id',
> initialContent: DEFAULT_INITIAL_CONTENT,
> onError: (err) => console.error('Collaboration error:', err),
> });
>
> // Create CodeMirror editor when primitives are ready
> useEffect(() => {
> if (!primitives?.ytext || !editorElRef.current || viewRef.current) return;
>
> const state = EditorState.create({
> doc: primitives.ytext.toString(),
> extensions: [
> basicSetup,
> javascript(),
> EditorView.lineWrapping,
> yCollab(primitives.ytext, primitives.awareness, {
> undoManager: primitives.undoManager,
> }),
> ],
> });
>
> viewRef.current = new EditorView({ state, parent: editorElRef.current });
>
> return () => {
> viewRef.current?.destroy();
> viewRef.current = null;
> };
> }, [primitives]);
>
> // Version management
> const refreshVersions = useCallback(async () => {
> if (!manager) return;
> setVersions(await manager.getVersions());
> }, [manager]);
>
> useEffect(() => { refreshVersions(); }, [manager, refreshVersions]);
>
> const handleSaveVersion = async (e: React.FormEvent) => {
> e.preventDefault();
> if (!manager || !versionInput.trim()) return;
> await manager.saveVersion(versionInput.trim());
> setVersionInput('');
> await refreshVersions();
> };
>
> const handleRestoreVersion = async (versionId: string) => {
> if (!manager) return;
> await manager.restoreVersion(versionId);
> await refreshVersions();
> };
>
> if (error) return Error: {error.message}
;
> if (isLoading || !primitives) return Connecting...
;
>
> return (
>
>
>
> Status: {status} | Synced: {isSynced ? 'Yes' : 'No'}
>
>
>
>
>
> {versions.map((v) => (
>
> {v.versionName}
> handleRestoreVersion(v.versionId)}>
> Restore
>
>
> ))}
>
>
>
> );
> };
> ```
> [tab] Other Frameworks
>
> A complete collaborative CodeMirror editor with SDK initialization, user login, status display, and version management.
>
> **velt.ts**
>
> ```ts Complete velt.ts expandable lines theme={null}
> import { initVelt } from '@veltdev/client';
> import type { Velt } from '@veltdev/types';
>
> let client: Velt | null = null;
> let veltInitialized = false;
>
> const veltInitSubscribers = new Map void>();
>
> async function initializeVelt() {
> client = await initVelt('YOUR_API_KEY');
>
> client.setDocument('my-document-id', { documentName: 'My Document' });
>
> client.getVeltInitState().subscribe((isReady) => {
> veltInitialized = !!isReady;
> if (isReady && client) {
> veltInitSubscribers.forEach((callback) => callback(client));
> }
> });
> }
>
> export const subscribeToVeltInit = (id: string, callback: (velt: Velt) => void) => {
> veltInitSubscribers.set(id, callback);
> if (veltInitialized && client) {
> callback(client);
> }
> };
>
> export async function loginWithUser(userId: string, name: string) {
> await client?.identify({ userId, name });
> }
>
> initializeVelt();
> ```
>
> **editor.ts**
>
> ```ts Complete editor.ts expandable lines theme={null}
> import { EditorState } from '@codemirror/state';
> import { EditorView, basicSetup } from 'codemirror';
> import { javascript } from '@codemirror/lang-javascript';
> import { yCollab } from 'y-codemirror.next';
> import { createCollaboration } from '@veltdev/codemirror-crdt';
> import type { CollaborationManager } from '@veltdev/codemirror-crdt';
> import type { Velt } from '@veltdev/types';
> import { subscribeToVeltInit } from './velt';
>
> let manager: CollaborationManager | null = null;
> let editorView: EditorView | null = null;
>
> async function initEditor(veltClient: Velt) {
> // Create the collaboration manager
> manager = await createCollaboration({
> editorId: 'my-document-id',
> veltClient,
> initialContent: 'Hello CodeMirror CRDT!',
> onError: (error) => console.error('Collaboration error:', error),
> });
>
> // Get Yjs primitives for CodeMirror binding
> const { ytext, awareness, undoManager } = manager.getCollaborationPrimitives();
>
> // Create the CodeMirror editor
> const state = EditorState.create({
> doc: ytext?.toString() ?? '',
> extensions: [
> basicSetup,
> javascript(),
> yCollab(ytext!, awareness, { undoManager }),
> ],
> });
>
> editorView = new EditorView({
> state,
> parent: document.querySelector('#editor')!,
> });
>
> // Wire up status display
> manager.onStatusChange((status) => updateStatus(status, manager!.synced));
> manager.onSynced((synced) => updateStatus(manager!.status, synced));
> }
>
> function updateStatus(status: string, synced: boolean) {
> const el = document.getElementById('status');
> if (!el) return;
>
> if (status === 'connected') {
> el.textContent = synced ? 'Connected & Synced' : 'Connected, syncing...';
> } else if (status === 'connecting') {
> el.textContent = 'Connecting...';
> } else {
> el.textContent = 'Disconnected';
> }
> }
>
> // Wait for SDK to be ready
> subscribeToVeltInit('editor', (velt) => initEditor(velt));
>
> // Version management
> export async function saveVersion(name: string) {
> await manager?.saveVersion(name);
> }
>
> export async function getVersions() {
> return await manager?.getVersions() ?? [];
> }
>
> export async function restoreVersion(versionId: string) {
> await manager?.restoreVersion(versionId);
> }
> ```
>
> **HTML structure**
>
> ```html theme={null}
>
>
>
>
>
> Connecting...
>
>
>
>
>
> ```
>
> **main.ts**
>
> ```ts theme={null}
> import './style.css';
> import './velt';
> import './editor';
> ```
> [tab] React / Next.js Live Demo
>
> [Open Live Demo In Larger Window](https://sample-apps-codemirror-crdt-demo.vercel.app/) | [View Demo Repo](https://github.com/velt-js/sample-apps/tree/main/apps/react/crdt/text-editors/codemirror/codemirror-crdt-demo)
>
> [https://sample-apps-codemirror-crdt-demo.vercel.app/](https://sample-apps-codemirror-crdt-demo.vercel.app/)
> [tab] Non-React Demo
>
> [Open Live Demo In Larger Window](https://sample-apps-codemirror-non-react-cr.vercel.app/) | [View Demo Repo](https://github.com/velt-js/sample-apps/tree/main/apps/javascript/crdt/text-editors/codemirror/codemirror-crdt-demo)
>
> [https://sample-apps-codemirror-non-react-cr.vercel.app/](https://sample-apps-codemirror-non-react-cr.vercel.app/)
## How It Works
1. **`useCollaboration` (React) / `createCollaboration` (non-React)** creates a `CollaborationManager`. This initializes a CRDT Store (`type: 'text'`), a Yjs `Y.Text`, and a `SyncProvider`.
2. **The primitives** (`ytext`, `awareness`, `undoManager`, `doc`) are returned by the hook or via `manager.getCollaborationPrimitives()`. You pass these to `yCollab()` from `y-codemirror.next` as a CodeMirror extension.
3. **User types** -> CodeMirror transaction -> `Y.Text` mutation -> Yjs CRDT broadcasts via Velt backend -> all connected clients see the change.
4. **Remote cursors** are tracked via Yjs Awareness. The `yCollab` extension renders colored cursor indicators at each remote user's selection position.
5. **Initial content** is applied only once for brand-new documents. The manager waits for remote content before deciding the document is new.
6. **Conflict resolution** is handled by Yjs CRDTs, concurrent typing at different positions merges correctly.
7. **Version management** saves the full Yjs state as a named snapshot. Restoring a version replaces the current state and broadcasts to all clients.
8. **Cleanup** is automatic, the manager destroys the editor bindings, store, and all listeners when destroyed or the component unmounts.
## APIs
### React: useCollaboration()
The primary React hook for collaborative CodeMirror editing. Creates a `CollaborationManager`, initializes the CRDT store, and returns collaboration primitives for CodeMirror integration.
* Signature: `useCollaboration(config: UseCollaborationConfig)`
* Params: [UseCollaborationConfig](/docs/api-reference/sdk/models/data-models#usecollaborationconfig-codemirror)
* `editorId`: Unique identifier for this collaborative session.
* `initialContent`: Text content applied once for brand-new documents.
* `debounceMs`: Throttle interval (ms) for backend writes. Default: `0`.
* `forceResetInitialContent`: If `true`, always clear and re-apply `initialContent`. Default: `false`.
* `veltClient`: Explicit Velt client. Falls back to `VeltProvider` context.
* `onError`: Error callback.
* Returns: [UseCollaborationReturn](/docs/api-reference/sdk/models/data-models#usecollaborationreturn-codemirror)
* `primitives`: Yjs primitives for CodeMirror. `null` while loading.
* `isLoading`: `true` until CollaborationManager is initialized.
* `isSynced`: `true` after the initial sync with the backend completes.
* `status`: Connection status: `'connecting'`, `'connected'`, or `'disconnected'`.
* `error`: Most recent error, or `null`.
* `manager`: The underlying `CollaborationManager`. `null` before initialization.
```tsx theme={null}
const { primitives, isLoading, isSynced, status, error, manager } = useCollaboration({
editorId: 'my-codemirror-editor',
initialContent: 'console.log("Hello!");',
onError: (err) => console.error('Collaboration error:', err),
});
```
### Non-React: createCollaboration()
Factory function that creates a `CollaborationManager`, calls `initialize()`, and returns a ready-to-use instance.
* Signature: `createCollaboration(config: CollaborationConfig): Promise`
* Params: [CollaborationConfig](/docs/api-reference/sdk/models/data-models#collaborationconfig-codemirror)
* `editorId`: Unique editor/document identifier for syncing.
* `veltClient`: Velt client instance must have an authenticated user.
* `initialContent`: Plain text content applied once for brand-new documents.
* `debounceMs`: Throttle interval (ms) for backend writes. Default: `0`.
* `onError`: Callback for non-fatal errors.
* `forceResetInitialContent`: If `true`, always reset to `initialContent`. Default: `false`.
* Returns: `Promise`
```js theme={null}
import { createCollaboration } from '@veltdev/codemirror-crdt';
const manager = await createCollaboration({
editorId: 'my-document-id',
veltClient: client,
initialContent: 'Hello world',
onError: (error) => console.error(error),
});
```
### CollaborationPrimitives
The `primitives` object (from the React hook) or `manager.getCollaborationPrimitives()` (non-React) contains everything you need to set up `yCollab()`:
| Property | Type | Description |
| - | - | - |
| `ytext` | `Y.Text \| null` | Y.Text bound to the document. Pass to `yCollab()`. |
| `awareness` | `Awareness` | Awareness instance for cursor/presence tracking. |
| `undoManager` | `Y.UndoManager \| null` | Collaborative undo manager (tracks local changes only). |
| `doc` | `Y.Doc` | Underlying Yjs document. |
### CollaborationManager Methods
Once the `manager` is available (non-null from the hook, or returned from `createCollaboration`), you can use its full API:
#### manager.getCollaborationPrimitives()
Returns the Yjs primitives needed to call `yCollab()`. Non-React only, the React hook returns `primitives` directly.
* Returns: `{ ytext: Y.Text | null, awareness: Awareness, undoManager: Y.UndoManager | null, doc: Y.Doc }`
```js theme={null}
const { ytext, awareness, undoManager } = manager.getCollaborationPrimitives();
```
#### manager.onStatusChange()
Subscribe to connection status changes.
* Signature: `manager.onStatusChange(callback: (status: SyncStatus) => void): Unsubscribe`
* Returns: `Unsubscribe` (call to stop listening)
```js theme={null}
const unsubscribe = manager.onStatusChange((status) => {
console.log('Connection:', status);
});
unsubscribe(); // Stop listening
```
#### manager.onSynced()
Subscribe to sync state changes.
* Signature: `manager.onSynced(callback: (synced: boolean) => void): Unsubscribe`
* Returns: `Unsubscribe`
```js theme={null}
const unsubscribe = manager.onSynced((synced) => {
if (synced) console.log('Initial sync complete');
});
```
#### manager.initialized
Whether `initialize()` has completed.
* Returns: `boolean`
#### manager.synced
Whether initial sync with the backend has completed.
* Returns: `boolean`
#### manager.status
Current connection status.
* Returns: `SyncStatus` (`'connecting' | 'connected' | 'disconnected'`)
#### manager.saveVersion()
Save a named snapshot. Returns the version ID.
* Signature: `manager.saveVersion(name: string): Promise`
* Returns: `Promise`
```js theme={null}
const versionId = await manager.saveVersion('Before major edit');
```
#### manager.getVersions()
List all saved versions.
* Returns: `Promise`
```js theme={null}
const versions = await manager.getVersions();
```
#### manager.restoreVersion()
Restore to a saved version. Returns `true` on success. The restored state is pushed to all connected clients.
* Signature: `manager.restoreVersion(versionId: string): Promise`
* Returns: `Promise`
```js theme={null}
await manager.restoreVersion(versions[0].versionId);
```
#### manager.setStateFromVersion()
Apply a Version object's state locally to the current document.
* Signature: `manager.setStateFromVersion(version: Version): Promise`
* Returns: `Promise`
```js theme={null}
const versions = await manager.getVersions();
const version = versions.find((v) => v.versionId === targetVersionId);
if (version) {
await manager.setStateFromVersion(version);
}
```
#### manager.getDoc()
Get the underlying Yjs document.
* Returns: `Y.Doc`
```js theme={null}
const doc = manager.getDoc();
```
#### manager.getText() / manager.getYText()
Get the Y.Text bound to the document content. In React, this method is called `getText()`; in non-React, it is called `getYText()`.
* Returns: `Y.Text | null`
```js theme={null}
const text = manager.getText(); // React
const ytext = manager.getYText(); // Non-React
```
#### manager.getProvider()
Get the sync provider.
* Returns: `SyncProvider`
```js theme={null}
const provider = manager.getProvider();
```
#### manager.getAwareness()
Get the Yjs Awareness instance.
* Returns: `Awareness`
```js theme={null}
const awareness = manager.getAwareness();
```
#### manager.getStore()
Get the core CRDT Store.
* Returns: `Store`
```js theme={null}
const crdtStore = manager.getStore();
```
#### manager.getUndoManager()
Get the Y.UndoManager for undo/redo operations.
* Returns: `Y.UndoManager | null`
```js theme={null}
const undoManager = manager.getUndoManager();
```
#### manager.destroy()
Full cleanup (automatic on editor destroy or component unmount). Safe to call multiple times.
* Returns: `void`
```js theme={null}
manager.destroy();
```
## Migration Guide: v1 to v2
### React
#### Overview
The v2 API replaces `useVeltCodeMirrorCrdtExtension()` with `useCollaboration()`. The new hook provides richer reactive state (status, sync, error), returns Yjs primitives directly, and exposes the `CollaborationManager` for advanced use.
#### Key Changes
| Aspect | v1 (deprecated) | v2 (current) |
| - | - | - |
| Entry point | `useVeltCodeMirrorCrdtExtension(config)` | `useCollaboration(config)` |
| Yjs access | `store.getYText()`, `store.getAwareness()` | `primitives.ytext`, `primitives.awareness` |
| Undo manager | `store.getUndoManager()` | `primitives.undoManager` |
| Manager access | `store` (VeltCodeMirrorStore) | `manager` (CollaborationManager) |
| Version management | `store.saveVersion()`, `store.getVersions()` | `manager.saveVersion()`, `manager.getVersions()` |
| Status tracking | Not available | `status`, `isSynced` (reactive state) |
| Error handling | Not available | `onError` callback + `error` state |
| Cleanup | Automatic on unmount | Automatic on unmount |
#### Step-by-Step
**1. Replace the hook:**
```tsx theme={null}
// Before (v1)
import { useVeltCodeMirrorCrdtExtension } from '@veltdev/codemirror-crdt-react';
const { store, isLoading } = useVeltCodeMirrorCrdtExtension({ editorId: 'my-doc' });
// After (v2)
import { useCollaboration } from '@veltdev/codemirror-crdt-react';
const { primitives, isLoading, isSynced, status, error, manager } = useCollaboration({
editorId: 'my-doc',
onError: (err) => console.error(err),
});
```
**2. Replace editor creation:**
```tsx theme={null}
// Before (v1): store.getYText(), store.getAwareness(), store.getUndoManager()
// After (v2): primitives.ytext, primitives.awareness, primitives.undoManager
```
**3. Replace version management:**
```tsx theme={null}
// Before (v1): store.getVersions(), store.setStateFromVersion(version)
// After (v2): manager.getVersions(), manager.restoreVersion(versionId)
```
**4. Add status monitoring (new in v2):**
```tsx theme={null}
if (error) return Error: {error.message}
;
if (isLoading) return Connecting...
;
Status: {status} | Synced: {isSynced ? 'Yes' : 'No'}
```
### Non-React
#### Overview
The v2 API replaces the callback-based `createVeltCodeMirrorCrdtExtension()` with an async `createCollaboration()` factory that returns a `CollaborationManager`.
#### Key Changes
| Aspect | v1 (deprecated) | v2 (current) |
| - | - | - |
| Entry point | `createVeltCodeMirrorCrdtExtension(config, callback)` | `await createCollaboration(config)` |
| Return value | Cleanup function | `CollaborationManager` instance |
| Yjs primitives | Via callback: `store.getYText()`, `store.getAwareness()` | Via method: `manager.getCollaborationPrimitives()` |
| Store access | Via callback: `response.store` | Via method: `manager.getStore()` |
| Version management | `store.getEncodedState()`, `store.setStateFromVersion()` | `manager.saveVersion()`, `manager.getVersions()` |
| Status tracking | Not available | `manager.onStatusChange()`, `manager.onSynced()` |
| Cleanup | Call returned cleanup function | `manager.destroy()` |
| Error handling | `onConnectionError` callback | `onError` callback |
| Sync notification | `onSynced` callback (fires once) | `manager.onSynced()` (subscribable) |
#### Step-by-Step
**1. Replace the store creation:**
```js theme={null}
// Before (v1)
import { createVeltCodeMirrorCrdtExtension } from '@veltdev/codemirror-crdt';
const cleanup = createVeltCodeMirrorCrdtExtension(
{ editorId: 'my-doc', veltClient: client },
({ store }) => {
const state = EditorState.create({
doc: store.getYText()?.toString() ?? '',
extensions: [basicSetup, yCollab(store.getYText()!, store.getAwareness(), { undoManager: store.getUndoManager() })],
});
new EditorView({ state, parent: document.querySelector('#editor') });
}
);
// After (v2)
import { createCollaboration } from '@veltdev/codemirror-crdt';
const manager = await createCollaboration({ editorId: 'my-doc', veltClient: client });
const { ytext, awareness, undoManager } = manager.getCollaborationPrimitives();
const state = EditorState.create({
doc: ytext.toString(),
extensions: [basicSetup, yCollab(ytext, awareness, { undoManager })],
});
new EditorView({ state, parent: document.querySelector('#editor') });
```
**2. Replace version management:**
```js theme={null}
// Before (v1): store.getEncodedState(), store.setStateFromVersion(version)
// After (v2): manager.saveVersion('v1'), manager.restoreVersion(versionId)
```
**3. Replace cleanup:**
```js theme={null}
// Before (v1): cleanup()
// After (v2): manager.destroy()
```
**4. Add status monitoring (new in v2):**
```js theme={null}
manager.onStatusChange((status) => console.log('Status:', status));
manager.onSynced((synced) => console.log('Synced:', synced));
```
**5. Access Yjs internals:**
```js theme={null}
// Before (v1): store.getYDoc(), store.getYText(), store.getAwareness(), store.getUndoManager()
// After (v2): manager.getDoc(), manager.getYText(), manager.getAwareness(), manager.getUndoManager(), manager.getProvider()
```
## Legacy API (v1)
> [!WARNING]
>
> The v1 API is deprecated. Use the v2 `useCollaboration` hook (React) or `createCollaboration` (non-React) for all new integrations. The v1 API is still exported for backward compatibility.
### React: useVeltCodeMirrorCrdtExtension() (deprecated)
A React hook that returns a store for CodeMirror integration. Internally delegates to `useCollaboration` (v2) via a compatibility wrapper.
* Signature: `useVeltCodeMirrorCrdtExtension(config: VeltCodeMirrorCrdtExtensionConfig)`
* Params: [VeltCodeMirrorCrdtExtensionConfig](/docs/api-reference/sdk/models/data-models#veltcodemirrorcrdtextensionconfig-deprecated)
* Returns: [VeltCodeMirrorCrdtExtensionResponse](/docs/api-reference/sdk/models/data-models#veltcodemirrorcrdtextensionresponse-deprecated)
```tsx theme={null}
import { useVeltCodeMirrorCrdtExtension } from '@veltdev/codemirror-crdt-react';
const { store, isLoading } = useVeltCodeMirrorCrdtExtension({
editorId: 'my-document-id',
initialContent: 'console.log("Hello!");',
});
// Use store to create CodeMirror extensions
if (store) {
const state = EditorState.create({
doc: store.getYText()?.toString() ?? '',
extensions: [
basicSetup,
yCollab(store.getYText()!, store.getAwareness(), {
undoManager: store.getUndoManager(),
}),
],
});
}
```
### React: VeltCodeMirrorCrdtExtensionConfig (deprecated)
| Property | Type | Required | Description |
| - | - | - | - |
| `editorId` | `string` | Yes | Unique editor identifier. |
| `initialContent` | `string` | No | Text content for new documents. |
| `debounceMs` | `number` | No | Throttle interval (ms). |
| `veltClient` | `Velt` | No | Velt client instance. |
### React: VeltCodeMirrorCrdtExtensionResponse (deprecated)
| Property | Type | Description |
| - | - | - |
| `store` | `VeltCodeMirrorStore \| null` | Store instance for editor and version management. |
| `isLoading` | `boolean` | `true` until the store is ready. |
### Non-React: createVeltCodeMirrorCrdtExtension() (deprecated)
Creates a collaboration store using a callback-based pattern. The function subscribes to the Velt SDK lifecycle and invokes the `onReady` callback when the store is ready.
* Signature: `createVeltCodeMirrorCrdtExtension(config: VeltCodeMirrorStoreConfig, onReady: (response) => void): () => void`
* Returns: `() => void` (cleanup function)
```js theme={null}
import { createVeltCodeMirrorCrdtExtension } from '@veltdev/codemirror-crdt';
const cleanup = createVeltCodeMirrorCrdtExtension(
{
editorId: 'my-document-id',
veltClient: client,
initialContent: 'Hello world',
},
({ store }) => {
if (store) {
const state = EditorState.create({
doc: store.getYText()?.toString() ?? '',
extensions: [
basicSetup,
yCollab(store.getYText()!, store.getAwareness(), { undoManager: store.getUndoManager() }),
],
});
new EditorView({ state, parent: document.querySelector('#editor') });
}
}
);
// Call cleanup() to tear down
cleanup();
```
### Non-React: VeltCodeMirrorStoreConfig (deprecated)
| Property | Type | Required | Description |
| - | - | - | - |
| `editorId` | `string` | Yes | Unique editor identifier. |
| `initialContent` | `string` | No | Text content for new documents. |
| `debounceMs` | `number` | No | Throttle interval (ms). |
| `onSynced` | `(doc?: Y.Doc) => void` | No | Called once when initial sync completes. |
| `onConnectionError` | `(error: Error) => void` | No | Called on connection errors. |
| `veltClient` | `Velt` | No | Velt client instance. |
### Non-React: VeltCodeMirrorCrdtExtensionResponse (deprecated)
| Property | Type | Description |
| - | - | - |
| `store` | `VeltCodeMirrorStore \| null` | Store instance for Yjs access and versions. |
| `error` | `string \| null` | Error message if initialization failed. |
### VeltCodeMirrorStore Methods (deprecated)
| Method | Returns | Description |
| - | - | - |
| `getStore()` | `Store` | Get the core CRDT Store. |
| `getYText()` | `Y.Text \| null` | Get the Yjs Text instance. |
| `getYDoc()` | `Y.Doc` | Get the Yjs Doc. |
| `getUndoManager()` | `Y.UndoManager \| null` | Get the Yjs UndoManager. |
| `getAwareness()` | `Awareness` | Get the Awareness instance. |
| `getEncodedState()` | `number[]` | Get encoded Y.Doc state for versioning. |
| `isConnected()` | `boolean` | Check if connected to backend. |
| `setStateFromVersion(v)` | `Promise` | Apply a version's state. |
| `destroy()` | `void` | Clean up all resources. |
# Core Setup
Source: https://velt.dev/docs/realtime-collaboration/crdt/setup/core
Setup Multiplayer Editing for any frameworks or custom implementations.
## Introduction
Use these guides to add Yjs-based CRDT to your project with Velt. The core library supports multiple store types — pick the one that matches your data shape. Use the React Hook wrapper for the fastest integration in React apps, or the core library for other frameworks and custom implementations.
## Setup
### Step 1: Install Dependencies
> [tab] React / Next.js
>
> ```bash theme={null}
> npm install @veltdev/crdt-react @veltdev/crdt @veltdev/react
> ```
> [tab] Other Frameworks
>
> ```bash theme={null}
> npm install @veltdev/crdt @veltdev/client
> ```
### Step 2: Initialize Velt in your app
Initialize the Velt client and set the document context. This is required for the collaboration engine to work.
> [tab] React / Next.js
>
> Wrap your app with `VeltProvider` and use `useSetDocument` to scope the collaborative session. Follow the [Velt Setup Docs](/docs/get-started/quickstart) for full setup.
>
> ```tsx theme={null}
> import { VeltProvider, useSetDocument } from '@veltdev/react';
>
> function App() {
> return (
>
>
>
> );
> }
>
> function YourApp() {
> useSetDocument('my-document-id', { documentName: 'My Document' });
> return ;
> }
> ```
> [tab] Other Frameworks
>
> Initialize the Velt SDK with `initVelt()`, set the document context, and authenticate a user.
>
> ```js theme={null}
> import { initVelt } from '@veltdev/client';
>
> const client = await initVelt('YOUR_API_KEY');
>
> // Set the document scope
> client.setDocument('my-document-id', { documentName: 'My Document' });
>
> // Authenticate a user
> await client.identify({
> userId: 'user-1',
> name: 'John Doe',
> email: 'john@example.com',
> });
>
> // Wait for the SDK to be ready
> client.getVeltInitState().subscribe((isReady) => {
> if (isReady) {
> initializeStore(client);
> }
> });
> ```
### Step 3: Choose a store type
Each store type maps to a Yjs shared data structure. Pick the one that matches your use case and follow its setup guide:
> [card] [Array Store](/docs/realtime-collaboration/crdt/setup/core-stores/array)
>
> Collaborative ordered lists — todo apps, item collections, ordered datasets.
> [card] [Map Store](/docs/realtime-collaboration/crdt/setup/core-stores/map)
>
> Collaborative key-value pairs — settings, metadata, configuration objects.
> [card] [Text Store](/docs/realtime-collaboration/crdt/setup/core-stores/text)
>
> Collaborative plain text — notepads, code editors, text fields.
> [card] [XML Store](/docs/realtime-collaboration/crdt/setup/core-stores/xml)
>
> Collaborative XML/tree data — outlines, structured documents, custom tree editors.
### Step 4: Event subscriptions (optional)
> [tab] React / Next.js
>
> Use the `useCrdtEventCallback` hook to listen for CRDT events:
>
> ```jsx theme={null}
> import { useCrdtEventCallback } from '@veltdev/react';
>
> function YourComponent() {
> const updateDataEvent = useCrdtEventCallback('updateData');
>
> useEffect(() => {
> if (updateDataEvent) {
> console.log('CRDT data updated:', updateDataEvent);
> }
> }, [updateDataEvent]);
> }
> ```
> [tab] Other Frameworks
>
> Use `getCrdtElement().on()` to listen for CRDT events like `updateData`, which fires whenever the store data is synced.
>
> ```js theme={null}
> const crdtElement = client.getCrdtElement();
>
> crdtElement.on('updateData').subscribe((event) => {
> if (event) {
> console.log('CRDT data updated:', event);
> }
> });
> ```
### Step 5: Custom encryption (optional)
> [tab] React / Next.js
>
> Pass a custom `VeltEncryptionProvider` to `VeltProvider` to encrypt/decrypt CRDT state before it is stored on the backend.
>
> ```tsx theme={null}
> import { VeltProvider } from '@veltdev/react';
> import { VeltEncryptionProvider } from '@veltdev/types';
>
> const encryptionProvider: VeltEncryptionProvider = {
> encrypt: async (config) => {
> return config.data.map((num) => num.toString()).join('__');
> },
> decrypt: async (config) => {
> return config.data.split('__').map((str) => parseInt(str, 10));
> },
> };
>
> function App() {
> return (
>
>
>
> );
> }
> ```
> [tab] Other Frameworks
>
> Call `client.setEncryptionProvider()` to encrypt/decrypt CRDT state before it is stored on the backend.
>
> ```js theme={null}
> const encryptionProvider = {
> encrypt: async (config) => {
> return config.data.map((num) => num.toString()).join('__');
> },
> decrypt: async (config) => {
> return config.data.split('__').map((str) => parseInt(str, 10));
> },
> };
>
> client.setEncryptionProvider(encryptionProvider);
> ```
See also: [setEncryptionProvider()](/docs/api-reference/sdk/api/api-methods#setencryptionprovider-encryptionprovider)
· [VeltEncryptionProvider](/docs/api-reference/sdk/models/data-models#veltencryptionprovider)
· [EncryptConfig](/docs/api-reference/sdk/models/data-models#encryptconfig)
· [DecryptConfig](/docs/api-reference/sdk/models/data-models#decryptconfig)
## APIs
### React: useStore()
React hook that creates and manages a CRDT store. Handles initialization, real-time subscriptions, and cleanup automatically.
* Signature: `useStore(config: UseStoreConfig)`
* Params:
* `storeId`: Unique document identifier.
* `type`: Yjs data type: `'text'`, `'map'`, `'array'`, `'xml'`, or `'xmltext'`.
* `initialValue`: Initial value applied if remote state is empty.
* `debounceMs`: Throttle interval (ms) for backend writes. Default: `0`.
* `enablePresence`: Enable presence tracking. Default: `true`.
* `forceResetInitialContent`: If `true`, always reset to `initialValue` on init. Default: `false`.
* `onError`: Error callback.
* `veltClient`: Explicit Velt client. Falls back to `VeltProvider` context.
* Returns: `UseStoreReturn`
* `value`: Current store value, reactively updated.
* `update`: Replace the entire store value.
* `store`: Underlying store instance for advanced use.
* `isLoading`: `true` while the store is initializing.
* `isSynced`: `true` when the store is connected and synced.
* `status`: Connection status: `'connecting'`, `'connected'`, or `'disconnected'`.
* `error`: Error object if initialization failed.
* `versions`: List of saved versions.
* `saveVersion`: Save a named snapshot.
* `getVersions`: List all saved versions.
* `getVersionById`: Get a specific version by ID.
* `restoreVersion`: Restore to a saved version.
* `setStateFromVersion`: Apply a version's state to the document.
```tsx theme={null}
import { useStore } from '@veltdev/crdt-react';
const {
value,
update,
store,
isLoading,
isSynced,
status,
error,
saveVersion,
getVersions,
getVersionById,
restoreVersion,
setStateFromVersion,
} = useStore- ({
storeId: 'my-array-store',
type: 'array', // can be 'array', 'map', 'text', 'xml', or 'xmltext'
initialValue: [],
});
```
### React: useAwareness()
React hook that wraps the Yjs Awareness instance from a store, providing reactive remote peer states and a stable setter for local awareness state.
* Params: `store: Store
| null` — The store instance from `useStore()` (safe to pass `null`)
* Returns: `UseAwarenessReturn`
* `remoteStates`: Awareness states of all remote peers.
* `localState`: Current local awareness state.
* `setLocalState`: Set or clear the local awareness state.
```tsx theme={null}
import { useStore, useAwareness } from '@veltdev/crdt-react';
const { store } = useStore- ({ storeId: 'my-store', type: 'array', initialValue: [] });
const { remoteStates, localState, setLocalState } = useAwareness(store);
setLocalState({
user: { userId: 'user-1', name: 'John', color: '#ff0000' },
cursor: { anchor: 0, head: 5 },
});
```
### Non-React: createVeltStore()
Convenience factory that creates a `Store`, calls `initialize()`, and returns it. Returns `null` if initialization fails.
* Params: [StoreConfig](/docs/api-reference/sdk/models/data-models#storeconfig)
* `id`: Unique document identifier.
* `type`: Yjs data type: `'text'`, `'map'`, `'array'`, or `'xml'`.
* `initialValue`: Initial value applied if remote state is empty.
* `veltClient`: Velt client instance (from `initVelt()`). Required for sync.
* `debounceMs`: Throttle interval (ms) for backend writes. Default: `0`.
* `enablePresence`: Enable presence tracking. Default: `true`.
* `forceResetInitialContent`: If `true`, always reset to `initialValue` on init. Default: `false`.
* `contentKey`: Content key for Yjs shared types. Default: `'content'`.
* `userId`: User identifier for update attribution.
* `collection`: Collection/namespace for document grouping.
* `logLevel`: Log level: `'silent'`, `'error'`, `'warn'`, `'debug'`. Default: `'error'`.
* Returns: `Promise
| null>`
```js theme={null}
const store = await createVeltStore({
id: 'my-array-store',
type: 'array',
initialValue: [{ id: '1', name: 'First item' }],
veltClient: client,
});
```
### Store Methods
These methods are available on the `store` instance (from `useStore` or `createVeltStore`):
#### update()
Update the store value and sync to peers.
* Params: `newValue: T`
* Returns: `void`
```ts theme={null}
store.update('New Value');
```
#### getValue()
Get the current store value. For map stores, returns the `toJSON()` representation of the underlying Y.Map as a plain JavaScript object.
* Returns: `T`
```ts theme={null}
const value = store.getValue();
```
#### subscribe()
Subscribe to changes in the store.
* Params: `(newValue: T) => void`
* Returns: `() => void` (unsubscribe function)
```ts theme={null}
const unsubscribe = store.subscribe((newValue) => {
console.log('Updated value:', newValue);
});
```
#### destroy()
Clean up resources when done with the store. Automatic in React via the hook.
* Returns: `void`
```ts theme={null}
store.destroy();
```
#### getDoc()
Get the underlying Yjs document.
* Returns: `Y.Doc`
```ts theme={null}
const ydoc = store.getDoc();
```
#### getProvider()
Get the provider instance for the store.
* Returns: `Provider`
```ts theme={null}
const provider = store.getProvider();
```
#### getText()
Get the Y.Text instance if store type is 'text'.
* Returns: `Y.Text | null`
```ts theme={null}
const ytext = store.getText();
```
#### getXml()
Get the Y.XmlFragment instance if store type is 'xml'.
* Returns: `Y.XmlFragment | null`
```ts theme={null}
const yxml = store.getXml();
```
#### getAwareness()
Get the Awareness instance for cursor/presence tracking.
* Returns: `Awareness`
```ts theme={null}
const awareness = store.getAwareness();
```
### Version Methods
Available on both the `useStore` hook return and the `store` instance:
#### saveVersion()
Save a snapshot of the current state as a named version.
* Params: `versionName: string`
* Returns: `Promise`
```ts theme={null}
const versionId = await saveVersion('Checkpoint');
```
#### getVersions()
Fetch all saved versions.
* Returns: `Promise`
```ts theme={null}
const versions = await getVersions();
```
#### getVersionById()
Fetch a specific version by ID.
* Params: `versionId: string`
* Returns: `Promise`
```ts theme={null}
const version = await getVersionById('abc123');
```
#### restoreVersion()
Restore the store to a specific version using its ID.
* Params: `versionId: string`
* Returns: `Promise`
```ts theme={null}
await restoreVersion('abc123');
```
#### setStateFromVersion()
Restore the store state from a specific version object.
* Params: `version: Version`
* Returns: `Promise`
```ts theme={null}
await setStateFromVersion(version);
```
### Custom Encryption
Encrypt CRDT data before it's stored in Velt by registering a custom encryption provider. For CRDT methods, input data is of type `Uint8Array | number[]`.
> [tab] React / Next.js
>
> ```tsx theme={null}
> import { VeltProvider } from '@veltdev/react';
> import { VeltEncryptionProvider } from '@veltdev/types';
>
> const encryptionProvider: VeltEncryptionProvider = {
> encrypt: async (config) => {
> return config.data.map((num) => num.toString()).join('__');
> },
> decrypt: async (config) => {
> return config.data.split('__').map((str) => parseInt(str, 10));
> },
> };
>
> function App() {
> return (
>
>
>
> );
> }
> ```
> [tab] Other Frameworks
>
> ```js theme={null}
> const encryptionProvider = {
> encrypt: async (config) => {
> return config.data.map((num) => num.toString()).join('__');
> },
> decrypt: async (config) => {
> return config.data.split('__').map((str) => parseInt(str, 10));
> },
> };
>
> client.setEncryptionProvider(encryptionProvider);
> ```
See also: [setEncryptionProvider()](/docs/api-reference/sdk/api/api-methods#setencryptionprovider-encryptionprovider)
· [VeltEncryptionProvider](/docs/api-reference/sdk/models/data-models#veltencryptionprovider)
· [EncryptConfig](/docs/api-reference/sdk/models/data-models#encryptconfig)
· [DecryptConfig](/docs/api-reference/sdk/models/data-models#decryptconfig)
### CRDT Event Subscriptions
#### [on](/docs/api-reference/sdk/api/api-methods#on)
Subscribe to CRDT events. Currently supports the `updateData` event which fires when CRDT data changes.
* Params: `eventType: "updateData"`
* Returns: `Observable<`[`CrdtUpdateDataEvent`](/docs/api-reference/sdk/models/data-models#crdtupdatedataevent)`>`
> [tab] React / Next.js
>
> **Using Hook:**
>
> ```jsx theme={null}
> import { useCrdtEventCallback } from "@veltdev/react";
>
> export function YourComponent() {
> const crdtUpdateData = useCrdtEventCallback("updateData");
>
> useEffect(() => {
> console.log("[CRDT] event on data change: ", crdtUpdateData);
> }, [crdtUpdateData]);
>
> return Your Component
;
> }
> ```
>
> **Using API:**
>
> ```jsx theme={null}
> import { useVeltClient } from "@veltdev/react";
>
> export function YourComponent() {
> const { client } = useVeltClient();
>
> useEffect(() => {
> if (!client) return;
> const crdtElement = client.getCrdtElement();
> const subscription = crdtElement.on("updateData").subscribe((eventData) => {
> console.log("[CRDT] event on data change: ", eventData);
> });
> return () => subscription.unsubscribe();
> }, [client]);
>
> return Your Component
;
> }
> ```
> [tab] Other Frameworks
>
> ```html theme={null}
>
> ```
### Low-Level Message APIs
These APIs provide direct access to the CRDT message stream for custom implementations.
#### [pushMessage()](/docs/api-reference/sdk/api/api-methods#pushmessage)
Push a raw Yjs message into the unified message stream.
* Params: [`CrdtPushMessageQuery`](/docs/api-reference/sdk/models/data-models#crdtpushmessagequery)
* Returns: `Promise`
> [tab] React / Next.js
>
> ```jsx theme={null}
> const crdtElement = client.getCrdtElement();
>
> await crdtElement.pushMessage({
> id: 'my-doc',
> data: Array.from(update),
> yjsClientId: ydoc.clientID,
> messageType: 'sync',
> source: 'tiptap',
> });
> ```
> [tab] Other Frameworks
>
> ```js theme={null}
> const crdtElement = Velt.getCrdtElement();
>
> await crdtElement.pushMessage({
> id: 'my-doc',
> data: Array.from(update),
> yjsClientId: ydoc.clientID,
> messageType: 'sync',
> source: 'tiptap',
> });
> ```
#### [onMessage()](/docs/api-reference/sdk/api/api-methods#onmessage)
Subscribe to incoming messages on the unified message stream. Returns an unsubscribe function.
* Params: [`CrdtOnMessageQuery`](/docs/api-reference/sdk/models/data-models#crdtonmessagequery)
* Returns: `() => void`
> [tab] React / Next.js
>
> ```jsx theme={null}
> const crdtElement = client.getCrdtElement();
>
> const unsubscribe = crdtElement.onMessage({
> id: 'my-doc',
> callback: (msg) => {
> Y.applyUpdate(ydoc, new Uint8Array(msg.data));
> },
> });
>
> unsubscribe();
> ```
> [tab] Other Frameworks
>
> ```js theme={null}
> const crdtElement = Velt.getCrdtElement();
>
> const unsubscribe = crdtElement.onMessage({
> id: 'my-doc',
> callback: (msg) => {
> Y.applyUpdate(ydoc, new Uint8Array(msg.data));
> },
> });
>
> unsubscribe();
> ```
#### [getMessages()](/docs/api-reference/sdk/api/api-methods#getmessages)
Retrieve historical messages from the unified message stream.
* Params: [`CrdtGetMessagesQuery`](/docs/api-reference/sdk/models/data-models#crdtgetmessagesquery)
* Returns: [`Promise`](/docs/api-reference/sdk/models/data-models#crdtmessagedata)
> [tab] React / Next.js
>
> ```jsx theme={null}
> const crdtElement = client.getCrdtElement();
>
> const messages = await crdtElement.getMessages({
> id: 'my-doc',
> afterTs: snapshot?.timestamp ?? 0,
> });
> for (const msg of messages) {
> Y.applyUpdate(ydoc, new Uint8Array(msg.data));
> }
> ```
> [tab] Other Frameworks
>
> ```js theme={null}
> const crdtElement = Velt.getCrdtElement();
>
> const messages = await crdtElement.getMessages({
> id: 'my-doc',
> afterTs: snapshot?.timestamp ?? 0,
> });
> for (const msg of messages) {
> Y.applyUpdate(ydoc, new Uint8Array(msg.data));
> }
> ```
#### [getSnapshot()](/docs/api-reference/sdk/api/api-methods#getsnapshot)
Retrieve the latest CRDT state snapshot for a document.
* Params: [`CrdtGetSnapshotQuery`](/docs/api-reference/sdk/models/data-models#crdtgetsnapshotquery)
* Returns: [`Promise`](/docs/api-reference/sdk/models/data-models#crdtsnapshotdata)
> [tab] React / Next.js
>
> ```jsx theme={null}
> const crdtElement = client.getCrdtElement();
>
> const snapshot = await crdtElement.getSnapshot({ id: 'my-doc' });
> if (snapshot?.state) {
> Y.applyUpdate(ydoc, new Uint8Array(snapshot.state));
> }
> ```
> [tab] Other Frameworks
>
> ```js theme={null}
> const crdtElement = Velt.getCrdtElement();
>
> const snapshot = await crdtElement.getSnapshot({ id: 'my-doc' });
> if (snapshot?.state) {
> Y.applyUpdate(ydoc, new Uint8Array(snapshot.state));
> }
> ```
#### [saveSnapshot()](/docs/api-reference/sdk/api/api-methods#savesnapshot)
Persist a CRDT state snapshot for a document.
* Params: [`CrdtSaveSnapshotQuery`](/docs/api-reference/sdk/models/data-models#crdtsavesnapshotquery)
* Returns: `Promise`
> [tab] React / Next.js
>
> ```jsx theme={null}
> const crdtElement = client.getCrdtElement();
>
> await crdtElement.saveSnapshot({
> id: 'my-doc',
> state: Y.encodeStateAsUpdate(ydoc),
> vector: Y.encodeStateVector(ydoc),
> source: 'tiptap',
> });
> ```
> [tab] Other Frameworks
>
> ```js theme={null}
> const crdtElement = Velt.getCrdtElement();
>
> await crdtElement.saveSnapshot({
> id: 'my-doc',
> state: Y.encodeStateAsUpdate(ydoc),
> vector: Y.encodeStateVector(ydoc),
> source: 'tiptap',
> });
> ```
#### [pruneMessages()](/docs/api-reference/sdk/api/api-methods#prunemessages)
Delete historical messages older than a given timestamp from the message stream.
* Params: [`CrdtPruneMessagesQuery`](/docs/api-reference/sdk/models/data-models#crdtprunemessagesquery)
* Returns: `Promise`
> [tab] React / Next.js
>
> ```jsx theme={null}
> const crdtElement = client.getCrdtElement();
>
> await crdtElement.pruneMessages({
> id: 'my-doc',
> beforeTs: Date.now() - 24 * 60 * 60 * 1000,
> });
> ```
> [tab] Other Frameworks
>
> ```js theme={null}
> const crdtElement = Velt.getCrdtElement();
>
> await crdtElement.pruneMessages({
> id: 'my-doc',
> beforeTs: Date.now() - 24 * 60 * 60 * 1000,
> });
> ```
## Migration Guide: v1 to v2
### React
#### Overview
The v2 API replaces `useVeltCrdtStore()` with `useStore()`. The new hook uses `storeId` instead of `id`, adds reactive `status`/`isSynced`/`error` state, and supports `forceResetInitialContent`.
#### Key Changes
| Aspect | v1 (deprecated) | v2 (current) |
| - | - | - |
| Entry point | `useVeltCrdtStore(config)` | `useStore(config)` |
| Store ID field | `id` | `storeId` |
| Status tracking | Not available | `isLoading`, `isSynced`, `status` |
| Error handling | Not available | `onError` callback + `error` state |
| Force reset | Not available | `forceResetInitialContent` |
| Version management | Same methods | Same methods |
| Cleanup | Automatic on unmount | Automatic on unmount |
#### Step-by-Step
**1. Replace the hook:**
```tsx theme={null}
// Before (v1)
import { useVeltCrdtStore } from '@veltdev/crdt-react';
const { value, update, store } = useVeltCrdtStore({ id: 'my-doc', type: 'text' });
// After (v2)
import { useStore } from '@veltdev/crdt-react';
const { value, update, store, isLoading, isSynced, status, error } = useStore({
storeId: 'my-doc',
type: 'text',
onError: (err) => console.error(err),
});
```
**2. Add status monitoring (new in v2):**
```tsx theme={null}
if (isLoading) return Loading...
;
if (error) return Error: {error.message}
;
```
## Legacy API (v1)
> [!WARNING]
>
> The v1 `useVeltCrdtStore` hook is deprecated. Use the v2 `useStore` hook for all new React integrations. The non-React `createVeltStore` API remains unchanged.
### useVeltCrdtStore() (deprecated)
React hook to create and sync a collaborative CRDT store. Internally delegates to `useStore` (v2) via a compatibility wrapper.
* Signature: `useVeltCrdtStore(config)`
* Params:
* `id`: Unique identifier for the store.
* `type`: Type of Yjs data structure (`'text'` | `'array'` | `'map'` | `'xml'`).
* `initialValue`: Optional initial value for the store.
* `debounceMs`: Optional debounce time for update propagation (ms).
* `enablePresence`: Optional boolean to enable realtime presence tracking (default: `true`).
* Returns: Store properties and methods (`value`, `update`, `store`, `versions`, `saveVersion`, `getVersions`, `getVersionById`, `restoreVersion`, `setStateFromVersion`)
```jsx theme={null}
import { useVeltCrdtStore } from '@veltdev/crdt-react';
const {
value,
versions,
store,
update,
saveVersion,
getVersions,
getVersionById,
restoreVersion,
setStateFromVersion,
} = useVeltCrdtStore({
id: 'my-collab-note',
type: 'text',
initialValue: 'Hello, world!',
});
```
## Debugging
Use the Velt Chrome Extension or the `window.VeltCrdtStoreMap` debugging interface to inspect and monitor your CRDT stores.
### window\.VeltCrdtStoreMap
`window.VeltCrdtStoreMap` is a global debugging interface that exposes all active CRDT stores in your application. It's automatically created and maintained by the Velt CRDT library.
#### [get()](/docs/api-reference/sdk/api/api-methods#get)
Get a store by its ID.
* Params:
* `id` (optional): Store ID. If omitted, returns the first registered store.
* Returns: `VeltCrdtStore | undefined`
* **Store object methods:**
* `getValue()`: Get the current value from the store
* `subscribe(callback: (value: any) => void)`: Subscribe to changes. Returns an unsubscribe function.
> [tab] Basic Usage
>
> ```jsx theme={null}
> // Get a specific store
> const store = window.VeltCrdtStoreMap.get('my-store-id');
> if (store) {
> console.log('Current value:', store.getValue());
> }
>
> // Get the first registered store
> const firstStore = window.VeltCrdtStoreMap.get();
> ```
> [tab] Inspect Store
>
> ```jsx theme={null}
> const store = window.VeltCrdtStoreMap.get('editor-123');
>
> if (store) {
> console.log('Current value:', store.getValue());
>
> store.subscribe((value) => {
> console.log('Value updated:', value);
> });
>
> setInterval(() => {
> console.log('Current value:', store.getValue());
> }, 5000);
> }
> ```
# Array Store
Source: https://velt.dev/docs/realtime-collaboration/crdt/setup/core-stores/array
Add real-time collaborative lists and collections to your application using Velt CRDT.
> [!NOTE]
>
> Complete [Steps 1-2](/docs/realtime-collaboration/crdt/setup/core#setup) on the Core setup page before continuing. Those steps install dependencies and initialize Velt.
## Setup
### Step 1: Create a CRDT array store
> [tab] React / Next.js
>
> Use the `useStore` hook to create a CRDT store backed by a Yjs `Y.Array`. The hook handles store initialization, React lifecycle, and real-time subscriptions automatically — no manual `useState`/`useEffect` needed for store setup.
>
> ```tsx theme={null}
> import { useStore } from '@veltdev/crdt-react';
>
> interface Item {
> id: string;
> name: string;
> }
>
> function Component() {
> const {
> value: items,
> update: updateItems,
> store,
> isLoading,
> isSynced,
> status,
> error,
> } = useStore- ({
> storeId: 'my-array-store',
> type: 'array',
> initialValue: [{ id: '1', name: 'First item' }],
> });
>
> if (isLoading) return
Loading...
;
> if (error) return Error: {error.message}
;
>
> const itemList = Array.isArray(items) ? items : [];
>
> return (
>
> {itemList.map((item) => (
> {item.name}
> ))}
>
> );
> }
> ```
> [tab] Other Frameworks
>
> Use `createVeltStore` to create a CRDT store backed by a Yjs `Y.Array`. The `initialValue` is only applied when the document is brand-new (no prior remote state exists).
>
> ```js theme={null}
> import { createVeltStore } from '@veltdev/crdt';
>
> async function initializeStore(client) {
> const store = await createVeltStore({
> id: 'my-array-store',
> type: 'array',
> initialValue: [{ id: '1', name: 'First item' }],
> veltClient: client,
> });
> if (!store) return;
>
> // Seed the UI with the current CRDT value
> const items = store.getValue() || [];
> renderItems(items);
> }
> ```
### Step 2: Read the store
Read the current array value at any time. The CRDT library keeps the value automatically synced with all collaborators.
> [tab] React / Next.js
>
> The hook's `value` field reactively tracks the current array — re-renders automatically on every local and remote change, so no manual subscription is needed. You can also read the latest synchronous value at any time via `store.getValue()` (useful inside event handlers).
>
> ```tsx theme={null}
> const { value: items, store } = useStore- ({
> storeId: 'my-array-store',
> type: 'array',
> initialValue: [],
> });
>
> // Reactive value from the hook — already up to date
> const itemList = Array.isArray(items) ? items : [];
>
> // Synchronous read of the latest value (useful inside event handlers)
> const current = store.getValue() || [];
> ```
> [tab] Other Frameworks
>
> Use `store.getValue()` to read the current synchronous value, and `store.subscribe()` to listen for every change (local and remote) with the full merged array.
>
> ```js theme={null}
> // Read the current array value
> const currentItems = store.getValue() || [];
>
> // Subscribe to all future changes (local and remote)
> const unsubscribe = store.subscribe((newItems) => {
> // Re-render the UI with the latest merged state
> renderItems(Array.isArray(newItems) ? newItems : []);
> });
>
> // Call unsubscribe to stop listening when no longer needed
> unsubscribe();
> ```
### Step 3: Update the store
Use `update()` to replace the entire array value. The CRDT library handles conflict-free merging with other users' edits automatically.
> [tab] React / Next.js
>
> ```tsx theme={null}
> // Add a new item to the end of the array
> const addItem = (name: string) => {
> const current = store.getValue() || [];
> if (Array.isArray(current)) {
> updateItems([...current, { id: generateId(), name }]);
> }
> };
>
> // Update an item by its ID
> const updateItem = (itemId: string, newName: string) => {
> const current = store.getValue() || [];
> if (Array.isArray(current)) {
> updateItems(
> current.map((item) => (item.id === itemId ? { ...item, name: newName } : item))
> );
> }
> };
>
> // Remove an item from the array by its ID
> const removeItem = (itemId: string) => {
> const current = store.getValue() || [];
> if (Array.isArray(current)) {
> updateItems(current.filter((item) => item.id !== itemId));
> }
> };
> ```
> [tab] Other Frameworks
>
> ```js theme={null}
> // Add a new item to the end of the array
> function addItem(name) {
> const current = store.getValue() || [];
> store.update([...current, { id: generateId(), name }]);
> }
>
> // Update an item by its ID
> function updateItem(itemId, newName) {
> const current = store.getValue() || [];
> store.update(
> current.map((item) => (item.id === itemId ? { ...item, name: newName } : item))
> );
> }
>
> // Remove an item from the array by its ID
> function removeItem(itemId) {
> const current = store.getValue() || [];
> store.update(current.filter((item) => item.id !== itemId));
> }
> ```
### Step 4: Save and restore versions (optional)
Create checkpoints and roll back when needed.
> [tab] React / Next.js
>
> The `useStore` hook exposes version management methods directly:
>
> ```tsx theme={null}
> import { Version } from '@veltdev/crdt-react';
>
> const {
> value: items,
> update: updateItems,
> saveVersion,
> getVersions,
> getVersionById,
> restoreVersion,
> setStateFromVersion,
> } = useStore
- ({
> storeId: 'my-array-store',
> type: 'array',
> initialValue: [],
> });
>
> // Save a named snapshot of the current state
> await saveVersion('Draft v1');
>
> // Retrieve the list of all saved versions
> const versions: Version[] = await getVersions();
>
> // Restore the store to a previously saved version
> await restoreVersion(versionId);
> const version = await getVersionById(versionId);
> if (version) {
> await setStateFromVersion(version);
> }
> ```
> [tab] Other Frameworks
>
> ```js theme={null}
> import { Version } from '@veltdev/crdt';
>
> // Save a named snapshot of the current state
> const versionId = await store.saveVersion('Draft v1');
>
> // List all saved versions
> const versions = await store.getVersions();
>
> // Restore the store to a previously saved version
> await store.restoreVersion(versionId);
> const version = await store.getVersionById(versionId);
> if (version) {
> await store.setStateFromVersion(version);
> }
> ```
### Step 5: Initial content with forceResetInitialContent (optional)
By default, `initialValue` is only applied when the document has no existing remote state. Set `forceResetInitialContent` to `true` to always reset the store to `initialValue` on initialization, overwriting any existing remote data.
> [tab] React / Next.js
>
> ```tsx theme={null}
> const { value: items, update: updateItems } = useStore
- ({
> storeId: 'my-array-store',
> type: 'array',
> initialValue: defaultItems,
> forceResetInitialContent: true,
> });
> ```
> [tab] Other Frameworks
>
> ```js theme={null}
> const store = await createVeltStore({
> id: 'my-array-store',
> type: 'array',
> initialValue: defaultItems,
> veltClient: client,
> forceResetInitialContent: true,
> });
> ```
## Complete Example
> [tab] React / Next.js
>
> A complete collaborative todo list built with `useStore`:
>
> ```tsx Complete Implementation expandable lines theme={null}
> import React, { useState, useEffect, useCallback } from 'react';
> import { useStore, Version } from '@veltdev/crdt-react';
>
> interface Todo {
> id: string;
> text: string;
> completed: boolean;
> }
>
> const generateId = () => Math.random().toString(36).substring(2, 15);
>
> const defaultTodos: Todo[] = [
> { id: 'seed-1', text: 'Welcome Todo - Edit me!', completed: false },
> ];
>
> export const Todos = () => {
> const [newTodo, setNewTodo] = useState('');
> const [versionName, setVersionName] = useState('');
> const [versions, setVersions] = useState
([]);
>
> // Use the useStore hook — handles initialization and subscriptions automatically
> const {
> value: todos,
> update: updateTodos,
> store,
> saveVersion: storeSaveVersion,
> getVersions: storeGetVersions,
> restoreVersion: storeRestoreVersion,
> getVersionById,
> setStateFromVersion,
> } = useStore