How do I copy a string to the clipboard?
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
Copying text to the clipboard is straightforward in modern browsers, but it is one of those tasks where environment rules matter. A reliable solution uses the async Clipboard API first, then falls back carefully for older browsers while keeping the user informed about success or failure.
Use the Modern Clipboard API
The preferred browser API is navigator.clipboard.writeText. It is promise-based, so you can await the result and only show success after the browser confirms the write.
This is the cleanest option because it does not require selection hacks or hidden inputs. It also makes error handling explicit.
Wrap Copy Logic in a Small Utility
Applications usually need clipboard support in more than one place. A helper function keeps the rest of the UI code simple.
That fallback uses document.execCommand('copy'), which is legacy but still useful when you must support older browser environments.
Example usage:
Understand the Browser Restrictions
Clipboard write access is intentionally limited.
- It usually requires HTTPS or localhost.
- It should be triggered by a user gesture such as a click.
- It may fail if permissions are denied or the tab is not in a suitable state.
That means code which works in local development can fail on a staging environment served over plain HTTP. The API is not broken in that case; the page is simply not in a trusted context.
You should also avoid surprising clipboard writes. Copying in response to a clear user action is good UX. Writing to the clipboard on page load or in a timer is usually blocked and can feel hostile even if it succeeds somewhere.
Add Good UX Around the Copy Action
The copy itself is only half the job. Users need to know whether it worked. A short visible message plus an aria-live region makes the interaction usable and accessible.
This prevents silent failure and gives screen-reader users the same confirmation as sighted users.
Common Pitfalls
- Calling clipboard code outside a user gesture often causes rejection in modern browsers.
- Testing only on localhost can hide HTTPS-related failures that appear later in staging or production.
- Assuming the fallback always works is risky because legacy copy commands are increasingly restricted.
- Copying raw text without trimming or formatting checks can give users an unexpected value.
- Logging errors only to the console leaves users with no clue whether the action succeeded.
Summary
- Prefer
navigator.clipboard.writeTextin modern browsers. - Use a small fallback utility only when older support is required.
- Trigger copy from explicit user interaction and in a secure context.
- Show visible and accessible success or failure feedback.
- Normalize the string before copying so the clipboard contains exactly what the user expects.

