Skip to content
Engineering note7 min read

Autosave Is a State Machine: Building Iokeep's Lexical Editor

A source-level look at Iokeep's rich-text editor: idle-triggered persistence, create-versus-update transitions, preview synchronization, and the failure modes still left to solve.

lexical · nextjs · react · autosave · typescript

The hard part of adding Lexical to Iokeep was not rendering a toolbar. It was keeping three representations of a note coherent:

  1. the live editor state in the browser;
  2. the compact preview in the note list;
  3. the persisted record behind an Express API.

That turns autosave into a small distributed-systems problem. Even without collaboration or offline support, the browser and server can disagree, requests can fail, and initialization can look like user input.

This is how the current implementation works, why I made those choices, and where I would harden it next.

The Actual Boundary

Iokeep is split across two applications:

Lexical editor
    ↓
Next.js /be rewrite
    ↓
Express notes API
    ↓
Prisma repository
    ↓
PostgreSQL

The editor is a client component inside a Next.js 15 App Router application. Browser requests use relative /be/... URLs; a Next.js rewrite forwards them to the backend selected for the current environment. That keeps backend location out of feature code and gives the browser a same-origin path for the API's cookie-based authentication.

The backend stores editorState as a string. On save, the frontend serializes editor.getEditorState().toJSON() and stringifies the result. On load, the saved string is passed back to Lexical as the composer's initial state.

This is deliberately direct: no HTML conversion and no second document format in the write path.

Autosave Starts With a Dirty-to-Idle Transition

I implemented autosave as a Lexical plugin rather than putting persistence inside the editor component. AutoSyncPlugin registers two listeners:

  • an update listener to detect editing activity;
  • a text-content listener to derive the note preview.

When an update represents a real edit, the plugin marks the editor as non-idle, clears the previous timeout, and schedules a new one for one second later. Continued typing keeps moving that deadline. When the timeout fires, the state changes back to idle.

A second effect watches that transition. It only starts persistence when the state moves from non-idle to idle.

editing → reset 1s timer → idle → synchronize

That distinction matters. Saving directly inside every editor update would flood the API. Running a periodic save loop would write unchanged content. Triggering on the transition expresses the real intent: persist after the user pauses.

Initialization Is Not an Edit

Hydrating a saved note also produces editor activity. Without a guard, opening a note can immediately send its unchanged state back to the server.

The plugin checks prevEditorState.isEmpty() before changing the idle state. The initial empty-to-hydrated transition is treated as setup noise; subsequent content changes can schedule a save.

The broader lesson is that editor events describe lifecycle activity, not necessarily user intent. Autosave needs an explicit definition of "dirty" instead of assuming every update should become a write.

One Editor, Two Persistence Paths

The same editor creates new notes and updates existing ones. The selected-note ID decides which path to take.

Creating the first persisted version

If a folder is selected but no note is selected, the plugin inspects the Lexical root and refuses to create a record when every child is blank. For non-empty content it sends:

POST /notes
{ folderId, editorState, description }

The create endpoint returns note metadata but intentionally omits the full editor state. The frontend already owns that state, so it combines the response with the local serialized document, adds the new note to the SWR cache, and selects the returned ID.

That last step is the state transition that prevents every later pause from creating another note. Once the ID exists, future synchronizations use the update path.

Updating an existing note

With a selected note, the plugin sends:

PATCH /notes/:noteId
{ noteData: { editorState, description } }

After the server confirms success, it updates the cached description used by the note list. This is a post-confirmation cache update, not an optimistic write with rollback.

That wording is important. The current implementation makes the list feel current after a successful request, but it does not claim that a failed write was persisted.

The Preview Is Derived Data

Each note card needs useful text without rendering a second Lexical editor. A text-content listener takes the editor's plain text, removes empty lines, and keeps the first two entries as description.

The backend stores that string array next to the serialized editor state. Folder and note lists can therefore render previews without parsing the full document.

This duplicates data, but it makes the read path simple. The invariant is that editor state and description must be written together. If preview generation later becomes more sophisticated, I would move it behind a versioned derivation function so old notes can be regenerated safely.

Why I Kept Lexical JSON

Lexical JSON is coupled to Lexical's node schema, which is a real trade-off. A future node change may require a document migration.

For the current editor, however, serialized state preserves headings and inline formatting exactly and hydrates without a lossy conversion step. Markdown would be more portable, but it would also introduce conversion rules for features that do not map cleanly in both directions.

The next architectural step is not automatically "replace JSON with Markdown." It is to add a document version, define migrations, and keep export formats separate from the canonical editing format.

Failure Modes the Current Version Exposes

Reading the complete flow made the remaining gaps clear.

A boolean cannot represent sync truth

The status bar currently knows only isSyncing: boolean. That gives it "Syncing" and "Synced," but no durable dirty, failed, retrying, or offline states. A rejected request can leave the UI without a trustworthy explanation of what happened.

I would replace it with an explicit state machine:

clean → dirty → saving → saved
                    ↘ failed → retrying

Failed writes need policy, not a console message

The save path has no retry queue, exponential backoff, or locally durable pending write. The next version should retain the unsaved revision, display the failure, and retry without allowing an older response to overwrite newer content.

Listener and timer cleanup should be explicit

Lexical registration functions return cleanup callbacks, and the idle timeout also has a lifecycle. A hardened plugin should unregister both listeners and clear the timeout when it unmounts or changes editor instances.

"Last request wins" is not enough

Rapid edits can produce overlapping network requests. The current API has no revision number or conditional update. Adding a monotonically increasing client revision, an updated-at precondition, or another concurrency token would make stale-response handling explicit.

Autosave is not offline-first

Iokeep currently persists to a remote API. It does not use IndexedDB, a background sync queue, CRDTs, or conflict resolution. Those are possible future directions, but they are not features I can claim today.

What I Learned

The useful abstraction was not "debounce a function." It was modeling the lifecycle of a note:

  • distinguish hydration from editing;
  • distinguish an unsaved draft from a persisted note;
  • treat previews as derived data with an invariant;
  • update client caches only according to what the server actually confirmed;
  • represent failure as a first-class state.

Lexical supplied the editor primitives. The engineering work was defining what a save means across the frontend/backend boundary.