Offline files and durability

Store an attachment in OPFS

Write and read an origin-private attachment file without confusing browser-managed files with user-visible documents.

8 minute lesson

~~~

OPFS gives an origin a private filesystem. Its files are not normal files the user browses in Finder or Explorer.

Get the origin root, create a file handle, open a writable stream, write the contents, and close the stream. The data shares the origin’s storage quota and disappears when the user clears site data.

const root = await navigator.storage.getDirectory()
const file = await root.getFileHandle('trail.txt', { create: true })
const writable = await file.createWritable()
await writable.write('North trail closed after rain')
await writable.close()

const saved = await file.getFile()
console.log(await saved.text())

Use IndexedDB for searchable note metadata and OPFS for file bytes. Store a stable attachment identifier in the note instead of pretending a file handle is permanent business data.

OPFS avoids a user permission prompt because the files stay inside the origin. Use a download or file-picker flow when the user expects a visible file they control.

Write one text attachment, link its filename from an IndexedDB note, reload, and read it back. Then delete site data and confirm both the database and file disappear.

Lesson completed

Take this course offline

Get every free book and course as PDF and EPUB files.

Get the download library →