Developers · Share links

Share links

Publish one record as a public, read-only link. Anyone with the link can open it without an account. Your app renders the shared record on its own URL.

Sharing needs a synced store and a signed-in connection. A share is a record in the reserved _civility.shares collection. When that record syncs, the server makes the share public. When it is deleted, the server stops serving it.

Turn on sharing

Add a share option. CloudStore then declares and syncs _civility.shares for you.

// store.ts
import { CloudStore } from '@civility/cloud'
import { IDBStorage } from '@civility/cloud/storage/idb'

export const APP_ID = 'app-k3m7q2x4p6w5z7n3b2v4c6h5'

export type Note = { title: string; body: string }

export const cloud = new CloudStore({
  id: APP_ID,
  storage: { db: new IDBStorage() },
  collections: ['notes'],
  versions: [{
    version: '1.0.0',
    schema: { type: 'object', properties: { notes: { type: 'object' } } },
  }],
  cloud: { appId: APP_ID },
  share: { appShareUrl: 'https://notes.example/' },
})

export const notes = cloud.collection<Note>('notes')

appShareUrl is the page in your app that renders shares. Share links are <appShareUrl>?id=<shareId>&server=<serverOrigin>.

Publish and revoke

cloud.share is available once the store has a server. It throws before that, so check cloud.canShare first.

if (!cloud.canShare) await cloud.resume()

const { id, url } = await cloud.share.publish({
  collection: 'notes',
  docId,
})
Method Does
publish(ref, options?) Creates the share and returns { id, url, record }. Publishing the same record again returns the existing share.
list() Returns this user's shares as ShareRecord[], read locally.
revoke(id) Deletes the share. The link returns 404 after the next sync.
urlFor(id) Returns the link for a share id.
stats(ids) Returns view counts from the server.

publish returns the link right away, even offline. The link works after the share record has synced.

publish option Notes
frozen true serves the record as it was when published. By default the share follows later edits.
visibility 'public', 'unlisted' or 'restricted'.
recipients [{ handle, permission? }]. Limits the share to named users. Requires 'restricted'.

Share UI

@civility/cloud/ui has three elements for sharing. You give them callbacks; they do not import the store. See the note on @inro/ui.

Element Set Events
<civ-share-dialog> open, methods (SharePublisher), share (ShareView), heading on-published, on-revoked, dismiss
<civ-shares-list> shares (ShareView[]), methods (ShareRevoker), empty-text on-revoked
<civ-share-link> Shows one link with a copy button.
import '@civility/cloud/ui'
import type { SharePublisher, ShareView } from '@civility/cloud/ui'
import { cloud, notes } from './store.ts'

function publisherFor(docId: string): SharePublisher {
  return {
    async publish(): Promise<ShareView> {
      if (!cloud.canShare) throw new Error('Connect to a server first.')
      const { id, url } = await cloud.share.publish({
        collection: 'notes',
        docId,
      })
      return { id, url, label: (await notes.get(docId))?.title }
    },
    revoke: (id) => cloud.share.revoke(id),
  }
}

const dialog = document.querySelector('civ-share-dialog')!
Object.assign(dialog, { methods: publisherFor(docId), open: true })

For a list of all shares, map the records to views:

const records = await cloud.share.list()
const shares: ShareView[] = records.map((r) => ({
  id: r.id,
  url: cloud.share.urlFor(r.id),
  createdAt: r.createdAt,
}))

Object.assign(document.querySelector('civ-shares-list')!, {
  shares,
  methods: { revoke: (id: string) => cloud.share.revoke(id) },
})

Render a share

Civility has no share viewer. Your app reads the id and server query parameters and fetches the record with getShare. No sign-in is needed. Import it from @civility/cloud/api so the page does not load the store.

import { z } from '@zod/zod'
import { getShare } from '@civility/cloud/api'
import { APP_ID } from './store.ts'

const Note = z.object({ title: z.string(), body: z.string() })

const params = new URLSearchParams(location.search)
const id = params.get('id')
const server = params.get('server')

if (id && server) {
  const note = await getShare(APP_ID, id, { server, schema: Note })
  document.querySelector('h1')!.textContent = note.title
  document.querySelector('article')!.textContent = note.body
}

The server parameter and the data it returns are untrusted.

  • Pass a schema. getShare throws if the data does not match.
  • Insert values as text, not HTML. escapeStrings: true also HTML-escapes every string in the result.
  • A missing or revoked share rejects with a CivilityApiError whose code is sync.share_not_found.

For a blob the shared record references, use getShareBlob(appId, id, hash, { server, mime }). It returns a Blob.

Shares are not encrypted

The server and every visitor read the record as stored. 'restricted' visibility limits who can fetch it; it does not encrypt it. To share confidential data, store your own encrypted format and give visitors the key another way.

Reference