navigator.clipboard.writeText() is the modern way to copy text to the clipboard, a clean one-liner. The little touch I always like adding is a quick “Copied!” confirmation on the button itself, so the user knows the click actually did something. Here’s a quick way I like to do it.

async function copyWithFeedback(text, button) {
  try {
    await navigator.clipboard.writeText(text);
    const original = button.textContent;
    button.textContent = "Copied!";
    button.classList.add("copied");
    setTimeout(() => {
      button.textContent = original;
      button.classList.remove("copied");
    }, 1500);
  } catch (err) {
    console.error("Copy failed:", err);
  }
}
<button onclick="copyWithFeedback('hello world', this)">Copy</button>

Result

npx create-astro@latest

A few things worth knowing —

  • navigator.clipboard only works in secure contexts (HTTPS or localhost). On HTTP it’ll be undefined.
  • It returns a Promise, so always await or .catch() the rejection.
  • Some browsers will silently fail if the call isn’t triggered by a user gesture (a click, a keypress) — keep it inside an event handler.

For the edge case where navigator.clipboard isn’t available, the old document.execCommand('copy') fallback still works on a hidden textarea, but in 2025 that should be rare enough to skip.