# How share works in eLNotes. A step by step guide.

Published: 2026-10-31
Canonical: https://mrinmay.dev/blog/how-share-works-in-elnotes/

How a local-first app with no user accounts and no central database moves a note from one browser to another.

In [eLNotes](https://elnotes.com) and [slides.eLNotes](https://slides.elnotes.com), your notes or slides live in `IndexedDB` inside the browser. There are no user accounts and no central database of your content on my server.

That makes sharing an interesting problem. In a typical app, sharing just means flipping a permission bit on a database row and handing out a link. Here, the content only exists inside one browser on one device.

If I want to send a note to a friend, or move it to my phone, it has to travel from my browser's `IndexedDB` into theirs through a server that is not supposed to read it or hold onto it. So how do we actually pull that off? (Both apps use the exact same sharing pipeline, so for the sake of simplicity I'll only talk about notes moving forward.)

## Step 1: Pack the note and its images

A note in eLNotes is an HTML string from the editor, but its images do not live inside the HTML. Each image is stored as a binary `Blob` in `IndexedDB`, and the note only holds a reference like `<img data-image-id="...">`.

If I only shared the HTML string, the recipient would get broken image tags pointing to IDs that only exist on my machine. Before encrypting, `ShareModal` walks the note HTML, pulls up to 20 referenced image blobs out of `IndexedDB`, and base64-encodes them into the snapshot:

```ts
const images = await extractImageBlobsForSharing(content);
const payload = { title, content, images };
```

That plaintext snapshot is capped at 3 MB (`SHARE_PAYLOAD_MAX_BYTES`) so a note full of screenshots cannot blow up the upload.

*There's an interactive demo here. [Try it on the site](https://mrinmay.dev/blog/how-share-works-in-elnotes/).*
## Step 2: Encrypt in the browser and keep the passcode in the hash

Before anything touches the network, the browser generates a random 4-digit passcode (`0000` to `9999`) using rejection sampling over `crypto.getRandomValues` so every code is equally likely:

```ts

  const limit = 0x10000 - (0x10000 % PASSCODE_MODULUS);
  const buf = new Uint16Array(1);
  let value: number;
  do {
    crypto.getRandomValues(buf);
    value = buf[0];
  } while (value >= limit);
  return String(value % PASSCODE_MODULUS).padStart(PASSCODE_DIGITS, "0");
}
```

Four digits sounds short for an encryption secret, and on its own it would be. Here it sits behind three constraints: you first need the random 8-character `shareId`, `/api/share` is rate-limited, and the snapshot disappears from KV after 180 seconds. To make offline guessing expensive too, `deriveAesKey` stretches the passcode through `PBKDF2` (`SHA-256`, 210,000 iterations) with a random 16-byte salt to derive a 256-bit `AES-GCM` key.

`encryptSharePayload` encrypts the JSON snapshot with that key and a random 12-byte IV, returning an envelope of base64 strings:

```ts
return {
  version: SHARE_CRYPTO_VERSION,
  salt: bytesToBase64(salt),
  iv: bytesToBase64(iv),
  ciphertext: bytesToBase64(new Uint8Array(ciphertextBuffer)),
};
```

Why a 4-digit passcode instead of a long key in the URL? Some chat apps and link unfurlers strip the `#fragment` when you paste a link. When that happens, a 4-digit code is short enough to read off the share dialog and type by hand on the other device.

*There's an interactive demo here. [Try it on the site](https://mrinmay.dev/blog/how-share-works-in-elnotes/).*
## Step 3: Store the ciphertext in KV for 180 seconds

The browser `POST`s the encrypted envelope to `/api/share` on the Cloudflare Worker (`elnotes-server/src/routes/share.ts`). The title, HTML, images, and passcode never leave the browser in plaintext.

The Worker validates the envelope shape, checks that the serialized body is under 5 MB (leaving headroom for base64 and JSON overhead on a 3 MB note), generates an 8-character alphanumeric ID with `nanoid`, and writes the envelope to Cloudflare KV with a 180-second TTL:

```ts
const { customAlphabet } = await import("nanoid");
const generateShareId = customAlphabet(SHARE_ID_ALPHABET, 8);
const shareId = generateShareId();
const note: SharedNote = {
  version: 1,
  salt: body.salt,
  iv: body.iv,
  ciphertext: body.ciphertext,
  createdAt: new Date().toISOString(),
};

await c.env.SHARE_NOTES.put(`note:${shareId}`, JSON.stringify(note), {
  expirationTtl: SHARE_TTL_SECONDS,
});

return jsonNoStore(c, { sharePath: `/share/${shareId}` });
```

Back in `ShareModal`, the browser attaches the passcode it kept in memory to `sharePath` as a URL fragment and starts a 3-minute countdown:

```ts
url: `${baseUrl}${data.sharePath}#${pendingPasscode}`
```

Because `#4827` is a URL fragment, browsers never send it over HTTP. Neither Netlify nor the Cloudflare Worker ever sees the passcode in request logs.

*There's an interactive demo here. [Try it on the site](https://mrinmay.dev/blog/how-share-works-in-elnotes/).*
## Step 4: Fetch the envelope and decrypt on `/share/$shareId`

When the recipient opens `https://elnotes.com/share/Ab12Cd34#4827`, the route in `share.$shareId.tsx` checks that `shareId` matches `/^[A-Za-z0-9_-]{8}$/` and fetches `GET /api/shared/Ab12Cd34` from the Worker. If the 180 seconds are already up, KV returns nothing and the page renders a "Shared Note Not Found" screen.

Once the encrypted envelope arrives, the route looks for the passcode in `window.location.hash`:

```ts
const hashPasscode = parseSharePasscodeFromHash(
  typeof window !== "undefined" ? window.location.hash : "",
);

if (hashPasscode) {
  void tryDecryptAndImport(hashPasscode, generation);
  return;
}

setNeedsPasscode(true);
```

When the `#4827` fragment is intact, `tryDecryptAndImport` re-derives the `AES-GCM` key from the envelope's `salt` and decrypts the note in the background. The recipient never sees a passcode form.

If a chat app stripped the `#fragment` from the URL, or if `AES-GCM` authentication fails because the code was edited, `needsPasscode` flips to `true` and the route renders a 4-digit passcode input so the recipient can enter it manually.

*There's an interactive demo here. [Try it on the site](https://mrinmay.dev/blog/how-share-works-in-elnotes/).*
## Step 5: Mint new IDs and import into IndexedDB

Decryption yields the original `{ title, content, images }` plaintext. Rather than rendering a read-only page backed by the server, `importPlaintext` immediately saves the note into the recipient's own `IndexedDB` with a fresh `uuidv4()`:

```ts
const newNoteId = uuidv4();
const newNote = {
  id: newNoteId,
  title: title || "Shared Note",
  urlSlug: createNoteSlug(title || "Shared Note") || null,
  content,
  createdAt: Date.now(),
  updatedAt: Date.now(),
  order: Date.now(),
};

await addExistingNote(newNote);
```

Minting a new UUID on import means opening your own share link, or importing the same link twice, creates a clean copy instead of overwriting an existing note.

The images need new IDs for the same reason. `storeSharedImages` converts each base64 string back into a `Blob`, stores it in the recipient's `IndexedDB` under a new image UUID, and returns a map of `{ [oldId]: newId }`. Then `updateImageIdsInContent` rewrites every `data-image-id` in the note HTML to point at the newly stored blobs:

```ts
if (images.length > 0) {
  const idMapping = await storeSharedImages(newNoteId, images);
  const updatedContent = updateImageIdsInContent(content, idMapping);
  if (updatedContent !== content) {
    const { updateNote } = useNotesStore.getState();
    await updateNote(newNoteId, title, updatedContent);
  }
}
```

Once the note and its images are saved locally, the router navigates straight from `/share/Ab12Cd34` to `/note/$noteId`.

*There's an interactive demo here. [Try it on the site](https://mrinmay.dev/blog/how-share-works-in-elnotes/).*
## Conclusion

In the end, sharing in eLNotes is just a three-minute encrypted dead drop. Your browser packs the note, locks it with a passcode that stays in the URL hash, and drops the ciphertext into Cloudflare KV. The recipient's browser grabs the blob, unlocks it locally, and saves a fresh copy into its own `IndexedDB`.

Two minutes later, the KV entry expires and vanishes. No user accounts, no permanent database rows, and nothing readable left behind on the server.
