Copy to Clipboard
Published on
The modern way to copy text to the clipboard. No hidden textareas, no document.execCommand — just the Async Clipboard
API that works in all modern browsers.
async function copyToClipboard(text: string): Promise<boolean> { try { await navigator.clipboard.writeText(text); return true; } catch { return false; } }
React Component
A copy button with visual feedback — shows a checkmark for 2 seconds after a successful copy:
function CopyButton({ text }: { text: string }) { const [copied, setCopied] = React.useState(false); const handleCopy = async () => { const success = await copyToClipboard(text); if (success) { setCopied(true); setTimeout(() => setCopied(false), 2000); } }; return ( <button onClick={handleCopy} aria-label="Copy to clipboard"> {copied ? '✓ Copied' : 'Copy'} </button> ); }
The Clipboard API requires a secure context ( HTTPS or localhost). It won't work on plain HTTP pages.