Trilium Backend API
    Preparing search index...

    Interface Api

    interface Api {
        __private: { becca: default };
        axios: undefined;
        cheerio: ../../node_modules/cheerio/dist/esm;
        currentNote: BNote;
        dayjs: __module;
        htmlParser: __module;
        logMessages: Record<string, string[]>;
        logSpacedUpdates: Record<string, SpacedUpdate>;
        originEntity?: AbstractBeccaEntity<any>;
        pathParams?: string[];
        req?: Request;
        res?: Response;
        sql: any;
        startNote?: BNote;
        xml2js: ../../node_modules/@types/xml2js;
        backupNow(backupName: string): Promise<string>;
        createDataNote(
            parentNoteId: string,
            title: string,
            content: {},
        ): NoteAndBranch;
        createNewNote(params: NoteParams): NoteAndBranch;
        createNote(
            parentNoteId: string,
            title: string,
            content: string,
            extraOptions: Omit<
                NoteParams,
                "type"
                | "title"
                | "content"
                | "parentNoteId",
            > & { attributes?: AttributeRow[]; json?: boolean },
        ): NoteAndBranch;
        createOrUpdateLauncher(
            opts: {
                icon: string;
                id: string;
                isVisible: boolean;
                keyboardShortcut: string;
                scriptNoteId: string;
                targetNoteId: string;
                title: string;
                type: "note" | "script" | "customWidget";
                widgetNoteId?: string;
            },
        ): { note: BNote };
        createTextNote(
            parentNoteId: string,
            title: string,
            content: string,
        ): NoteAndBranch;
        duplicateSubtree(
            origNoteId: string,
            newParentNoteId: string,
        ): { branch: BBranch; note: BNote };
        ensureNoteIsAbsentFromParent(noteId: string, parentNoteId: string): void;
        ensureNoteIsPresentInParent(
            noteId: string,
            parentNoteId: string,
            prefix: string,
        ): { branch: BBranch };
        escapeHtml(string: string): string;
        exportSubtreeToZipFile(
            noteId: string,
            format: "html" | "markdown",
            zipFilePath: string,
        ): Promise<void>;
        getAppInfo(): AppInfo;
        getAttachment(attachmentId: string): BAttachment;
        getAttribute(attachmentId: string): BAttribute;
        getAttribute(attributeId: string): BAttribute;
        getBranch(branchId: string): BBranch;
        getDayNote(date: string, rootNote?: BNote): BNote;
        getEtapiToken(etapiTokenId: string): BEtapiToken;
        getEtapiTokens(): BEtapiToken[];
        getInstanceName(): string;
        getMonthNote(date: string, rootNote: BNote): BNote;
        getNote(noteId: string): BNote;
        getNotesWithLabel(name: string, value?: string): BNote[];
        getNoteWithLabel(name: string, value?: string): BNote;
        getOption(optionName: string): BOption;
        getOptions(): BOption[];
        getQuarterNote(date: string, rootNote: BNote): BNote;
        getRevision(revisionId: string): BRevision;
        getRootCalendarNote(): BNote;
        getTodayNote(rootNote?: BNote): BNote;
        getWeekFirstDayNote(date: string, rootNote: BNote): BNote;
        getWeekNote(date: string, rootNote: BNote): BNote;
        getYearNote(year: string, rootNote?: BNote): BNote;
        log(...args: unknown[]): void;
        randomString(length: number): string;
        runOnFrontend(script: () => string | void, params: []): void;
        runOutsideOfSync(callback: () => void): Promise<void>;
        searchForNote(query: string, searchParams: SearchParams): BNote;
        searchForNotes(query: string, searchParams: SearchParams): BNote[];
        setNoteToParent(noteId: string, prefix: string, parentNoteId: string): void;
        sortNotes(
            parentNoteId: string,
            sortConfig: { foldersFirst?: boolean; reverse?: boolean; sortBy?: string },
        ): void;
        toggleNoteInParent(
            present: true,
            noteId: string,
            parentNoteId: string,
            prefix: string,
        ): void;
        transactional(func: () => void): any;
        unescapeHtml(string: string): string;
    }
    Index

    Properties

    __private: { becca: default }

    This object contains "at your risk" and "no BC guarantees" objects for advanced use cases.

    Type Declaration

    • becca: default

      provides access to the backend in-memory object graph, see Becca

    axios: undefined

    Axios was deprecated since April 2024 and has now been removed following the March 2026 supply chain attack. Use the native fetch() API instead.

    cheerio library for HTML parsing and manipulation. See https://cheerio.js.org for documentation

    cheerio will be removed in a future version. Use api.htmlParser (node-html-parser) instead.

    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.

    dayjs: __module

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

    htmlParser: __module

    node-html-parser library for HTML parsing. See https://github.com/piotr-nicol/node-html-parser for documentation. This is the recommended replacement for cheerio.

    logMessages: Record<string, string[]>
    logSpacedUpdates: Record<string, SpacedUpdate>
    originEntity?: AbstractBeccaEntity<any>

    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 (BNote);
    • ~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.
    pathParams?: string[]

    Capture groups from the #customRequestHandler regex that matched this request's URL, in order. Only present in custom request handlers.

    req?: Request

    Express request object. Only present when the script runs as a custom request handler (a note with the #customRequestHandler label invoked via /custom/...); undefined for every other backend script.

    res?: Response

    Express response object — write the HTTP response here. Only present in custom request handlers; undefined otherwise.

    sql: any

    sql

    startNote?: BNote

    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.

    xml2js library for XML parsing. See https://github.com/Leonidas-from-XIV/node-xml2js for documentation

    Methods

    • Parameters

      • backupName: string

        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

    • 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.

      Parameters

      • parentNoteId: string
      • title: string
      • content: {}

      Returns NoteAndBranch

    • Parameters

      • parentNoteId: string

        create new note under this parent

      • title: string
      • content: string
      • extraOptions: Omit<NoteParams, "type" | "title" | "content" | "parentNoteId"> & {
            attributes?: AttributeRow[];
            json?: boolean;
        }
        • Optionalattributes?: AttributeRow[]
        • Optionaljson?: boolean

          should the note be JSON

      Returns NoteAndBranch

      object contains newly created entities note and branch

      please use createTextNote() with similar API for simpler use cases or createNewNote() for more complex needs

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

      Parameters

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

          name of the boxicon to be used (e.g. "bx-time")

        • id: string

          id of the launcher, only alphanumeric at least 6 characters long

        • isVisible: boolean

          if true, will be created in the "Visible launchers", otherwise in "Available launchers"

        • keyboardShortcut: string

          will activate the target note/script upon pressing, e.g. "ctrl+e"

        • scriptNoteId: string

          for type "script"

        • targetNoteId: string

          for type "note"

        • title: string
        • type: "note" | "script" | "customWidget"

          one of

          • "note" - activating the launcher will navigate to the target note (specified in targetNoteId param)
          • "script" - activating the launcher will execute the script (specified in scriptNoteId param)
          • "customWidget" - the launcher will be rendered with a custom widget (specified in widgetNoteId param)
        • OptionalwidgetNoteId?: string

          for type "customWidget"

      Returns { note: BNote }

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

      Parameters

      • parentNoteId: string
      • title: string
      • content: string

      Returns 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.

      Parameters

      • origNoteId: string

        the noteId for the original note to be duplicated

      • newParentNoteId: string

        the noteId for the parent note where the duplication is to be placed.

      Returns { branch: BBranch; note: BNote }

      the note and the branch of the newly created note.

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

      Parameters

      • noteId: string
      • parentNoteId: string

      Returns void

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

      Parameters

      • noteId: string
      • parentNoteId: string
      • prefix: string

        if branch is created between note and parent note, set this prefix

      Returns { branch: BBranch }

    • Parameters

      • string: string

      Returns string

      escaped string

    • Parameters

      • noteId: string
      • format: "html" | "markdown"

        either 'html' or 'markdown'

      • zipFilePath: string

      Returns Promise<void>

    • Returns AppInfo

    • Parameters

      • attachmentId: string

      Returns BAttachment

    • Parameters

      • attachmentId: string

      Returns BAttribute

    • Parameters

      • attributeId: string

      Returns BAttribute

    • Parameters

      • branchId: string

      Returns BBranch

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

      Parameters

      • date: string

        in YYYY-MM-DD format

      • OptionalrootNote: BNote

        specify calendar root note, normally leave empty to use the default calendar

      Returns BNote

    • Parameters

      • etapiTokenId: string

      Returns BEtapiToken

    • Returns BEtapiToken[]

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

      Returns string

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

      Parameters

      • date: string

        in YYYY-MM format

      • rootNote: BNote

        specify calendar root note, normally leave empty to use the default calendar

      Returns BNote

    • Parameters

      • noteId: string

      Returns BNote

    • Retrieves notes with given label name & value

      Parameters

      • name: string

        attribute name

      • Optionalvalue: string

        attribute value

      Returns BNote[]

    • Retrieves first note with given label name & value

      Parameters

      • name: string

        attribute name

      • Optionalvalue: string

        attribute value

      Returns BNote

    • Parameters

      • optionName: string

      Returns BOption

    • Returns BOption[]

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

      Parameters

      • date: string

        in YYYY-MM format

      • rootNote: BNote

        specify calendar root note, normally leave empty to use the default calendar

      Returns BNote

    • Parameters

      • revisionId: string

      Returns BRevision

    • Returns root note of the calendar.

      Returns BNote

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

      Parameters

      • OptionalrootNote: BNote

        specify calendar root note, normally leave empty to use the default calendar

      Returns BNote

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

      Parameters

      • date: string

        in YYYY-MM-DD format

      • rootNote: BNote

        specify calendar root note, normally leave empty to use the default calendar

      Returns BNote

    • 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`.

      Parameters

      • date: string

        in YYYY-MM-DD format

      • rootNote: BNote

        specify calendar root note, normally leave empty to use the default calendar

      Returns BNote

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

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

      Parameters

      • year: string

        in YYYY format

      • OptionalrootNote: BNote

        specify calendar root note, normally leave empty to use the default calendar

      Returns BNote

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

      Parameters

      • ...args: unknown[]

      Returns void

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

      Parameters

      • length: number

        of the string

      Returns string

      random string

    • 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.

      Parameters

      • script: () => string | void

        script to be executed on the frontend

      • params: []

        list of parameters to the anonymous function to be sent to frontend

      Returns void

      no return value is provided.

    • 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(...)

      Parameters

      • callback: () => void

        function to be executed while sync process is not running

      Returns Promise<void>

      resolves once the callback is finished (callback is awaited)

    • 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.

      Parameters

      • noteId: string
      • prefix: string
      • parentNoteId: string

      Returns void

      this method is pretty confusing and serves specialized purpose only

    • Sort child notes of a given note.

      Parameters

      • parentNoteId: string
      • sortConfig: { foldersFirst?: boolean; reverse?: boolean; sortBy?: string }

      Returns void

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

      Parameters

      • present: true

        true if we want the branch to exist, false if we want it gone

      • noteId: string
      • parentNoteId: string
      • prefix: string

        if branch is created between note and parent note, set this prefix

      Returns void

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

      Parameters

      • func: () => void

      Returns any

      result of func callback

    • Parameters

      • string: string

        to unescape

      Returns string

      unescaped string