Structured data
react-smart-copy/structured puts your app’s own data on the clipboard: invoice rows, a
dashboard widget, a form’s configuration, a set of shapes. Paste it in another tab, another
window or another of your apps and you get the same typed objects back, validated against
your schema. Text editors, chat and mail get readable text and HTML instead. No dependencies,
about 1.9 kB for the copy side.
Try it
Section titled “Try it”No cards selected: all cards will be copied.
Cards can also be dragged. Paste into a text editor or a mail to see the readable version.
Backlog
Click here and press Ctrl + V or ⌘ + V, or drop cards here.
Nothing pasted yet.
Objects in, objects out
clipPayload writes the cards three ways: a web custom format, a custom clipboard type and a
hidden envelope in the HTML. The paste button, Ctrl + V and drops each read a
different one, so every path in every browser finds the cards.
Whatever is pasted is checked before your code sees it: size-limited, parsed without prototype keys, migrated from older versions, then validated. "Copy a tampered clip" writes the same format with bad data, the way a buggy or hostile app could.
import { clipAccept, clipPayload, defineClipFormat, readClip } from 'react-smart-copy/structured';
const Cards = defineClipFormat({
id: 'acme.cards',
version: 2,
schema: z.array(Card), // or Valibot, ArkType, a function
migrate: { 1: (cards) => addTags(cards) },
});
copy(() => clipPayload(Cards, selected));
usePaste({ accept: clipAccept(Cards), onPaste: async (result) => {
const clip = await readClip(result, Cards);
if (clip.status === 'ok') addToBacklog(clip.value);
} });
import { z } from "zod"; // or Valibot, ArkType, any Standard Schema, or a plain functionimport { useCopy, usePaste } from "react-smart-copy";import { clipAccept, clipPayload, defineClipFormat, readClip } from "react-smart-copy/structured";
// Define each format once and share it between the copying and the pasting code.export const InvoiceRows = defineClipFormat({ id: "acme.invoice-rows", // namespaced, stable: it names the clipboard type version: 2, schema: z.array(z.object({ id: z.string(), amount: z.number(), issued: z.coerce.date() })), migrate: { 1: (rows) => upgradeFromV1(rows) }, // data from older deployments still pastes text: (rows) => rows.map((row) => `${row.id}\t${row.amount}`).join("\n"),});
function CopyRows({ rows }: { rows: Invoice[] }) { const { copy } = useCopy(); return <button onClick={() => void copy(() => clipPayload(InvoiceRows, rows))}>Copy rows</button>;}
function PasteRows({ onRows }: { onRows: (rows: Invoice[]) => void }) { const { paste, targetProps } = usePaste<HTMLDivElement>({ accept: [...clipAccept(InvoiceRows), "text"], onPaste: async (result) => { const clip = await readClip(result, InvoiceRows); switch (clip.status) { case "ok": return onRows(clip.value); // typed, validated, migrated case "invalid": return report(clip.issues); // [{ message, path }] case "unsupported-version": return askToReload(); // written by a newer deployment case "absent": return; // not ours: handle result.text if you like } }, }); return <div {...targetProps} tabIndex={0}>Paste rows here <button onClick={() => void paste()}>Paste</button></div>;}clipPayload works everywhere a payload does: copy(), a useCopyInterceptor transform (so
Ctrl/⌘+C on selected rows copies the objects) and a useDragCopy source. readClip reads from a
PasteResult (paste button, Ctrl/⌘+V, drops, PasteField), a raw DataTransfer or a payload.
Use readClipSync when you need the answer synchronously and your schema is synchronous.
Why three carriers. No single clipboard entry survives every path in every browser, so each
copy writes three and readClip takes the first that holds this format:
| Carrier | Written by | Read back by |
|---|---|---|
web application/vnd.<id>+json |
copy() in Chromium |
the paste button (clipboard.read()), also across origins. Hidden from paste events |
application/vnd.<id>+json |
copy interceptor, drag | Ctrl/⌘+V and drops. Hidden from clipboard.read() |
hidden envelope in text/html |
every path | every path, every browser, including Safari and Firefox |
Security. The clipboard is untrusted input: any page or app can put any format on it, so the data is never trusted, only checked.
- Each carrier is size-checked (
maxBytes, default 8 MiB) before it is parsed or decoded - Own
__proto__keys are dropped while parsing, so merging pasted data can’t swap a prototype - Migrations run on untrusted data, then the schema validates the result; nothing unvalidated reaches
clip.value - The HTML carrier is found with a strict token match on a closed alphabet (
id;base64url): no HTML parsing, no DOM - Reading never throws for clipboard content: every outcome is a result
- The data is not authenticated. Validate it as you would a form submission, and check permissions server-side
- The HTML envelope travels wherever the HTML is pasted (a mail, a document), hidden but readable. Copy only what the user may share, or set
embedInHtml: false(keyboard paste in Chromium and drops still work through the custom type)
Copying is strict too. The data must survive JSON.stringify unchanged: NaN, Infinity,
BigInt, Map, Set, functions and symbols throw an invalid-payload error naming the key
instead of turning silently into null or {}. Dates become ISO strings, so read them back with a
coercing schema (z.coerce.date()), or convert in encode.