Copy to Clipboard with Next.js
Explanation of how to copy to clipboard with Next.js. It also works with React.
2025-5-28
Use Clipboard API.
Define a function
const copyToClipboard = async (text: string) => {
try {
await navigator.clipboard.writeText(text);
} catch (err) {
console.error(err);
}
};
Note
We need to add "use client"
if we use it in the Next.js app directory.
Call the function
<button onClick={() => copyToClipboard('Copy')}>Copy</button>
Change the text when copied
A common use case is to change the text after copying to let the user know that
the text has been copied.
const [isCopied, setIsCopied] = useState(false);
const copyToClipboard = async (text: string) => {
try {
await navigator.clipboard.writeText(text);
setIsCopied(true);
setTimeout(() => {
setIsCopied(false);
}, 1000);
} catch (err) {
console.error(err);
}
};
return (
<button onClick={() => copyToClipboard('Copy')}>
{isCopied ? 'Copied!' : 'Copy'}
</button>
);