Skip to content

Build your personal knowledge base with Trilium Notes

feat(import): add a basic Notion .zip importer (structural)

Elian Doran6116b636f0f9
diff --git a/apps/client/src/services/notion_import.ts b/apps/client/src/services/notion_import.ts
new file mode 100644
index 0000000000..eefb0444bd
--- /dev/null
+++ b/apps/client/src/services/notion_import.ts
@@ -0,0 +1,31 @@
+// Loading import.ts registers the shared "importNotes" WebSocket toast handlers (progress + success).
+// The Notion import reuses that taskType, but the import-provider dialog never loads import.ts on its
+// own, so without this side-effect import the progress/finished toasts would never appear.
+import "./import.js";
+
+import server from "./server.js";
+import utils from "./utils.js";
+
+/**
+ * Uploads a Notion export zip and returns as soon as the server has accepted it. The import itself runs
+ * in the background on the server; progress, completion (navigation to the imported note) and any error
+ * all arrive over the WebSocket via the shared "importNotes" toast handlers in import.ts.
+ */
+async function runImport({ parentNoteId, file }: { parentNoteId: string; file: File }) {
+ const formData = new FormData();
+ formData.append("upload", file);
+ formData.append("parentNoteId", parentNoteId);
+ formData.append("taskId", utils.randomString(10));
+
+ await $.ajax({
+ url: `${window.glob.baseApiUrl}notion-import/import`,
+ headers: await server.getHeaders(),
+ data: formData,
+ type: "POST",
+ timeout: 60 * 60 * 1000,
+ contentType: false, // NEEDED, DON'T REMOVE THIS
+ processData: false // NEEDED, DON'T REMOVE THIS
+ });
+}
+
+export default { runImport };
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index ae292fa4e8..7ea43f7b8d 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -250,6 +250,13 @@
"attach_source": "Attach original HTML (debug)",
"attach_source_hint": "Saves each page's unmodified OneNote HTML as an attachment on the imported note, for comparing against the converted result."
},
+ "notion_import": {
+ "name": "Notion",
+ "description": "Import pages from a Notion HTML export (.zip).",
+ "description_long": "In Notion, export your workspace or a page as HTML with subpages included, then choose the resulting .zip file here.",
+ "choose_file": "Notion export (.zip)",
+ "import": "Import"
+ },
"include_note": {
"dialog_title": "Include note",
"label_note": "Note",
diff --git a/apps/client/src/widgets/dialogs/import_providers/index.ts b/apps/client/src/widgets/dialogs/import_providers/index.ts
index 276a952260..b4ff554eff 100644
--- a/apps/client/src/widgets/dialogs/import_providers/index.ts
+++ b/apps/client/src/widgets/dialogs/import_providers/index.ts
@@ -1,3 +1,4 @@
+import notionProvider from "./notion.js";
import oneNoteProvider from "./onenote.js";
import type { ImportProvider } from "./types.js";
@@ -5,6 +6,6 @@ import type { ImportProvider } from "./types.js";
* Registry of available import providers. Append new providers here; the generic import dialog
* renders the picker and each provider's panel automatically.
*/
-export const importProviders: ImportProvider[] = [oneNoteProvider];
+export const importProviders: ImportProvider[] = [oneNoteProvider, notionProvider];
export type { ImportProvider, ImportProviderPanelProps } from "./types.js";
diff --git a/apps/client/src/widgets/dialogs/import_providers/notion.tsx b/apps/client/src/widgets/dialogs/import_providers/notion.tsx
new file mode 100644
index 0000000000..b8f7c91820
--- /dev/null
+++ b/apps/client/src/widgets/dialogs/import_providers/notion.tsx
@@ -0,0 +1,69 @@
+import { useCallback, useEffect, useRef, useState } from "preact/hooks";
+
+import { t } from "../../../services/i18n.js";
+import notionImport from "../../../services/notion_import.js";
+import toast from "../../../services/toast.js";
+import Button from "../../react/Button.js";
+import FormFileUpload from "../../react/FormFileUpload.js";
+import FormGroup from "../../react/FormGroup.js";
+import type { ImportProvider, ImportProviderPanelProps } from "./types.js";
+
+function NotionPanel({ parentNoteId, closeDialog, setFooter }: ImportProviderPanelProps) {
+ const [file, setFile] = useState<File | null>(null);
+
+ const onChange = useCallback((files: FileList | null) => setFile(files?.[0] ?? null), []);
+
+ const doImport = useCallback(async () => {
+ if (!file) {
+ return;
+ }
+
+ // Close immediately and let the shared import toasts report progress, completion and any error.
+ // The request returns as soon as the server accepts it (the import runs in the background), so the
+ // only errors caught here are upfront ones like an upload failure.
+ closeDialog();
+ try {
+ await notionImport.runImport({ parentNoteId, file });
+ } catch (e) {
+ toast.showError(e instanceof Error ? e.message : String(e));
+ }
+ }, [file, parentNoteId, closeDialog]);
+
+ // Keep the latest import handler in a ref so the footer effect depends only on `file` being present,
+ // never on doImport's identity — otherwise re-pushing the footer on every change would loop with the
+ // parent re-rendering us back (see the OneNote panel for the same reasoning).
+ const doImportRef = useRef(doImport);
+ doImportRef.current = doImport;
+
+ useEffect(() => {
+ setFooter(
+ <Button
+ text={t("notion_import.import")}
+ kind="primary"
+ disabled={!file}
+ onClick={() => void doImportRef.current()}
+ />
+ );
+ }, [file, setFooter]);
+
+ useEffect(() => () => setFooter(null), [setFooter]);
+
+ return (
+ <div className="notion-panel">
+ <p>{t("notion_import.description_long")}</p>
+ <FormGroup name="notion-file" label={t("notion_import.choose_file")}>
+ <FormFileUpload onChange={onChange} />
+ </FormGroup>
+ </div>
+ );
+}
+
+const provider: ImportProvider = {
+ id: "notion",
+ name: t("notion_import.name"),
+ icon: "bx bxs-file-archive",
+ description: t("notion_import.description"),
+ Panel: NotionPanel
+};
+
+export default provider;
diff --git a/apps/server/src/assets/translations/en/server.json b/apps/server/src/assets/translations/en/server.json
index fc718877ed..67a19bfc78 100644
--- a/apps/server/src/assets/translations/en/server.json
+++ b/apps/server/src/assets/translations/en/server.json
@@ -319,6 +319,9 @@
"onenote_import": {
"root-title": "OneNote import"
},
+ "notion_import": {
+ "root-title": "Notion import"
+ },
"pdf": {
"export_filter": "PDF Document (*.pdf)",
"unable-to-export-message": "The current note could not be exported as a PDF.",
diff --git a/apps/server/src/routes/api/notion_import.ts b/apps/server/src/routes/api/notion_import.ts
new file mode 100644
index 0000000000..cc0b4f5a0e
--- /dev/null
+++ b/apps/server/src/routes/api/notion_import.ts
@@ -0,0 +1,34 @@
+/**
+ * REST endpoint for the Notion importer. Accepts a multipart upload of a Notion HTML-export zip and
+ * kicks off the structural import in the background, reporting progress over the WebSocket via the
+ * shared "importNotes" task type.
+ *
+ * POST /api/notion-import/import (multipart: `upload` = .zip, `parentNoteId`, `taskId`) -> {}
+ */
+
+import { becca, ValidationError } from "@triliumnext/core";
+import type { Request } from "express";
+
+import importer from "../../services/import/notion/importer.js";
+
+function runImport(req: Request) {
+ const { parentNoteId, taskId } = req.body as { parentNoteId?: string; taskId?: string };
+ if (!parentNoteId || !taskId) {
+ throw new ValidationError("parentNoteId and taskId are required.");
+ }
+
+ const file = req.file;
+ if (!file || typeof file.buffer === "string") {
+ throw new ValidationError("No zip file has been uploaded.");
+ }
+
+ becca.getNoteOrThrow(parentNoteId);
+
+ // Fire-and-forget: a large export can take far longer than the client's HTTP request timeout, so we
+ // return immediately and let the import report progress, completion and any error over the WebSocket
+ // (taskType "importNotes"). importZip catches and reports its own failures, so it never rejects here.
+ void importer.importZip({ fileBuffer: file.buffer, parentNoteId, taskId });
+ return {};
+}
+
+export default { runImport };
diff --git a/apps/server/src/routes/routes.ts b/apps/server/src/routes/routes.ts
index 40b65766be..91e1158a7f 100644
--- a/apps/server/src/routes/routes.ts
+++ b/apps/server/src/routes/routes.ts
@@ -17,25 +17,25 @@ import etapiSpecialNoteRoutes from "../etapi/special_notes.js";
import auth from "../services/auth.js";
import openID from '../services/open_id.js';
import { isElectron } from "../services/utils.js";
-
import shareRoutes from "../share/routes.js";
import clipperRoute from "./api/clipper.js";
import databaseRoute from "./api/database.js";
import etapiTokensApiRoutes from "./api/etapi_tokens.js";
import filesRoute from "./api/files.js";
import fontsRoute from "./api/fonts.js";
+// API routes
+import linkEmbedRoute from "./api/link_embed.js";
import llmChatRoute from "./api/llm_chat.js";
import llmSpecialNotesRoute from "./api/llm_special_notes.js";
import loginApiRoute from "./api/login.js";
import metricsRoute from "./api/metrics.js";
+import notionImportRoute from "./api/notion_import.js";
import ocrRoute from "./api/ocr.js";
import onenoteImportRoute from "./api/onenote_import.js";
import recoveryCodes from './api/recovery_codes.js';
import senderRoute from "./api/sender.js";
import systemInfoRoute from "./api/system_info.js";
import totp from './api/totp.js';
-// API routes
-import linkEmbedRoute from "./api/link_embed.js";
import { doubleCsrfProtection as csrfMiddleware } from "./csrf_protection.js";
import * as indexRoute from "./index.js";
import loginRoute from "./login.js";
@@ -192,6 +192,10 @@ function register(app: express.Application) {
asyncApiRoute(GET, "/api/onenote-import/notebooks", onenoteImportRoute.getNotebooks);
asyncApiRoute(PST, "/api/onenote-import/import", onenoteImportRoute.runImport);
+ // Notion importer: a multipart upload of the export zip (vs OneNote's API), so it needs the upload
+ // middleware + CSRF guard rather than the plain JSON `apiRoute` helper.
+ route(PST, "/api/notion-import/import", [auth.checkApiAuthOrElectron, uploadMiddlewareWithErrorHandling, csrfMiddleware], notionImportRoute.runImport, apiResultHandler);
+
shareRoutes.register(router);
etapiAuthRoutes.register(router, [loginRateLimiter]);
diff --git a/apps/server/src/services/import/notion/importer.ts b/apps/server/src/services/import/notion/importer.ts
new file mode 100644
index 0000000000..c6085519b1
--- /dev/null
+++ b/apps/server/src/services/import/notion/importer.ts
@@ -0,0 +1,183 @@
+/**
+ * Imports a Notion HTML-export zip into a Trilium note tree.
+ *
+ * Notion exports each page as `Page Title <id>.html`; a page that has children also gets a sibling
+ * folder `Page Title <id>/` holding those children. Internal links and attachments reference the same
+ * id-suffixed names. This first iteration reconstructs only the *structure* — the page hierarchy, titles
+ * and original timestamps — copying each page's body HTML across roughly as-is. Faithful HTML cleanup,
+ * link rewriting, images/attachments and database (CSV) handling are deliberately deferred.
+ *
+ * Like the OneNote importer, it runs in the background and reports progress, completion and failure over
+ * the WebSocket via an "importNotes" TaskContext, so it never throws to the caller.
+ */
+
+import { becca, date_utils, getLog, getZipProvider, note_service as noteService, protected_session as protectedSession, sanitize, TaskContext } from "@triliumnext/core";
+import { t } from "i18next";
+import { type HTMLElement, parse } from "node-html-parser";
+
+import sql from "../../sql.js";
+import { getNotionId, parseParentIds, stripNotionId } from "./notion_id.js";
+
+interface ParsedPage {
+ /** The page's own Notion id, used to resolve child pages and (later) internal links to it. */
+ id: string;
+ title: string;
+ /** Path of the .html entry inside the zip; retained for diagnostics. */
+ path: string;
+ /** Notion ids of ancestor pages (outermost first); the last is this page's immediate parent. */
+ parentIds: string[];
+ /** The page's body HTML, sanitized; empty when the body could not be located. */
+ content: string;
+ utcDateCreated?: string;
+ utcDateModified?: string;
+}
+
+export async function importZip({ fileBuffer, parentNoteId, taskId }: { fileBuffer: Uint8Array; parentNoteId: string; taskId: string }): Promise<void> {
+ const taskContext = TaskContext.getInstance(taskId, "importNotes", { safeImport: true });
+
+ try {
+ const pages = await parsePages(fileBuffer);
+ taskContext.setTotalCount(pages.length);
+
+ const rootNoteId = sql.transactional(() => createNotes(parentNoteId, pages, taskContext));
+
+ taskContext.taskSucceeded({ parentNoteId, importedNoteId: rootNoteId });
+ } catch (e: unknown) {
+ getLog().error(`Notion import failed: ${e instanceof Error ? (e.stack ?? e.message) : e}`);
+ taskContext.reportError(e instanceof Error ? e.message : String(e));
+ }
+}
+
+/** Reads every page (.html entry) out of the zip, parsing its title, ancestry, dates and body HTML. */
+async function parsePages(fileBuffer: Uint8Array): Promise<ParsedPage[]> {
+ const provider = getZipProvider();
+ const filenameEncoding = await provider.detectFilenameEncoding(fileBuffer);
+
+ const pages: ParsedPage[] = [];
+ await provider.readZipFile(fileBuffer, async (entry, readContent) => {
+ const path = entry.fileName;
+ // Notion exports the page body as HTML; everything else (images, the per-database CSV, the
+ // summary index.html) is deferred to a later iteration.
+ if (!path.toLowerCase().endsWith(".html") || isDirectory(path) || baseName(path) === "index.html") {
+ return;
+ }
+
+ const html = new TextDecoder().decode(await readContent());
+ const parsed = parsePage(path, html);
+ if (parsed) {
+ pages.push(parsed);
+ }
+ }, filenameEncoding);
+
+ return pages;
+}
+
+function parsePage(path: string, html: string): ParsedPage | null {
+ const root = parse(html);
+
+ // The page's own id is on the top-level element inside <body> (Notion gives it `id="<uuid>"`);
+ // fall back to the id suffix on the filename so a structurally-odd page still lands somewhere.
+ const body = root.querySelector("body");
+ const id = firstChildNotionId(body) ?? getNotionId(baseName(path));
+ if (!id) {
+ return null;
+ }
+
+ const title = root.querySelector("title")?.textContent?.trim() || stripNotionId(removeExtension(baseName(path))) || "Untitled";
+
+ const pageBody = root.querySelector(".page-body");
+ const content = pageBody ? sanitize.sanitizeHtml(pageBody.innerHTML) : "";
+
+ return {
+ id,
+ title,
+ path,
+ parentIds: parseParentIds(path),
+ content,
+ utcDateCreated: extractDate(root, "property-row-created_time"),
+ utcDateModified: extractDate(root, "property-row-last_edited_time")
+ };
+}
+
+/**
+ * Creates the note tree. Pages are created shallowest-first so a page's parent always exists before it;
+ * each page is parented under the note created for its immediate-parent id, or under the import root when
+ * it has no (resolvable) parent. Returns the import root's note id.
+ */
+function createNotes(parentNoteId: string, pages: ParsedPage[], taskContext: TaskContext<"importNotes">): string {
+ const parentNote = becca.getNoteOrThrow(parentNoteId);
+ const isProtected = parentNote.isProtected && protectedSession.isProtectedSessionAvailable();
+
+ const rootNote = noteService.createNewNote({ parentNoteId, title: t("notion_import.root-title"), content: "", type: "text", mime: "text/html", isProtected }).note;
+ rootNote.addLabel("iconClass", "bx bx-import");
+
+ const noteIdByPageId = new Map<string, string>();
+ const ordered = [...pages].sort((a, b) => a.parentIds.length - b.parentIds.length);
+
+ for (const page of ordered) {
+ const parentPageId = page.parentIds[page.parentIds.length - 1];
+ const targetParentId = (parentPageId && noteIdByPageId.get(parentPageId)) || rootNote.noteId;
+
+ const { note } = noteService.createNewNote({
+ parentNoteId: targetParentId,
+ title: page.title,
+ content: page.content,
+ type: "text",
+ mime: "text/html",
+ isProtected
+ });
+ noteIdByPageId.set(page.id, note.noteId);
+
+ // Preserve Notion's original timestamps. Must run after createNewNote's content save, which would
+ // otherwise re-stamp the modification date with "now".
+ if (page.utcDateCreated || page.utcDateModified) {
+ note.setDateCreatedAndModified(page.utcDateCreated, page.utcDateModified ?? page.utcDateCreated);
+ }
+
+ taskContext.increaseProgressCount();
+ }
+
+ return rootNote.noteId;
+}
+
+/** Returns the Notion id of the first child element of `body` that carries one (Notion's page wrapper). */
+function firstChildNotionId(body: HTMLElement | null): string | undefined {
+ if (!body) {
+ return undefined;
+ }
+ for (const child of body.querySelectorAll("*")) {
+ const id = getNotionId(child.getAttribute("id") ?? "");
+ if (id) {
+ return id;
+ }
+ }
+ return undefined;
+}
+
+/**
+ * Reads a Notion property-row timestamp (created/last-edited) from the page's properties table and
+ * converts it to Trilium's UTC DB format. Returns undefined when the row, the <time> element or the
+ * parsed date is missing/invalid.
+ */
+function extractDate(root: HTMLElement, rowClass: string): string | undefined {
+ const text = root.querySelector(`tr.${rowClass} time`)?.textContent?.replace(/@/g, "").trim();
+ if (!text) {
+ return undefined;
+ }
+ const date = new Date(text);
+ return Number.isNaN(date.getTime()) ? undefined : date_utils.utcDateTimeStr(date);
+}
+
+function isDirectory(path: string): boolean {
+ return path.endsWith("/");
+}
+
+function baseName(path: string): string {
+ return path.split("/").pop() ?? path;
+}
+
+function removeExtension(name: string): string {
+ return name.replace(/\.[^.]+$/, "");
+}
+
+export default { importZip };
diff --git a/apps/server/src/services/import/notion/notion_id.spec.ts b/apps/server/src/services/import/notion/notion_id.spec.ts
new file mode 100644
index 0000000000..fcebbff342
--- /dev/null
+++ b/apps/server/src/services/import/notion/notion_id.spec.ts
@@ -0,0 +1,51 @@
+import { describe, expect, it } from "vitest";
+
+import { getNotionId, parseParentIds, stripNotionId } from "./notion_id.js";
+
+const ID = "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d";
+
+describe("getNotionId", () => {
+ it("extracts the 32-hex id from a Notion file or folder name", () => {
+ expect(getNotionId(`My Page ${ID}.html`)).toBe(ID);
+ expect(getNotionId(`My Page ${ID}`)).toBe(ID);
+ });
+
+ it("extracts the id from a hyphenated UUID and from a query-suffixed URL", () => {
+ // Notion sometimes hyphenates the id; the hyphens are stripped before matching.
+ expect(getNotionId("My Page 1a2b3c4d-5e6f-7a8b-9c0d-1e2f3a4b5c6d.html")).toBe(ID);
+ expect(getNotionId(`image.png?table=block&id=${ID}`)).toBe(ID);
+ });
+
+ it("returns undefined when there is no id", () => {
+ expect(getNotionId("Workspace")).toBeUndefined();
+ expect(getNotionId("index.html")).toBeUndefined();
+ });
+});
+
+describe("stripNotionId", () => {
+ it("removes the trailing id while keeping the extension", () => {
+ expect(stripNotionId(`My Page ${ID}.html`)).toBe("My Page.html");
+ expect(stripNotionId(`My Page ${ID}`)).toBe("My Page");
+ });
+
+ it("leaves names without an id untouched", () => {
+ expect(stripNotionId("Workspace")).toBe("Workspace");
+ });
+});
+
+describe("parseParentIds", () => {
+ it("returns the ids of ancestor folders, outermost first", () => {
+ const parentId = "0000000000000000000000000000aaaa";
+ const grandParentId = "0000000000000000000000000000bbbb";
+ expect(parseParentIds(`Export/Grandparent ${grandParentId}/Parent ${parentId}/Child ${ID}.html`))
+ .toEqual([grandParentId, parentId]);
+ });
+
+ it("drops folder segments that carry no id (e.g. the workspace root)", () => {
+ expect(parseParentIds(`Export/Child ${ID}.html`)).toEqual([]);
+ });
+
+ it("returns an empty array for a top-level file", () => {
+ expect(parseParentIds(`Child ${ID}.html`)).toEqual([]);
+ });
+});
diff --git a/apps/server/src/services/import/notion/notion_id.ts b/apps/server/src/services/import/notion/notion_id.ts
new file mode 100644
index 0000000000..2f6f5e6fe0
--- /dev/null
+++ b/apps/server/src/services/import/notion/notion_id.ts
@@ -0,0 +1,34 @@
+/**
+ * Notion-export identity helpers. Every page/attachment Notion exports carries a 32-character hex id
+ * appended to its file and folder names ("Page Title <id>.html", "Page Title <id>/"), and internal
+ * links reference those same names. These helpers extract and strip those ids and derive a page's
+ * ancestry from its path inside the zip.
+ *
+ * Ported from Obsidian's importer (https://github.com/obsidianmd/obsidian-importer,
+ * src/formats/notion/notion-utils.ts and parse-info.ts), MIT-licensed, © 2023 Obsidian.
+ */
+
+/** Strips the trailing Notion id (and its separating space/hyphen) from a name, keeping the extension. */
+export function stripNotionId(id: string): string {
+ return id.replace(/-/g, "").replace(/[ -]?[a-z0-9]{32}(\.|$)/, "$1");
+}
+
+/** Extracts the 32-hex Notion id embedded at the end of a filename or URL path, or undefined if absent. */
+export function getNotionId(id: string): string | undefined {
+ return id.replace(/-/g, "").match(/([a-z0-9]{32})(\?|\.|$)/)?.[1];
+}
+
+/**
+ * Returns the Notion ids of a file's ancestor pages, outermost first, read from its folder path inside
+ * the zip. Folder segments without an id (e.g. the export's top-level workspace folder) are dropped, so
+ * the last entry is the file's immediate parent page.
+ */
+export function parseParentIds(filePath: string): string[] {
+ // Zip entry names always use forward slashes, so split on "/" directly (rather than a node `path`
+ // helper, whose behaviour differs on Windows) and drop the last segment (the file itself).
+ const segments = filePath.split("/");
+ segments.pop();
+ return segments
+ .map((segment) => getNotionId(segment))
+ .filter((id): id is string => !!id);
+}