---
title: Copy Button for Astro
description: Copy text with an Astro button or bind clipboard behavior to your own button.
seo:
    title: Copy Button for Astro | Shadcn & Tailwind CSS
    description: Astro button with built-in copy to clipboard functionality. Copy text with or bind clipboard behavior to your own button. Built on top of Shadcn UI and Tailwind CSS.
related:
    - /components/button
    - /components/code-block
    - /components/tooltip
sidebar:
    label: Copy Button
    badge: new
---

```astro
---
import { CopyButton } from "@/components/ui/copy-button"
---

<div class="flex items-center gap-2">
  <code>bun run build</code>
  <CopyButton value="bun run build" />
</div>
```

## Installation

### Command

```sh
bunx --bun shadcn@latest add @gnostic/copy-button
```

### Manual

Complete the [Installation guide](/docs/installation) first. Then copy the component files below.

No extra packages are required.

#### src/components/ui/copy-button/copy-button.astro

```astro
---
import type { HTMLAttributes } from "astro/types"
import Check from "@lucide/astro/icons/check"
import Copy from "@lucide/astro/icons/copy"
import { cn } from "cn"
import Button from "@/components/ui/button/button.astro"
import type { CopyButtonProps } from "./types.ts"

type Props = Omit<HTMLAttributes<"button">, "value"> & CopyButtonProps
const {
  class: className,
  value,
  timeout = 2000,
  variant = "ghost",
  size = "icon",
  "aria-label": label = "Copy to clipboard",
  ...props
} = Astro.props
---

<Button
  data-copy-control
  data-timeout={timeout}
  data-value={value}
  variant={variant}
  size={size}
  aria-label={label}
  class={cn("shrink-0 group/copy", className)}
  {...props}
>
  <slot>
    <Copy aria-hidden="true" class="group-data-copied/copy:hidden" />
    <Check aria-hidden="true" class="hidden group-data-copied/copy:block" />
  </slot>
</Button>
<span
  data-copy-status
  aria-live="polite"
  aria-atomic="true"
  class="sr-only"
></span>

<script>
  import {
    create,
    type CopyToClipboardController,
  } from "./copy-to-clipboard.ts"

  const controllers: CopyToClipboardController[] = []
  const initialize = () => controllers.push(...create())
  initialize()
  document.addEventListener("astro:page-load", initialize)
  document.addEventListener("astro:before-swap", () => {
    for (const controller of controllers) controller.destroy()
    controllers.length = 0
  })
</script>
```

#### src/components/ui/copy-button/copy-to-clipboard.ts

```ts
const selector = 'button[data-copy-control]'
const active = new WeakMap<HTMLButtonElement, CopyToClipboardController>()

/** Browser behavior adapted from Coss useCopyToClipboard. No framework runtime. */
export interface CopyToClipboardOptions {
    /** Read the current value on each copy. Defaults to the button's data-value. */
    value?: string | (() => string)
    /** Copied-state duration in milliseconds. Zero keeps it until reset. @default 2000 */
    timeout?: number
    onCopy?: () => void
    onError?: (error: unknown) => void
    onStateChange?: (state: 'idle' | 'copied' | 'error') => void
}

export interface CopyToClipboardController {
    readonly isCopied: boolean
    copy(value?: string): Promise<boolean>
    reset(): void
    destroy(): void
}

/** Bind one copy-button root. Destroy its controller before removing the root. */
export function createCopyToClipboard(
    root: Element,
    options: CopyToClipboardOptions = {},
): CopyToClipboardController {
    const button = root.matches('button')
        ? (root as HTMLButtonElement)
        : root.querySelector<HTMLButtonElement>(selector)
    if (!button) throw new Error('Copy Button requires a button.')
    const existing = active.get(button)
    if (existing) return existing
    const timeout =
        options.timeout ??
        Number(
            button.dataset.timeout ?? root.getAttribute('data-timeout') ?? 2000,
        )
    if (!Number.isFinite(timeout) || timeout < 0)
        throw new RangeError(
            'Copy timeout must be a finite, non-negative number.',
        )
    const label = button.getAttribute('aria-label')
    const sibling = button.nextElementSibling
    const status = sibling?.matches('[data-copy-status]')
        ? sibling
        : root.querySelector('[aria-live]')
    let timer: ReturnType<typeof setTimeout> | undefined
    let pending: symbol | undefined
    let destroyed = false

    const state = (value: 'idle' | 'copied' | 'error') => {
        button.toggleAttribute('data-copied', value === 'copied')
        if (value === 'copied') button.setAttribute('aria-label', 'Copied')
        else if (label === null) button.removeAttribute('aria-label')
        else button.setAttribute('aria-label', label)
        if (status)
            status.textContent =
                value === 'copied'
                    ? 'Copied'
                    : value === 'error'
                      ? 'Copy failed. Select and copy the text.'
                      : ''
        options.onStateChange?.(value)
    }

    const reset = () => {
        pending = undefined
        clearTimeout(timer)
        state('idle')
    }

    const copy = async (value?: string): Promise<boolean> => {
        if (
            destroyed ||
            pending ||
            button.matches(':disabled') ||
            button.getAttribute('aria-disabled') === 'true'
        )
            return false
        clearTimeout(timer)
        const request = Symbol()
        pending = request
        state('idle')
        try {
            const text =
                value ??
                (typeof options.value === 'function'
                    ? options.value()
                    : options.value) ??
                button.dataset.value
            if (!text) {
                pending = undefined
                return false
            }
            const clipboard =
                button.ownerDocument.defaultView?.navigator.clipboard
            if (!clipboard?.writeText)
                throw new Error('Clipboard API is unavailable.')
            await clipboard.writeText(text)
        } catch (error) {
            if (pending !== request) return false
            pending = undefined
            state('error')
            options.onError?.(error)
            return false
        }
        if (pending !== request) return false
        pending = undefined
        if (timeout > 0) timer = setTimeout(reset, timeout)
        state('copied')
        options.onCopy?.()
        return true
    }
    const click = (event: Event) => {
        if (!event.defaultPrevented) void copy()
    }
    button.addEventListener('click', click)
    const controller: CopyToClipboardController = {
        get isCopied() {
            return button.hasAttribute('data-copied')
        },
        copy,
        reset,
        destroy() {
            if (destroyed) return
            destroyed = true
            button.removeEventListener('click', click)
            active.delete(button)
            reset()
        },
    }
    active.set(button, controller)
    return controller
}

/** Bind each unbound copy-button root within the scope. Defaults to the page. */
export function create(
    scope: ParentNode = document,
): CopyToClipboardController[] {
    const controllers: CopyToClipboardController[] = []
    const buttons = scope.querySelectorAll<HTMLButtonElement>(selector)
    if (
        scope instanceof HTMLButtonElement &&
        scope.matches(selector) &&
        !active.has(scope)
    )
        controllers.push(createCopyToClipboard(scope))
    for (const button of buttons) {
        if (!active.has(button)) controllers.push(createCopyToClipboard(button))
    }
    return controllers
}
```

#### src/components/ui/copy-button/types.ts

```ts
import type { ButtonVariantProps } from '@/components/ui/button/button-variants.ts'

/** A button that copies text and confirms a successful clipboard write. */
export interface CopyButtonProps extends ButtonVariantProps {
    /** Initial text for the button's data-value attribute. */
    value?: string
    /** Copied-state duration in milliseconds. Zero keeps it until reset. @default 2000 */
    timeout?: number
}
```

#### src/components/ui/copy-button/index.ts

```ts
export { default as CopyButton } from './copy-button.astro'
export { createCopyToClipboard, create } from './copy-to-clipboard.ts'
export type { CopyButtonProps } from './types.ts'
export type {
    CopyToClipboardOptions,
    CopyToClipboardController,
} from './copy-to-clipboard.ts'
```

Component classes use the preset configured during project setup. Select the same preset in the docs before copying Manual source. To change installed component classes, edit or reinstall their source. See [Theming](/docs/theming) for details.


## Usage

```astro
---
import { CopyButton } from "@/components/ui/copy-button"
---

<CopyButton value="bun run build" />
```

The button uses the shared Button styles. Its defaults are `variant="ghost"`
and `size="icon"`. Position it with a caller class or a parent layout.
The copied state starts after a successful clipboard write and lasts 2000 ms.
Set `timeout={0}` to keep that state until the controller is reset or destroyed.
Empty values do nothing. Whitespace and final newlines are copied exactly.

## Examples

### Custom content

Use the default slot for other icons or text. The button's `data-copied`
attribute controls the state. The `group/copy` marker lets child elements
respond to it. Native button attributes, including `disabled`, pass through.

```astro
---
import { CopyButton } from "@/components/ui/copy-button"
---

<CopyButton
  value="hello@example.com"
  variant="outline"
  size="default"
  aria-label="Copy email address"
  timeout={3000}
>
  <span class="group-data-copied/copy:hidden">Copy email</span>
  <span class="hidden group-data-copied/copy:inline">Copied</span>
</CopyButton>
```

### Optional tooltip

CopyButton has no tooltip by default. Add [Tooltip](/ui/components/tooltip) when
you want a visible hint on hover or focus. Set `data-slot="tooltip-trigger"`
on CopyButton to use its button as the trigger.

```astro
---
import { CopyButton } from "@/components/ui/copy-button"
import { Tooltip, TooltipContent } from "@/components/ui/tooltip"
---

<Tooltip>
  <CopyButton
    value="bun run build"
    aria-label="Copy command"
    data-slot="tooltip-trigger"
  />
  <TooltipContent>Copy command</TooltipContent>
</Tooltip>
```

### Change the value

The button reads its current `data-value` when clicked. Set it in Astro with
`value` or `data-value`. In a browser script, assign text to
`button.dataset.value`.

```astro
---
import { CopyButton } from "@/components/ui/copy-button"
---

<div class="flex items-center gap-2" data-copy-example>
  <label>
    <span class="sr-only">Text to copy</span>
    <input class="rounded-md border px-3 py-1" value="Hello" />
  </label>
  <CopyButton data-value="Hello" />
</div>

<script>
  document.addEventListener("input", (event) => {
    if (!(event.target instanceof HTMLInputElement)) return
    const button = event.target
      .closest("[data-copy-example]")
      ?.querySelector<HTMLButtonElement>("[data-copy-control]")
    if (button) button.dataset.value = event.target.value
  })
</script>
```

### Copy text from a URL

This example fetches the Markdown guide, sets `button.dataset.value` to the
response text, and enables the button. Click the copy button to copy the guide.

```astro
---
import { CopyButton } from "@/components/ui/copy-button"

const url = "/components/copy-button.md"
---

<div class="flex flex-wrap items-center gap-2">
  <a href={url} class="underline">
    Copy Button guide (.md)
  </a>
  <CopyButton data-copy-url={url} aria-label="Copy guide Markdown" disabled />
  <span data-load-status role="status" class="text-sm"></span>
</div>

<script>
  async function loadText(button: HTMLButtonElement) {
    const url = button.dataset.copyUrl!
    delete button.dataset.copyUrl
    try {
      const response = await fetch(url)
      if (!response.ok) throw new Error()
      const text = await response.text()
      if (!text) throw new Error()
      button.dataset.value = text
      button.disabled = false
    } catch {
      const status = button.parentElement?.querySelector("[data-load-status]")
      if (status) status.textContent = "Could not load the guide."
    }
  }

  function initialize() {
    document
      .querySelectorAll<HTMLButtonElement>("button[data-copy-url]")
      .forEach(loadText)
  }

  initialize()
  document.addEventListener("astro:page-load", initialize)
</script>
```

### Bind a native button

The Astro component handles setup and cleanup. To use the clipboard behavior
on your own button, pass the button to `createCopyToClipboard`.

```ts
import { createCopyToClipboard } from "@/components/ui/copy-button/copy-to-clipboard"

const button = document.querySelector<HTMLButtonElement>("#copy-command")!
button.dataset.value = "bun run build"
const clipboard = createCopyToClipboard(button)

// Before removing the button:
clipboard.destroy()
```

A second call for the same button returns its controller. Use `copy(value?)`
from a user action to copy text directly. It returns a promise with `true`
after a successful write. Use `isCopied` to read the state and `reset()` to
clear it. The options include `value`, `timeout`, `onCopy`, `onError`, and
`onStateChange`.

To bind a group of native buttons, mark each with `data-copy-control` and
call `create(container)`. It returns the new controllers. Call `destroy()`
on each before removing those buttons.

## Accessibility and browser support

The component includes an accessible button label and a polite status message.
Icon buttons use `aria-label` for their accessible name. A tooltip is optional
and does not replace that label. Failed writes show failure feedback and do not show the check
icon. Clipboard access requires HTTPS or localhost and browser permission.
The browser module reports an unavailable API through `onError`.

## Design source

Adapted from the Coss `CopyButton` and `useCopyToClipboard` source.
The Astro port uses native events, the shared Button component, and
`data-copied` for icon changes. It does not require a React hook.

## API Reference

### CopyButtonProps

<AutoTypeTable
    path="../../packages/ui/src/components/ui/copy-button/types.ts"
    name="CopyButtonProps"
/>

Read the [installed source](/ui/r/copy-button.json) for the complete prop types.

## Theme and layout

Copy Button uses the shared [Button](/ui/components/button) styles. Use its variant and size props for the control, and place it with a parent layout. Keep the success and error feedback visible when you supply custom content. For a full code sample with copy controls, use [Code Block](/ui/components/code-block).
