Skip to content

Build your personal knowledge base with Trilium Notes

127 KB
Raw Blame

Backend API

BackendApi

The api global available inside backend script notes (application/javascript;env=backend). Runs server-side: no DOM, no jQuery.

Member Description
startNote
optional

BNote | null
Note where the script execution started — the entry point of the current script bundle (in C terms, the file containing main()). When a script is spread across multiple code notes (descendant code notes loaded as modules via require()), every note in the bundle shares the same startNote, while currentNote differs per note. Messages from api.log() are grouped under this note. When a frontend script calls api.runOnBackend(), the frontend's startNote is preserved here; since that note may not be resolvable on the backend, this can be null.

currentNote

BNote
Note containing the source code that is currently executing (in C terms, __FILE__). Equal to startNote unless execution has moved into a descendant module note loaded via require(). Don't confuse this with the concept of the active note in the UI.

originEntity
optional

Attribute | BBranch | BNote | null
Entity whose event triggered this execution; undefined when the run was not event-driven (e.g. started manually via "Execute script" or note.executeScript()). What it holds depends on the trigger: - ~runOnNoteCreation, ~runOnNoteChange, ~runOnNoteTitleChange, ~runOnNoteContentChange — the affected note; - ~runOnChildNoteCreation — the newly created child note; - ~runOnAttributeCreation, ~runOnAttributeChange — the attribute; - ~runOnBranchCreation, ~runOnBranchChange, ~runOnBranchDeletion — the branch; - scheduled scripts (#run=backendStartup / #run=hourly / #run=daily) — the script note itself; - search scripts (~searchScript) — the search note.

req

Request
The HTTP request, present only when the script runs as a custom request handler: a note with the #customRequestHandler label, invoked through a /custom/... URL. It is undefined in every other backend script. The object is Express's own request, so it has more members than Request lists.

res

Response
The HTTP response to write the reply to, such as api.res.status(200).json({ ok: true }). Like req, it is present only in custom request handlers, and is Express's own response.

pathParams

string[]
The capture groups from the #customRequestHandler regex that matched this request's URL, in order. Available only inside custom request handlers.

dayjs

Dayjs
day.js library for date manipulation. See https://day.js.org for documentation

xml2js

Xml2js
The xml2js library, which converts between XML and JavaScript objects.

htmlParser

HtmlParser
The node-html-parser library, which parses HTML into elements that can be queried.

getInstanceName
getInstanceName(): string | null

Instance name identifies particular Trilium instance. It can be useful for scripts if some action needs to happen on only one specific instance.

getNote
getNote(noteId: string): BNote | null

Returns a note by its ID, or null.

getBranch
getBranch(branchId: string): BBranch | null

Returns a branch by its ID, or null.

getAttribute
getAttribute(attributeId: string): Attribute | null

Returns an attribute by its ID, or null.

getAttachment
getAttachment(attachmentId: string): BAttachment | null

Returns an attachment by its ID, or null.

getRevision
getRevision(revisionId: string): BRevision | null

Returns a revision by its ID, or null.

getEtapiToken
getEtapiToken(etapiTokenId: string): BEtapiToken | null

Returns an ETAPI token by its ID, or null.

getEtapiTokens
getEtapiTokens(): BEtapiToken[]

Returns all ETAPI tokens.

getOption
getOption(optionName: string): BOption | null

Returns an option by name, or null.

getOptions
getOptions(): BOption[]

Returns all options.

searchForNotes
searchForNotes(query: string, searchParams?: SearchParams): BNote[]

This is a powerful search method - you can search by attributes and their values, e.g.: "#dateModified =* MONTH AND #log". See https://triliumnext.github.io/Docs/Wiki/search.html for full documentation for all options

searchForNote
searchForNote(query: string, searchParams?: SearchParams): BNote | null

This is a powerful search method - you can search by attributes and their values, e.g.: "#dateModified =* MONTH AND #log". See https://triliumnext.github.io/Docs/Wiki/search.html for full documentation for all options

getNotesWithLabel
getNotesWithLabel(name: string, value?: string): BNote[]

Retrieves notes with given label name & value

ParameterDescription
namestring
attribute name
value
optional
string
attribute value
getNoteWithLabel
getNoteWithLabel(name: string, value?: string): BNote | null

Retrieves first note with given label name & value

ParameterDescription
namestring
attribute name
value
optional
string
attribute value
ensureNoteIsPresentInParent
ensureNoteIsPresentInParent(noteId: string, parentNoteId: string, prefix?: string): { branch: BBranch | null }

If there's no branch between note and parent note, create one. Otherwise, do nothing. Returns the new or existing branch.

ParameterDescription
noteIdstring
parentNoteIdstring
prefix
optional
string
if branch is created between note and parent note, set this prefix
ensureNoteIsAbsentFromParent
ensureNoteIsAbsentFromParent(noteId: string, parentNoteId: string): void

If there's a branch between note and parent note, remove it. Otherwise, do nothing.

toggleNoteInParent
toggleNoteInParent(present: boolean, noteId: string, parentNoteId: string, prefix?: string): void

Based on the value, either create or remove branch between note and parent note.

ParameterDescription
presentboolean
true if we want the branch to exist, false if we want it gone
noteIdstring
parentNoteIdstring
prefix
optional
string
if branch is created between note and parent note, set this prefix
createTextNote
createTextNote(parentNoteId: string, title: string, content: string): NoteAndBranch

Create text note. See also createNewNote() for more options.

createDataNote
createDataNote(parentNoteId: string, title: string, content: object): NoteAndBranch

Create data note - data in this context means object serializable to JSON. Created note will be of type 'code' and JSON MIME type. See also createNewNote() for more options.

createNewNote
createNewNote(params: { parentNoteId: string; title: string; content: string | Uint8Array<ArrayBufferLike>; type: string; mime?: string; [key: string]: unknown }): NoteAndBranch

Returns NoteAndBranch: object contains newly created entities note and branch

logMessages

Record<string, string[]>
Per-note log message buffers shown in the UI log pane.

logSpacedUpdates

Record<string, unknown>
Per-note spaced-update handlers for the log pane.

log
log(...args: unknown[]): void

Log given message to trilium logs and log pane in UI. Accepts multiple arguments which are joined with spaces, similar to console.log.

getRootCalendarNote
getRootCalendarNote(): BNote | null

Returns root note of the calendar.

getDayNote
getDayNote(date: string, rootNote?: BNote): BNote | null

Returns day note for given date. If such note doesn't exist, it is created.

ParameterDescription
datestring
in YYYY-MM-DD format
rootNote
optional
BNote
specify calendar root note, normally leave empty to use the default calendar
getTodayNote
getTodayNote(rootNote?: BNote): BNote | null

Returns today's day note. If such note doesn't exist, it is created.

ParameterDescription
rootNote
optional
BNote
specify calendar root note, normally leave empty to use the default calendar
getWeekFirstDayNote
getWeekFirstDayNote(date: string, rootNote?: BNote): BNote | null

Returns note for the first date of the week of the given date.

ParameterDescription
datestring
in YYYY-MM-DD format
rootNote
optional
BNote
specify calendar root note, normally leave empty to use the default calendar
getWeekNote
getWeekNote(date: string, rootNote?: BNote): BNote | null

Returns week note for given date. If such a note doesn't exist, it is created.

If the calendar does not support week notes, this method will return `null`.

ParameterDescription
datestring
in YYYY-MM-DD format
rootNote
optional
BNote
specify calendar root note, normally leave empty to use the default calendar

Returns BNote | null: an existing or newly created week note, or null if the calendar does not support week notes.

getMonthNote
getMonthNote(date: string, rootNote?: BNote): BNote | null

Returns month note for given date. If such a note doesn't exist, it is created.

ParameterDescription
datestring
in YYYY-MM format
rootNote
optional
BNote
specify calendar root note, normally leave empty to use the default calendar
getQuarterNote
getQuarterNote(date: string, rootNote?: BNote): BNote | null

Returns quarter note for given date. If such a note doesn't exist, it is created.

ParameterDescription
datestring
in YYYY-MM format
rootNote
optional
BNote
specify calendar root note, normally leave empty to use the default calendar
getYearNote
getYearNote(year: string, rootNote?: BNote): BNote | null

Returns year note for given year. If such a note doesn't exist, it is created.

ParameterDescription
yearstring
in YYYY format
rootNote
optional
BNote
specify calendar root note, normally leave empty to use the default calendar
sortNotes
sortNotes(parentNoteId: string, sortConfig: { sortBy?: string; reverse?: boolean; foldersFirst?: boolean }): void

Sort child notes of a given note. sortBy takes the #sorted grammar — comma-separated levels of title, dateCreated, dateModified or a label name, each optionally followed by asc or desc (priority desc, dueDate); reverse is the direction of the levels without their own, of the folders grouping and of ties.

setNoteToParent
setNoteToParent(noteId: string, prefix: string, parentNoteId: string | null): void

This method finds note by its noteId and prefix and either sets it to the given parentNoteId or removes the branch (if parentNoteId is not given).

This method looks similar to toggleNoteInParent() but differs because we're looking up branch by prefix.

transactional
transactional<T>(func: () => T): T

This functions wraps code which is supposed to be running in transaction. If transaction already exists, then we'll use that transaction.

Returns T: result of func callback

randomString
randomString(length: number): string

Return randomly generated string of given length. This random string generation is NOT cryptographically secure.

ParameterDescription
lengthnumber
of the string

Returns string: random string

escapeHtml
escapeHtml(str: string): string

Returns string: escaped string

unescapeHtml
unescapeHtml(str: string): string

Returns string: unescaped string

htmlToMarkdown
htmlToMarkdown(html: string): string

Converts the given HTML string to Markdown.

ParameterDescription
htmlstring
HTML content to convert

Returns string: Markdown representation of the input HTML

markdownToHtml
markdownToHtml(markdown: string): string

Converts the given Markdown string to HTML.

ParameterDescription
markdownstring
Markdown content to convert

Returns string: HTML representation of the input Markdown

sql

Sql
Direct access to Trilium's SQLite database.

getAppInfo
getAppInfo(): AppInfo

Application info (version, build date, etc.).

createOrUpdateLauncher
createOrUpdateLauncher(opts: { id: string; type: "note" | "script" | "customWidget"; title: string; isVisible: boolean; icon: string; keyboardShortcut: string; targetNoteId?: string; scriptNoteId?: string; widgetNoteId?: string }): { note: BNote }

Creates a new launcher to the launchbar. If the launcher (id) already exists, it will be updated.

exportSubtreeToZipFile
exportSubtreeToZipFile(noteId: string, format: "markdown" | "html", zipFilePath: string): Promise<void>
ParameterDescription
noteIdstring
format"markdown" | "html"
either 'html' or 'markdown'
zipFilePathstring
runOnFrontend
runOnFrontend(script: string | (() => void), params?: unknown[]): void

Executes given anonymous function on the frontend(s). Internally, this serializes the anonymous function into string and sends it to frontend(s) via WebSocket. Note that there can be multiple connected frontend instances (e.g. in different tabs). In such case, all instances execute the given function.

ParameterDescription
scriptstring | (() => void)
script to be executed on the frontend
params
optional
unknown[]
list of parameters to the anonymous function to be sent to frontend

Returns void: no return value is provided.

runOutsideOfSync
runOutsideOfSync(callback: () => void): Promise<void>

Sync process can make data intermittently inconsistent. Scripts which require strong data consistency can use this function to wait for a possible sync process to finish and prevent new sync process from starting while it is running.

Because this is an async process, the inner callback doesn't have automatic transaction handling, so in case you need to make some DB changes, you need to surround your call with api.transactional(...)

ParameterDescription
callback() => void
function to be executed while sync process is not running

Returns Promise<void>: resolves once the callback is finished (callback is awaited)

backupNow
backupNow(backupName: string): Promise<string>
ParameterDescription
backupNamestring
If the backupName is e.g. "now", then the backup will be written to "backup-now.db" file

Returns Promise<string>: resolves once the backup is finished

duplicateSubtree
duplicateSubtree(origNoteId: string, newParentNoteId: string): NoteAndBranch

Enables the complete duplication of the specified original note and all its children into the specified parent note. The new note will be named the same as the original, with (Dup) added to the end of it.

ParameterDescription
origNoteIdstring
the noteId for the original note to be duplicated
newParentNoteIdstring
the noteId for the parent note where the duplication is to be placed.

Returns NoteAndBranch: the note and the branch of the newly created note.

BNote

A note as seen by backend scripts (subset of trilium-core's BNote).

Member Description
noteId

string
The ID of the note. The root note's ID is root. System notes have IDs that start with _, such as _hidden.

title

string
The title of the note. For a protected note read outside a protected session, this holds the encrypted title. Use getTitleOrProtected() to show a title safely.

type

string
The note type, such as text, code, file, image, search or book. Together with mime, it decides how Trilium renders the content.

mime

string
The MIME type of the note's content, such as text/html for a text note or application/javascript;env=backend for a backend script.

isProtected

boolean
Whether the note is protected. The title and content of a protected note are encrypted, and can be read or changed only while a protected session is active.

isArchived

boolean
Whether the note is archived: it has an archived label of its own or inherits one. A non-inheritable archived label on an ancestor does not count; see areAllNotePathsArchived().

isDeleted

boolean
Whether the note has been deleted, or its deletion is in progress. It becomes true on an object a script still holds after the note is deleted.

shareId

string
Share root ID this note is published under, if any.

blobId

string
The ID of the blob that stores the note's content. It changes whenever the content changes, and notes with identical content share a blob.

dateCreated

string
The date and time the note was created, in local time with its UTC offset, for example 2026-10-22 14:03:05.123+0200.

dateModified

string
The date and time the note was last modified, in local time with its UTC offset, for example 2026-10-22 14:03:05.123+0200. It changes when the content changes or the note itself is saved, such as after a title change.

utcDateCreated

string
The date and time the note was created, in UTC, for example 2026-10-22 12:03:05.123Z.

utcDateModified

string
The date and time the note was last modified, in UTC, for example 2026-10-22 12:03:05.123Z. It changes when the content changes or the note itself is saved.

getContent
getContent(): string | Uint8Array<ArrayBufferLike>

Returns the content of the note: a string for text-based notes (see hasStringContent()), a Uint8Array for binary ones such as images and files. The content is read from the database on each call. For a protected note outside a protected session, it returns an empty string.

setContent
setContent(content: string | Uint8Array<ArrayBufferLike>, opts?: { forceFrontendReload?: boolean }): void

Replaces the content of the note and saves it immediately; there is no need to call save() afterwards. If the content is unchanged, nothing is saved and dateModified stays the same.

The call throws an error when content is null or undefined, when the note is protected and no protected session is active, and when the note is read-only, such as a page of the in-app help.

ParameterDescription
contentstring | Uint8Array<ArrayBufferLike>
The new content: a string for text-based notes, or a Uint8Array for binary ones such as images and files.
opts
optional
{ forceFrontendReload?: boolean }
getJsonContent
getJsonContent<T = unknown>(): T | null

Returns the note's content parsed as JSON. Returns null when the content is empty, blank or binary, and throws an error when it is not valid JSON.

getJsonContentSafely
getJsonContentSafely(): unknown

Returns the note's content parsed as JSON, like getJsonContent(), but returns null instead of throwing an error when the content is not valid JSON.

setJsonContent
setJsonContent(content: unknown): void

Serializes content to JSON, indented with tabs, and saves it as the note's content through setContent(), with the same errors.

hasStringContent
hasStringContent(): boolean

Returns whether getContent() returns a string rather than a Uint8Array. This holds for text, code, canvas, Mermaid and other text-based note types, and for MIME types such as text/*, application/json, application/javascript and image/svg+xml.

getFileName
getFileName(): string

Returns a file name for the note, as used when it is downloaded or exported: the title with characters invalid in file names removed (untitled when the title is empty), plus an extension. The extension is .html for text notes, .json for relation maps, canvases and saved searches, and otherwise comes from the MIME type, unless the title already ends in a matching one.

getFlatText
getFlatText(): string

Returns a single line of text that Trilium searches when matching notes: the note ID, type, MIME type, branch prefixes, title and attributes (as #name=value and ~name=value, inherited ones included), lowercased and with diacritics removed. The content is not included.

getPojo
getPojo(): Record<string, unknown>

Plain serialisable representation of the note (the real return type is NotePojo).

getTitleOrProtected
getTitleOrProtected(): string

Returns the note's title, or the literal string [protected] when the note is protected and no protected session is active.

getIcon
getIcon(): string

Returns the CSS classes of the note's icon, for example tn-icon bx bx-note. The icon comes from the note's iconClass label (its own or inherited) when it has one, and otherwise from its type.

parents

BNote[]
The parent notes of this note: one per place the note appears in the tree, so a cloned note has several. Parents that are not archived come first. This is the same array getParentNotes() returns; don't modify it.

children

BNote[]
The child notes of this note, in their order in the tree. This is the same array getChildNotes() returns; don't modify it.

parentBranches

BBranch[]
The branches that place this note under each of its parents, in the same order as parents. This is the same array getParentBranches() returns; don't modify it.

parentCount

number
The number of parent notes, which is greater than 1 for a cloned note.

childrenCount

number
The number of child notes, including hidden and system notes.

getParentNotes
getParentNotes(): BNote[]

Returns the parent notes of this note, one per place the note appears in the tree. Parents that are not archived come first. The result is the parents array itself; don't modify it.

getChildNotes
getChildNotes(): BNote[]

Returns the child notes of this note, in their order in the tree. The result is the children array itself; don't modify it.

getVisibleChildNotes
getVisibleChildNotes(): BNote[]

Returns the child notes that are shown in a shared note's navigation tree, in tree order. It leaves out system notes, whose IDs start with _, and notes with a shareHiddenFromTree label, their own or inherited. Archived notes are included.

getParentBranches
getParentBranches(): BBranch[]

Returns the branches that place this note under each of its parents. The result is the parentBranches array itself; don't modify it.

getChildBranches
getChildBranches(): BBranch[]

Returns the branches that connect this note to each of its children, in their order in the tree. A branch holds the child's position and prefix.

getVisibleChildBranches
getVisibleChildBranches(): BBranch[]

Returns the child branches whose notes are shown in a shared note's navigation tree, in tree order. It leaves out system notes, whose IDs start with _, and notes with a shareHiddenFromTree label, their own or inherited. Archived notes are included.

getStrongParentBranches
getStrongParentBranches(): BBranch[]

Returns the parent branches the user created, leaving out the automatic placements under the shared notes (_share) and the bookmarks (_lbBookmarks). A note whose last such branch is deleted is deleted too.

getFilteredChildBranches
getFilteredChildBranches(): BBranch[]

Returns the same branches as getChildBranches(). Despite its name, it filters nothing: archived and hidden children are included.

getBranches
getBranches(): BBranch[]

Returns the branches that place this note under each of its parents.

hasChildren
hasChildren(): boolean

Returns whether the note has at least one child note, including hidden and system notes.

hasVisibleChildren
hasVisibleChildren(): boolean

Returns whether getVisibleChildNotes() returns at least one note.

getAncestors
getAncestors(): BNote[]

Returns every ancestor of the note across all of its paths in the tree, each note once, up to and including the root note. The note itself is not included. The order follows the parents: each parent comes first, followed by its own ancestors.

getAncestorNoteIds
getAncestorNoteIds(): string[]

Returns the IDs of the notes getAncestors() returns, in the same order.

getDescendantNoteIds
getDescendantNoteIds(): string[]

Returns the IDs of this note and all its descendants.

getDistanceToAncestor
getDistanceToAncestor(ancestorNoteId: string): number

Returns the number of levels between this note and the given ancestor along the shortest path: 1 for a parent, 2 for a grandparent, and 0 for the note itself. If the note is not a descendant of the given note, it returns 999999.

ParameterDescription
ancestorNoteIdstring
The ID of the ancestor note to measure the distance to.
hasAncestor
hasAncestor(ancestorNoteId: string): boolean

Returns whether the given note is an ancestor of this note on any of its paths. It returns false for the note's own ID.

ParameterDescription
ancestorNoteIdstring
The ID of the note to look for among the ancestors.
isDescendantOfNote
isDescendantOfNote(ancestorNoteId: string): boolean

Returns whether the given note lies on at least one of this note's paths from the root. Unlike hasAncestor(), it returns true for the note's own ID.

isRoot
isRoot(): boolean

Returns whether this note is the root of the note tree, whose ID is root.

getSubtree
getSubtree(opts?: SubtreeOpts): { notes: BNote[]; relationships: SubtreeRelationship[] }

Returns the note and all its descendants, each note once, together with every parent-child relationship among them, including those of cloned notes.

Returns { notes: BNote[]; relationships: SubtreeRelationship[] }: An object with notes, the notes of the subtree including this note, and relationships, the { parentNoteId, childNoteId } pairs connecting them.

getSubtreeNoteIds
getSubtreeNoteIds(opts?: SubtreeOpts): string[]

Returns the IDs of this note and all its descendants, each once. Takes the same options as getSubtree().

getSubtreeNotesIncludingTemplated
getSubtreeNotesIncludingTemplated(): BNote[]

Returns the notes that this note's inheritable attributes reach: the note itself, its descendants, and every note that uses one of them as a template or inherit relation target, along with that note's descendants. Each note appears once; the hidden subtree (_hidden) is skipped.

getInheritingNotes
getInheritingNotes(): BNote[]

Returns the notes that this note's non-inheritable attributes apply to: the note itself and every note that uses it as a template or inherit relation target. Their descendants are not included.

getAllNotePaths
getAllNotePaths(): string[][]

Returns every path from the root note to this note, one per placement in the tree. Each path is an array of note IDs that starts with root and ends with this note's ID.

getBestNotePath
getBestNotePath(hoistedNoteId?: string): string[]

Returns the best path from the root note to this note as an array of note IDs, ranked as in getSortedNotePathRecords().

ParameterDescription
hoistedNoteId
optional
string
The ID of the note whose subtree is preferred. Defaults to root.
getBestNotePathString
getBestNotePathString(hoistedNoteId?: string): string

Returns the best path from the root note to this note as a string of note IDs joined by /, for example root/a1h315/js725h.

ParameterDescription
hoistedNoteId
optional
string
The ID of the note whose subtree is preferred. Defaults to root.
getSortedNotePathRecords
getSortedNotePathRecords(hoistedNoteId?: string): NotePathRecord[]

Returns a record for every path from the root note to this note, best path first. Paths within the hoisted note's subtree come first, then paths without archived notes, then paths outside the hidden subtree, then shorter paths.

ParameterDescription
hoistedNoteId
optional
string
The ID of the note whose subtree is preferred. Defaults to root.

Returns NotePathRecord[]: Records whose notePath holds the note IDs from the root to this note, with flags telling whether the path lies within the hoisted subtree (isInHoistedSubTree), passes through an archived note, the note itself included (isArchived), or lies within the hidden subtree (isHidden).

areAllNotePathsArchived
areAllNotePathsArchived(): boolean

Returns whether every path to this note passes through an archived note. Unlike isArchived, this also counts a non-inheritable archived label on an ancestor. It throws an error if the note has no path from the root.

ownedAttributes

Attribute[]
The labels and relations defined directly on this note, without inherited ones.

targetRelations

Attribute[]
The relations in other notes (or this one) that point to this note. This includes the link relations Trilium creates automatically for links in note content, such as internalLink and imageLink.

attributeCount

number
The number of labels and relations on this note, inherited ones and automatic link relations included.

ownedAttributeCount

number
The number of labels and relations defined directly on this note, automatic link relations included.

labelCount

number
The number of labels on this note, inherited ones included.

ownedLabelCount

number
The number of labels defined directly on this note.

relationCount

number
The number of relations on this note, inherited ones included. Excludes the link relations Trilium creates automatically for links in note content (internalLink, imageLink, relationMapLink, includeNoteLink).

relationCountIncludingLinks

number
The number of relations on this note, inherited ones included, together with the link relations Trilium creates automatically for links in note content.

ownedRelationCount

number
The number of relations defined directly on this note, excluding the link relations Trilium creates automatically for links in note content.

ownedRelationCountIncludingLinks

number
The number of relations defined directly on this note, together with the link relations Trilium creates automatically for links in note content.

targetRelationCount

number
The number of relations in other notes that point to this note, excluding the link relations Trilium creates automatically for links in note content.

targetRelationCountIncludingLinks

number
The number of relations in other notes that point to this note, together with the link relations Trilium creates automatically for links in note content.

getAttributes
getAttributes(type?: string, name?: string): Attribute[]

Returns the labels and relations of this note, inherited ones included, optionally filtered by type and name. Without a filter, the result is the note's own cached array; don't modify it.

ParameterDescription
type
optional
string
"label" or "relation"; any other value throws an error.
name
optional
string
The attribute name, without the leading # or ~.
getOwnedAttributes
getOwnedAttributes(type?: string, name?: string): Attribute[]

Returns the labels and relations defined directly on this note, optionally filtered by type and name. Without a filter, the result is the ownedAttributes array itself; don't modify it.

ParameterDescription
type
optional
string
"label" or "relation"; any other value throws an error.
name
optional
string
The attribute name, without the leading # or ~.
getAttribute
getAttribute(type: string, name: string): Attribute | null

Returns the first attribute of the given type and name, inherited ones included, or null if there is none.

ParameterDescription
typestring
"label" or "relation".
namestring
getOwnedAttribute
getOwnedAttribute(type: string, name: string, value?: string | null): Attribute | null

Returns the first attribute of the given type and name defined directly on this note, or null if there is none. It skips inheritance, so it can be much faster than getAttribute().

ParameterDescription
typestring
"label" or "relation".
namestring
value
optional
string | null
The value to match; when omitted, any value matches.
getAttributeValue
getAttributeValue(type: string, name: string): string | null

Returns the value of the first attribute of the given type and name, inherited ones included, or null if there is none. For a relation, the value is the target note's ID.

ParameterDescription
typestring
"label" or "relation".
namestring
getOwnedAttributeValue
getOwnedAttributeValue(type: string, name: string): string | null

Returns the value of the first attribute of the given type and name defined directly on this note, or null if there is none. For a relation, the value is the target note's ID.

ParameterDescription
typestring
"label" or "relation".
namestring
getAttributeById
getAttributeById(attributeId: string): Attribute | undefined

Returns the attribute of this note with the given ID, inherited ones included, or undefined if there is none.

getAttributeCaseInsensitive
getAttributeCaseInsensitive(type: string, name: string, value?: string | null): Attribute | undefined

Returns the first attribute of the given type whose name, and optionally value, matches regardless of letter case, or undefined if none does. Inherited attributes are included.

ParameterDescription
typestring
"label" or "relation".
namestring
value
optional
string | null
The value to match; an empty or omitted value matches any value.
hasAttribute
hasAttribute(type: string, name: string): boolean

Returns true if the note has a label or relation of the given type and name, inherited ones included.

ParameterDescription
typestring
"label" or "relation".
namestring
hasOwnedAttribute
hasOwnedAttribute(type: string, name: string, value?: string): boolean

Returns whether the note has a label or relation of the given type and name defined directly on it. Inherited attributes don't count.

ParameterDescription
typestring
"label" or "relation".
namestring
value
optional
string
The value to match; when omitted, any value matches.
getLabelDefinitions
getLabelDefinitions(): Attribute[]

Returns the attribute definitions on this note, inherited ones included. Currently returns the same #relation:* definitions as getRelationDefinitions(), not the #label:* ones; to read label definitions, filter getLabels() by names that start with label:.

getRelationDefinitions
getRelationDefinitions(): Attribute[]

Returns the relation definitions on this note, inherited ones included: the #relation:* labels that declare promoted relations, such as #relation:author="promoted,single".

getTargetRelations
getTargetRelations(): Attribute[]

Returns the relations in other notes (or this one) that point to this note, the automatic link relations included. Same as targetRelations.

getLabel
getLabel(name: string): Attribute | null

Returns the first label with the given name, inherited ones included, or null if there is none. Pass the name without the leading #.

getOwnedLabel
getOwnedLabel(name: string): Attribute | null

Returns the first label with the given name defined directly on this note, or null if there is none.

getLabels
getLabels(name?: string): Attribute[]

Returns the labels of this note, inherited ones included. When name is given, only labels with that name are returned.

getOwnedLabels
getOwnedLabels(name: string): Attribute[]

Returns the labels with the given name defined directly on this note.

getLabelValue
getLabelValue(name: string): string | null

Returns the value of the first label with the given name, inherited ones included, or null if there is none. A label without a value returns an empty string.

getOwnedLabelValue
getOwnedLabelValue(name: string): string | null

Returns the value of the first label with the given name defined directly on this note, or null if there is none.

getLabelValues
getLabelValues(name: string): string[]

Returns the values of all labels with the given name, inherited ones included, for labels that can occur more than once.

getOwnedLabelValues
getOwnedLabelValues(name: string): string[]

Returns the values of all labels with the given name defined directly on this note.

hasLabel
hasLabel(name: string): boolean

Returns whether the note has a label with the given name, inherited ones included.

hasOwnedLabel
hasOwnedLabel(name: string, value?: string): boolean

Returns whether the note has a label with the given name defined directly on it.

ParameterDescription
namestring
value
optional
string
The value to match; when omitted, any value matches.
isLabelTruthy
isLabelTruthy(name: string): boolean

Returns whether the note has a label with the given name, inherited ones included, whose value is not "false". A label without a value counts as true.

hasInheritableArchivedLabel
hasInheritableArchivedLabel(): boolean

Returns true if the note has an inheritable #archived label, owned or inherited, so that the note's descendants are archived too.

getRelation
getRelation(name: string): Attribute | null

Returns the first relation with the given name, inherited ones included, or null if there is none. Pass the name without the leading ~.

getOwnedRelation
getOwnedRelation(name: string): Attribute | null

Returns the first relation with the given name defined directly on this note, or null if there is none.

getRelations
getRelations(name?: string): Attribute[]

Returns the relations of this note, inherited ones included. When name is given, only relations with that name are returned.

getOwnedRelations
getOwnedRelations(name?: string | null): Attribute[]

Returns the relations defined directly on this note. When name is given, only relations with that name are returned.

getRelationValue
getRelationValue(name: string): string | null

Returns the ID of the note that the first relation with the given name points to, inherited relations included, or null if there is none. To get the note itself, use getRelationTarget().

getOwnedRelationValue
getOwnedRelationValue(name: string): string | null

Returns the ID of the note that the first relation with the given name defined directly on this note points to, or null if there is none.

getRelationTarget
getRelationTarget(name: string): BNote | null

Returns the note that the first relation with the given name points to, or null if the note has no such relation. Inherited relations are included.

hasRelation
hasRelation(name: string, value?: string): boolean

Returns whether the note has a relation with the given name, inherited ones included.

ParameterDescription
namestring
value
optional
string
The ID of the target note to match; when omitted, any target matches.
hasOwnedRelation
hasOwnedRelation(name: string, value?: string): boolean

Returns whether the note has a relation with the given name defined directly on it.

ParameterDescription
namestring
value
optional
string
The ID of the target note to match; when omitted, any target matches.
addLabel
addLabel(name: string, value?: string, isInheritable?: boolean): Attribute

Adds a label to this note, saves it and returns it. It adds a new label even when the note already has one with that name; to change an existing label instead, use setLabel().

ParameterDescription
namestring
The label name, without the leading #.
value
optional
string
The label value. Defaults to an empty string.
isInheritable
optional
boolean
Whether the note's descendants inherit the label. Defaults to false.
addRelation
addRelation(name: string, targetNoteId: string, isInheritable?: boolean): Attribute

Adds a relation from this note to another note, saves it and returns it. It adds a new relation even when the note already has one with that name; to change an existing relation instead, use setRelation().

ParameterDescription
namestring
The relation name, without the leading ~.
targetNoteIdstring
isInheritable
optional
boolean
Whether the note's descendants inherit the relation. Defaults to false.
addAttribute
addAttribute(type: string, name: string, value?: string, isInheritable?: boolean): Attribute

Adds a label or relation to this note, saves it and returns it. addLabel() and addRelation() do the same for one type.

ParameterDescription
typestring
"label" or "relation".
namestring
The attribute name, without the leading # or ~.
value
optional
string
The label's text, or the relation's target note ID. Defaults to an empty string.
isInheritable
optional
boolean
Whether the note's descendants inherit the attribute. Defaults to false.
setLabel
setLabel(name: string, value?: string): void

Sets the value of the first label with the given name defined directly on this note, or adds a non-inheritable label if the note has none of its own. Inherited labels are left alone. The change is saved immediately.

ParameterDescription
namestring
value
optional
string
The new value. Defaults to an empty string.
setRelation
setRelation(name: string, value?: string): void

Points the first relation with the given name defined directly on this note to another note, or adds a non-inheritable relation if the note has none of its own. Inherited relations are left alone. The change is saved immediately.

ParameterDescription
namestring
value
optional
string
The ID of the target note.
setAttribute
setAttribute(type: string, name: string, value?: string): void

Sets the value of the first attribute of the given type and name defined directly on this note, or adds a non-inheritable one if the note has none of its own. setLabel() and setRelation() do the same for one type. The change is saved immediately.

ParameterDescription
typestring
"label" or "relation".
namestring
value
optional
string
The label's text, or the relation's target note ID. Defaults to an empty string.
setAttributeValueById
setAttributeValueById(attributeId: string, value?: string): void

Sets the value of the attribute with the given ID, which must be defined directly on this note, and saves it. Throws an error if the note has no such attribute of its own.

ParameterDescription
attributeIdstring
value
optional
string
The new value. Defaults to an empty string.
toggleLabel
toggleLabel(enabled: boolean, name: string, value?: string): void

Sets the label like setLabel() when enabled is true, and removes it like removeLabel() when it is false.

toggleRelation
toggleRelation(enabled: boolean, name: string, value?: string): void

Sets the relation like setRelation() when enabled is true, and removes it like removeRelation() when it is false.

ParameterDescription
enabledboolean
namestring
value
optional
string
The ID of the target note.
toggleAttribute
toggleAttribute(type: string, enabled: boolean, name: string, value?: string): void

Sets the attribute like setAttribute() when enabled is true, and removes it like removeAttribute() when it is false.

ParameterDescription
typestring
"label" or "relation".
enabledboolean
namestring
value
optional
string
removeLabel
removeLabel(name: string, value?: string): void

Removes every label with the given name defined directly on this note. Inherited labels are not affected.

ParameterDescription
namestring
value
optional
string
The value to match; when omitted, labels with any value are removed.
removeRelation
removeRelation(name: string, value?: string): void

Removes every relation with the given name defined directly on this note. Inherited relations are not affected.

ParameterDescription
namestring
value
optional
string
The ID of the target note to match; when omitted, relations to any note are removed.
removeAttribute
removeAttribute(type: string, name: string, value?: string): void

Removes every attribute of the given type and name defined directly on this note. Inherited attributes are not affected.

ParameterDescription
typestring
"label" or "relation".
namestring
value
optional
string
The value to match; when omitted, attributes with any value are removed.
isInherited
isInherited(): boolean

Returns true if another note uses this note as its template or inheritance source, through a ~template or ~inherit relation. Despite the name, it does not tell whether this note inherits attributes itself.

revisionCount

number | null
The number of revisions of this note. It is null until a search that filters or sorts by revisionCount or one of the size properties has run; getRevisions().length always works.

getRevisions
getRevisions(): BRevision[]

Returns the saved revisions of this note, oldest first.

saveRevision
saveRevision(opts?: { description?: string; source?: string }): BRevision

Saves a revision that snapshots the note's current title, content and attachments, and returns it. Afterwards, Trilium erases the oldest revisions beyond the number the revision settings keep.

ParameterDescription
opts
optional
{ description?: string; source?: string }
description names the revision; source records what created it: "auto" (the default), "manual", "etapi", "llm" or "restore".
getAttachments
getAttachments(): BAttachment[]

Returns the attachments of this note, ordered by position. Deleted attachments are excluded.

getAttachmentById
getAttachmentById(attachmentId: string): BAttachment

Returns the attachment of this note with the given ID. Returns undefined if this note has no such attachment, although the type does not say so.

getAttachmentByTitle
getAttachmentByTitle(title: string): BAttachment | undefined

Returns the first attachment of this note whose title matches exactly, or undefined if none does.

getAttachmentsByRole
getAttachmentsByRole(role: string): BAttachment[]

Returns the attachments of this note with the given role, such as "image" or "file", ordered by position.

saveAttachment
saveAttachment(attachment: SaveAttachmentInput, matchBy?: "title" | "attachmentId"): BAttachment

Saves an attachment of this note and returns it. If an existing attachment matches, only its content is replaced; otherwise a new attachment is created from attachment, protected if the note is. Missing content is saved as an empty string.

ParameterDescription
attachmentSaveAttachmentInput
matchBy
optional
"title" | "attachmentId"
How to find an existing attachment to update: "attachmentId" (the default) by attachment.attachmentId, which throws an error if no attachment has that ID, or "title" by attachment.title among this note's attachments.
convertToParentAttachment
convertToParentAttachment(opts?: { autoConversion?: boolean }): BAttachment | null

Converts this image note into an image attachment of its parent text note, points the parent's content at the attachment, deletes this note and returns the attachment. Returns null and changes nothing when isEligibleForConversionToAttachment() returns false.

ParameterDescription
opts
optional
{ autoConversion?: boolean }
Pass { autoConversion: true } to also require that the parent links the image.
isEligibleForConversionToAttachment
isEligibleForConversionToAttachment(opts?: { autoConversion?: boolean }): boolean

Returns true if this note can be converted into an attachment of its parent: it is an image note with no children and a single parent, the parent is a text note, both are readable in the current session, and at most one ~imageLink relation points to the image, from the parent.

ParameterDescription
opts
optional
{ autoConversion?: boolean }
Pass { autoConversion: true } to also require that the parent links the image.
contentSize

number | null
The size of the note's content in bytes. Like the other size properties, it is null until a search that filters or sorts by one of them, or by revisionCount, has run.

contentAndAttachmentsSize

number | null
The size in bytes of the note's content together with its attachments, counting content that several of them share once. It is null until a search that uses it has run.

contentAndAttachmentsAndRevisionsSize

number | null
The size in bytes of the note's content together with its attachments and its revisions and their attachments, counting shared content once. It is null until a search that uses it has run.

cloneTo
cloneTo(parentNoteId: string): CloneResponse

Places this note under another parent note as well, keeping its existing placements, and expands the new parent in the note tree. The result does not throw on failure; check success, and read message for why it failed (for example, the note is already in that parent, the target is a search note, or the clone would create a cycle).

ParameterDescription
parentNoteIdstring
The ID of the note to clone into.

Returns CloneResponse: On success, branchId of the new branch and notePath of the clone.

deleteNote
deleteNote(deleteId?: string | null): void

Deletes the note from every place in the tree, together with its descendants that have no other placement, and runs its runOnNoteDeletion relations first. Deleted notes stay recoverable until they are erased. Does nothing if the note is already deleted.

ParameterDescription
deleteId
optional
string | null
An ID that groups the deleted notes, branches and attributes so that they can be restored together. Defaults to a new random ID.
sortParents
sortParents(): void

Reorders this note's parents and parentBranches in memory so that archived and hidden parents come last, which makes Trilium prefer the other paths when it picks a note path. Saves nothing.

sortChildren
sortChildren(): void

Reorders this note's children array in memory by each child's notePosition. Saves nothing and does not change the order shown in the note tree.

searchNotesInSubtree
searchNotesInSubtree(searchString: string): BNote[]

Returns the notes that match a search query. Despite the name, the search covers the whole tree, not only this note's subtree, and leaves out archived and hidden notes; to limit it to this note's subtree, call api.searchForNotes(query, { ancestorNoteId: note.noteId }).

searchNoteInSubtree
searchNoteInSubtree(searchString: string): BNote | null

Returns the first note that matches a search query, or undefined if none does. Like searchNotesInSubtree(), the search covers the whole tree, not only this note's subtree.

getSearchResultNotes
getSearchResultNotes(): BNote[]

Runs the saved search of a search note and returns the notes it finds. Returns an empty array for other note types, and when the search fails (the error goes to the backend log).

isFolder
isFolder(): boolean

Returns true if this note is a search note or has at least one child, archived children included.

isContentAvailable
isContentAvailable(): boolean

Returns true if the note's title and content can be read: the note is not protected, or a protected session is open. Otherwise the content reads as an empty string and the title as "[protected]".

isStringNote
isStringNote(): boolean

Returns whether getContent() returns a string rather than a Uint8Array.

isHtml
isHtml(): boolean

Returns whether this is a code, file or render note with the MIME type text/html.

isImage
isImage(): boolean

Returns whether this is an image note, or a file note with an image/* MIME type.

isJavaScript
isJavaScript(): boolean

Returns whether this is a code, file or launcher note with a JavaScript MIME type.

isJsx
isJsx(): boolean

Returns true if this is a code note with the MIME type text/jsx.

isJson
isJson(): boolean

Returns whether the note's MIME type is application/json, whatever its type.

isMarkdown
isMarkdown(): boolean

Returns whether this is a code note with a Markdown MIME type.

isOptions
isOptions(): boolean

Returns true if this note is one of the settings pages in the hidden subtree, whose IDs start with _options.

isLaunchBarConfig
isLaunchBarConfig(): boolean

Returns true if this note is a launcher or one of the containers that configure the desktop or mobile launch bar.

isHiddenCompletely
isHiddenCompletely(): boolean

Returns whether every path to this note passes through the hidden subtree (_hidden), so that the note has no placement in the visible tree. Returns false for the root note and for _hidden itself.

isInHiddenSubtree
isInHiddenSubtree(): boolean

Returns true if this note is the hidden root note (_hidden) or lies under it in any of its placements. The hidden subtree holds Trilium's system notes, such as settings, launchers and templates.

getScriptEnv
getScriptEnv(): "frontend" | "backend" | null

Returns where the note runs as a script: "backend" for JavaScript with env=backend in its MIME type, "frontend" for frontend JavaScript, JSX, HTML and render notes, and null for notes that are not scripts.

executeScript
executeScript(): unknown

Runs this note as a backend script and returns the script's return value, which is a promise for an async script. The note must be a backend JavaScript code note; for any other note it runs nothing and returns undefined. Throws an error if the note is protected and no protected session is active, or if backend scripting is disabled.

BBranch

A branch (note→parent placement) as seen by backend scripts (subset of BBranch).

Member Description
branchId

string
The ID of the branch. Moving a note to another parent replaces its branch with a new one, so store the note ID rather than the branch ID when you need a stable reference.

noteId

string
The ID of the child note this branch places in the tree.

parentNoteId

string
The ID of the parent note. For the root note's branch, it is "none".

prefix

string | null
The text shown before the note's title in the note tree for this placement only, or null if there is none.

notePosition

number
The position of the note among its siblings under this parent; notes with lower values come first.

isExpanded

boolean
Whether the note is expanded in the note tree at this placement, showing its children.

getNote
getNote(): BNote

Returns the child note this branch places in the tree.

getParentNote
getParentNote(): BNote | null

Returns the parent note. The root note's branch has no parent note.

Request

Minimal Express Request surface available to custom request handlers (a subset of Express's Request — re-declared here to keep this module self-contained). Only the commonly used members are typed; the real object is a full Express request.

Member Description
params

Record<string, string>
Route/path parameters.

query

Record<string, unknown>
Parsed query-string parameters.

body

unknown
Parsed request body (requires a matching body parser).

headers

Record<string, string | string[] | undefined>
Request headers (lower-cased names).

method

string
HTTP method, e.g. "GET", "POST".

url

string
Request URL (path + query string).

get
get(headerName: string): string | undefined

Returns the value of the given (case-insensitive) header.

Response

Minimal Express Response surface available to custom request handlers (a subset of Express's Response). Write the HTTP response through this object, e.g. api.res.status(200).json({ ok: true }).

Member Description
status
status(code: number): Response

Sets the HTTP status code (chainable).

send
send(body?: unknown): Response

Sends the response body (string, Buffer, object, …) and ends the response.

json
json(body: unknown): Response

Sends a JSON response and ends the response.

setHeader
setHeader(name: string, value: string | string[]): Response

Sets a response header (chainable).

set
set(field: string, value?: string): Response

Sets a response header (Express alias of setHeader, chainable).

redirect
redirect(url: string): void

Redirects to the given URL.

end
end(): void

Ends the response without further data.

BAttachment

An attachment as seen by backend scripts (subset of trilium-core's BAttachment).

Member Description
attachmentId
optional

string
The ID of the attachment. It is undefined until a new attachment is first saved.

ownerId

string
The ID of the note the attachment belongs to. For an attachment of a revision, it is the ID of the revision.

role

string
The purpose of the attachment: image for an image shown in a text note, file for an attached file. Trilium also uses roles of its own, such as viewConfig for a collection's view settings.

mime

string
The MIME type of the attachment's content, such as image/png.

title

string
The title of the attachment, usually its file name. For a protected attachment outside a protected session, it holds the encrypted title; use getTitleOrProtected() to show it.

position
optional

number
The place of the attachment among its owner's attachments, listed by ascending position.

isProtected
optional

boolean
Whether the attachment is protected (encrypted).

blobId
optional

string
The ID of the blob that stores the content. It changes whenever the content changes.

utcDateModified
optional

string
The date and time, in UTC, that the attachment was last saved.

contentLength
optional

number
The length of the attachment's content, when it was loaded together with the attachment. Attachments returned by note.getAttachmentsByRole() leave it undefined.

getNote
getNote(): BNote | undefined

Returns the note the attachment belongs to, or undefined for a revision's attachment.

getContent
getContent(): string | Uint8Array<ArrayBufferLike>

Returns the content: a string for text-based content, a Uint8Array for binary content such as images. For a protected attachment outside a protected session, it returns an empty string.

setContent
setContent(content: string | Uint8Array<ArrayBufferLike>, opts?: { forceSave?: boolean; forceFrontendReload?: boolean }): void

Replaces the content and saves it immediately. Throws an error for a protected attachment outside a protected session.

hasStringContent
hasStringContent(): boolean

Returns whether the content is text rather than binary, judged by the MIME type.

isContentAvailable
isContentAvailable(): boolean

Returns whether the title and content can be read: the attachment is not protected, or a protected session is active.

getTitleOrProtected
getTitleOrProtected(): string

Returns the title, or [protected] when the title cannot be read.

getFileName
getFileName(): string

Returns the file name the attachment downloads under: its title with a fitting extension.

convertToNote
convertToNote(): NoteAndBranch

Turns the attachment into a child note of its owner and deletes the attachment. In a text note, images and links that point to the attachment are rewritten to point to the new note. Throws an error for a revision's attachment, and for a protected one outside a protected session.

save
save(): this

Saves changes made to the attachment's properties, such as title.

markAsDeleted
markAsDeleted(deleteId?: string | null): void

Deletes the attachment. Deleted attachments stay recoverable until they are erased.

ParameterDescription
deleteId
optional
string | null
An ID that groups items deleted together, so that they can be restored together.

BRevision

A note revision as seen by backend scripts (subset of trilium-core's BRevision).

Member Description
revisionId
optional

string
The ID of the revision.

noteId

string
The ID of the note this revision belongs to.

type

string
The note's type at the time of the revision, such as "text" or "code".

mime

string
The note's MIME type at the time of the revision.

title

string
The note's title at the time of the revision. For a protected revision outside a protected session, it is "[protected]".

dateLastEdited
optional

string
When the note was last edited before the revision was saved, in local time with its UTC offset, formatted as YYYY-MM-DD HH:mm:ss.SSS+ZZZZ (for example, 2026-10-22 14:05:09.123+0200).

utcDateLastEdited
optional

string
When the note was last edited before the revision was saved, in UTC, formatted as YYYY-MM-DD HH:mm:ss.SSSZ (for example, 2026-10-22 12:05:09.123Z).

contentLength
optional

number
The size of the revision's content in bytes, when it was loaded together with the revision. Revisions returned by note.getRevisions() and note.saveRevision() leave it undefined.

getContent
getContent(): string | Uint8Array<ArrayBufferLike>

Returns the content of the revision: a string for text-based note types, a Uint8Array for binary ones such as images and files. For a protected revision outside a protected session, it returns an empty string.

getJsonContent
getJsonContent(): unknown

Returns the revision's content parsed as JSON. Returns null when the content is empty, blank or binary, and throws an error when it is not valid JSON.

Sql

Direct access to Trilium's SQLite database (subset of trilium-core's SqlService). Queries mark parameters with ? and take their values in an array, in order. Changes made here bypass Trilium's own bookkeeping: they do not sync, and Trilium's in-memory copy of the notes does not see them until the next restart. Change notes through the note methods instead.

Member Description
getRow
getRow<T>(query: string, params?: unknown[]): T

Returns the first row of the result, as an object of column names to values, or undefined when the query returns no rows.

getRowOrNull
getRowOrNull<T>(query: string, params?: unknown[]): T | null

Returns the first row of the result, or null when the query returns no rows.

getValue
getValue<T>(query: string, params?: unknown[]): T

Returns the first column of the first row, such as the count of SELECT COUNT(*) FROM notes, or undefined when the query returns no rows.

getRows
getRows<T>(query: string, params?: unknown[]): T[]

Returns every row of the result, each as an object of column names to values.

getColumn
getColumn<T>(query: string, params?: unknown[]): T[]

Returns the first column of every row of the result.

getMap
getMap<K extends string | number | symbol, V>(query: string, params?: unknown[]): Record<K, V>

Returns an object that maps the first column of each row to its second column.

iterateRows
iterateRows<T>(query: string, params?: unknown[]): IterableIterator<T>

Returns the rows of the result one at a time, which keeps a large result out of memory.

execute
execute(query: string, params?: unknown[]): { changes: number; lastInsertRowid: number }

Runs a statement that changes data, such as UPDATE or INSERT.

Returns { changes: number; lastInsertRowid: number }: changes, the number of rows changed, and lastInsertRowid, the ID of the row an INSERT added.

executeScript
executeScript(query: string): void

Runs several statements separated by semicolons, without parameters.

transactional
transactional<T>(func: () => T): T

Calls func in a transaction: when it throws, every change it made is undone. Inside a transaction already running, it runs as a nested savepoint.

Returns T: What func returns.

DayjsInstance

A date as day.js wraps it (subset).

Member Description
format
format(template?: string): string

Formats the date, such as "YYYY-MM-DD" for 2026-10-22. Without a template, it returns the ISO 8601 form with the UTC offset, such as 2026-10-22T14:03:05+02:00.

add
add(value: number, unit: string): DayjsInstance

Returns a new date, value units later. The date it is called on stays unchanged.

ParameterDescription
valuenumber
unitstring
The unit, such as "day", "week", "month" or "year".
subtract
subtract(value: number, unit: string): DayjsInstance

Returns a new date, value units earlier. The date it is called on stays unchanged.

ParameterDescription
valuenumber
unitstring
The unit, such as "day", "week", "month" or "year".
toDate
toDate(): Date

Returns the date as a JavaScript Date.

Types

Attribute

A label or relation attached to a note.

Property Description
attributeId string
The ID of the attribute.
type "label" | "relation"
The type of the attribute: label or relation.
name string
The name of the attribute, without the # or ~ prefix.
value string
The value of the attribute. For a relation, it is the ID of the target note. For a label without a value, it is an empty string.
isInheritable boolean
Whether the note's descendants inherit the attribute.
isOwned boolean
Not set by Trilium: neither frontend nor backend attributes carry this property, so it reads undefined.

Dayjs

Minimal day.js surface (the real API exposes the full day.js factory).

type Dayjs = (date?: string | number | Date) => DayjsInstance

Xml2js

The xml2js library, version 0.6, which converts between XML and JavaScript objects, such as with xml2js.parseStringPromise(xml).

HtmlParser

The node-html-parser library, version 9, which parses HTML into elements that can be queried, such as with htmlParser.parse(html).querySelectorAll("a").

BEtapiToken

An ETAPI token, which grants an external program access to the ETAPI (subset of trilium-core's BEtapiToken). The token itself is not available, only its hash, which this type leaves out.

Property Description
etapiTokenId
optional
string
The ID of the token.
name string
The name given to the token when it was created.
utcDateCreated string
The date and time, in UTC, that the token was created.
utcDateModified
optional
string
The date and time, in UTC, that the token was last changed, such as renamed.
isDeleted boolean
Whether the token has been deleted, which revokes it.

BOption

An option, one of Trilium's settings (subset of trilium-core's BOption).

Property Description
name string
The name of the option, such as theme or locale.
value string
The value of the option. Every value is a string, numbers and booleans included.
isSynced
optional
boolean
Whether the option syncs to other devices; device-specific options do not.
utcDateModified
optional
string
The date and time, in UTC, that the option last changed.

SearchParams

Options of api.searchForNotes() and api.searchForNote().

Property Description
fastSearch
optional
boolean
Whether to search only titles and attributes, leaving out note content, which is faster. Defaults to false.
includeArchivedNotes
optional
boolean
Whether to include archived notes. Defaults to true.
includeHiddenNotes
optional
boolean
Whether to include the hidden subtree's notes, such as settings and launchers. Defaults to false.
ignoreHoistedNote
optional
boolean
Whether to search the whole tree even while a note is hoisted. Defaults to true; with false and no ancestorNoteId, only the hoisted note's subtree is searched.
ancestorNoteId
optional
string
The ID of a note to search under: only its descendants are found.
ancestorDepth
optional
string
How deep under ancestorNoteId the found notes can lie: eq, gt or lt followed by a depth, such as eq1 for its children only or lt4 for less than four levels down.
orderBy
optional
string
What to order the results by: a note property such as title, dateCreated or dateModified, or relevancy, the default.
orderDirection
optional
string
asc or desc; the direction of orderBy.
limit
optional
number | null
The largest number of results to return.
debug
optional
boolean
Whether to write how the query was parsed to the backend log.
fuzzyAttributeSearch
optional
boolean
Whether attribute conditions match loosely: #status=done also matches values that contain done, and #stat matches attributes whose name starts with stat. Defaults to false.

NoteAndBranch

Result of the backend note-creation helpers.

Property Description
note BNote
The new note. For duplicateSubtree(), it is the copy of the original note.
branch BBranch
The branch that places the new note under its parent.

AppInfo

Information about the running Trilium, as api.getAppInfo() returns it.

Property Description
appVersion string
The version of Trilium, such as 0.106.0.
dbVersion number
The version of the database schema.
nodeVersion
optional
string
The version of Node.js; absent in the standalone and mobile apps, which have no Node.js.
syncVersion number
The version of the sync protocol, which both sides of a sync must share.
buildDate string
When this build of Trilium was made.
buildRevision string
The Git commit this build of Trilium was made from.
dataDirectory
optional
string
The directory that holds the database and the other data; absent in the standalone and mobile apps.
clipperProtocolVersion string
The version of the protocol the web clipper speaks with Trilium.
utcDateTime string
The date and time, in UTC, that Trilium started, in ISO 8601 form.

SubtreeOpts

Options accepted by the subtree traversal helpers on BNote.

Property Description
includeArchived
optional
boolean
Whether to include archived notes and their descendants. Defaults to true.
includeHidden
optional
boolean
Whether to descend into the hidden subtree, _hidden, which holds Trilium's system notes. Defaults to false.
resolveSearch
optional
boolean
Whether to run each search note and include its results as its children. Defaults to false, which includes the search note but none of its results.

SubtreeRelationship

A single parent→child link in a subtree (BNote.getSubtree).

Property Description
parentNoteId string
The ID of the parent note. With resolveSearch, it can be a search note and the child one of its results.
childNoteId string
The ID of the child note. With includeArchived: false, it can name an archived note that the list of notes leaves out.

NotePathRecord

One resolved tree path to a note (subset of the client's NotePathRecord).

Property Description
isArchived boolean
Whether a note on the path, the note itself included, is archived, which means it has the #archived label, owned or inherited.
isInHoistedSubTree boolean
Whether the path passes through the hoisted note passed to getSortedNotePathRecords(). It is always true when the hoisted note is root.
isSearch
optional
boolean
Whether the note itself is a search note. Only frontend scripts get this property; backend records leave it out.
notePath string[]
The note IDs along the path, from root to the note itself.
isHidden boolean
Whether the path passes through the hidden subtree, _hidden, which holds Trilium's system notes.

SaveAttachmentInput

Input accepted by BNote.saveAttachment.

Property Description
attachmentId
optional
string
The ID of the attachment to update. Omit it to create a new attachment, which gets an ID of its own.
role string
The purpose of the attachment, such as image or file. Used only when a new attachment is created.
mime string
The MIME type of the content, such as image/png. Used only when a new attachment is created.
title string
The title of the attachment, usually its file name. Used when a new attachment is created, and to find the attachment to update when matchBy is "title".
content
optional
string | Uint8Array<ArrayBufferLike>
The content of the attachment: a string, or bytes for binary content. Defaults to an empty string.
position
optional
number
The place of the attachment among the note's attachments, which getAttachments() lists by ascending position. Used only when a new attachment is created.

CloneResponse

Result of a clone operation (BNote.cloneTo); mirrors CloneResponse.

Property Description
success boolean
Whether the note was cloned.
message
optional
string
Why the clone failed, such as the note already being in that parent. Present only when success is false.
branchId
optional
string
The ID of the new branch that places the note under the new parent. Present only when success is true.
notePath
optional
string
The path of the clone, as note IDs from root joined by /, ending in the note's ID. Present only when success is true.