UniqueID extension
The UniqueID
extension adds unique IDs to all nodes. The extension keeps track of your nodes, even if you split them, merge them, undo/redo changes, crop content, paste content … It just works.
Also, you can configure which node types get an unique ID, and which not, and you can customize how those IDs are generated.
Install
npm install @tiptap/extension-unique-id
Settings
attributeName
Name of the attribute that is attached to the HTML tag (will be prefixed with data-
).
Default: 'id'
UniqueID.configure({
attributeName: 'uid',
})
types
All types that should get a unique ID, for example ['heading', 'paragraph']
Default: []
UniqueID.configure({
types: ['heading', 'paragraph'],
})
generateID
Function that generates and returns a unique ID. It receives a context object (for example { node, pos }
), so you can customize ID generation based on the node's type or its position.
Default: ({ node, pos }) => uuidv4()
UniqueID.configure({
generateID: ({ node }) => `${node.type.name}-${uuidv4()}`,
})
filterTransaction
Ignore some mutations, for example applied from other users through the collaboration plugin.
Default: null
import { isChangeOrigin } from '@tiptap/extension-collaboration'
// Adds support for collaborative editing
UniqueID.configure({
filterTransaction: (transaction) => !isChangeOrigin(transaction),
})
Server side Unique ID utility
The generateUniqueIds
function allows you to add unique IDs to a Tiptap document on the server side, without needing to create an Editor
instance. This is useful for processing documents server-side or when you need to add IDs to existing content.
Parameters
doc
(JSONContent
): A Tiptap JSON document to add unique IDs toextensions
(Extensions
): The extensions to use. Must include theUniqueID
extension. To customize how the IDs are generated, you can pass options to theUniqueID
extension.
Return type
Returns a new Tiptap document (a JSONContent
object) with unique IDs added to the nodes.
Example
import { generateUniqueIds, UniqueID } from '@tiptap/extension-unique-id'
import { StarterKit } from '@tiptap/starter-kit'
const doc = {
type: 'doc',
content: [
{ type: 'paragraph', content: [{ type: 'text', text: 'Hello, world!' }] },
{ type: 'heading', attrs: { level: 1 }, content: [{ type: 'text', text: 'My Heading' }] },
],
}
const newDoc = generateUniqueIds(doc, [
StarterKit,
UniqueID.configure({ types: ['paragraph', 'heading'] }),
])
// Result:
// {
// type: 'doc',
// content: [
// { type: 'paragraph', content: [{ type: 'text', text: 'Hello, world!' }], attrs: { id: 'd4590f81-52e8-45ec-b317-2e9a805b03e3' } },
// { type: 'heading', content: [{ type: 'text', text: 'My Heading' }], attrs: { level: 1, id: 'c88f9b5f-7b91-442f-b4d9-ee0d04104827' } }
// ]
// }
The function automatically picks up the configuration from the UniqueID
extension, including options like types
, attributeName
, and generateID
.