Copying a command from a technical article should take one click, not a careful drag across twenty lines of highlighted source code. That is especially true on phones, where selecting text inside horizontally scrollable blocks is awkward.
This tutorial builds a lightweight, accessible Copy code button for the Markdown code blocks in an Astro blog. It uses the native browser Clipboard API, preserves Shiki or Prism syntax highlighting, and works with ordinary full-page navigation as well as Astro’s optional ClientRouter.
You will implement a reusable component, integrate it without replacing your existing article layout, verify its keyboard and screen-reader behavior, and learn the limits of copying text from highlighted HTML. No React island, clipboard package, database, or external API is required.
What this guide does not assume: Your site might render Markdown through a Content Collection, a custom remark pipeline, or Decap CMS. Inspect the generated HTML before following the CSS selectors below. The example expects real <pre><code> markup under .article-content; it is a reference implementation, not a tested modification to your repository.
1. Why Copy Buttons Matter in Developer Tutorials
Readers often want to try an installation command, configuration snippet, or small function immediately. A code block may have syntax colors, horizontal scrolling, and many lines. Manual selection makes it easy to miss a character or include unrelated surrounding text.
A copy button reduces friction without changing the meaning of the article. It can also improve accessibility when implemented as a genuine <button> with visible focus styles and a short status message. But it is not automatically a ranking factor, and there is no defensible guarantee that adding one will improve SEO, conversion rates, or Core Web Vitals.
Keep the objective measurable: readers should be able to copy the intended code accurately with mouse, touch, or keyboard while the website remains fast and usable without optional JavaScript.
2. Understand Astro’s Generated Code-Block HTML
Astro supports syntax highlighting for fenced Markdown blocks using Shiki or Prism. A Markdown code fence such as:
const message = "Hello, Astro!";
console.log(message);
is normally rendered into a <pre> container with a nested <code> element. Shiki may add <span> elements and inline color styles around the highlighted tokens. The exact classes vary by configuration; common output includes .astro-code.
Do not copy the innerHTML of the highlighted block: that would include highlighting tags rather than usable source code. Our implementation copies the nested <code> element’s textContent instead.
Also, do not assume that every site uses precisely the same markup. Remark plugins, custom components, code-title decorators, and line-number plugins can change the structure. Inspect two or three live examples before choosing your selector.

Figure 1. Keep highlighted markup for display, but copy the textual contents of the code element.
3. What We Are Building
We will add one small component to the existing article layout. It will:
- Find eligible
<pre><code>pairs inside the article body. - Wrap each code block in a lightweight container that can hold a positioned button.
- Add a native
<button type="button">Copy code</button>outside the scrollable code area. - Read the source from
code.textContenton click. - Call
navigator.clipboard.writeText()only after a user gesture. - Display a success or failure label and announce the outcome through a live region.
- Avoid duplicate buttons if initialization runs again after client-side navigation.
The code never sends copied content to the server. It also avoids intercepting normal browser navigation or inserting the copied text into HTML.
4. Check the Browser and Layout Prerequisites
You need an Astro project with Markdown code fences, a shared article template, and an HTTPS production URL. Localhost is normally treated as a trustworthy development context, but the deployment site should use HTTPS.
Open an article in browser DevTools, select a code block, and look for a structure similar to:
<article class="article-content">
<pre class="astro-code"><code>npm run build</code></pre>
</article>
If the actual wrapper is .prose, .markdown-body, or another class, either add .article-content to your current article body or adjust the selector in the component. Do not replace the layout just to match the tutorial. Keep existing headings, metadata, canonical links, author information, search, cookie controls, and other functioning elements.
If you already use Expressive Code or another plugin with built-in copy buttons, check its configuration first. Two competing copy-button systems can harm usability.
5. Create the Reusable Astro Component
Create src/components/CopyCodeButtons.astro. This is the complete reference implementation:
<!-- Add once to the existing Astro article layout. -->
<div id="code-copy-announcer" class="dh-copy-visually-hidden" role="status" aria-atomic="true"></div>
<style is:global>
.dh-copy-visually-hidden {
position: absolute;
width: 1px;
height: 1px;
padding: 0;
margin: -1px;
overflow: hidden;
clip: rect(0, 0, 0, 0);
white-space: nowrap;
border: 0;
}
.article-content .code-copy-wrap {
position: relative;
margin-block: 1.5rem;
}
.article-content .code-copy-wrap > pre {
margin: 0;
padding-top: 3.2rem;
overflow-x: auto;
}
.article-content .code-copy-button {
position: absolute;
z-index: 2;
top: 0.6rem;
right: 0.6rem;
padding: 0.35rem 0.75rem;
border: 1px solid #6785a6;
border-radius: 0.5rem;
background: #173451;
color: #fff;
font: inherit;
font-size: 0.875rem;
line-height: 1.5;
cursor: pointer;
}
.article-content .code-copy-button:hover { background: #265273; }
.article-content .code-copy-button:focus-visible {
outline: 3px solid #63e6ef;
outline-offset: 3px;
}
.article-content .code-copy-button:disabled {
opacity: 0.65;
cursor: wait;
}
</style>
<script>
function enhanceCodeBlocks() {
document.querySelectorAll<HTMLPreElement>('.article-content pre').forEach((pre) => {
if (pre.dataset.copyReady === 'true') return;
const code = pre.querySelector<HTMLElement>(':scope > code');
if (!code) return;
const wrapper = document.createElement('div');
wrapper.className = 'code-copy-wrap';
pre.parentNode?.insertBefore(wrapper, pre);
wrapper.appendChild(pre);
const button = document.createElement('button');
button.type = 'button';
button.className = 'code-copy-button';
button.textContent = 'Copy code';
wrapper.appendChild(button);
pre.dataset.copyReady = 'true';
button.addEventListener('click', async () => {
const announcer = document.getElementById('code-copy-announcer');
const source = code.textContent ?? '';
if (!source.trim()) return;
button.disabled = true;
try {
if (!navigator.clipboard?.writeText) {
throw new Error('Clipboard API not available');
}
await navigator.clipboard.writeText(source);
button.textContent = 'Copied!';
if (announcer) announcer.textContent = 'Code copied to clipboard.';
} catch {
button.textContent = 'Copy failed';
if (announcer) {
announcer.textContent =
'Could not access the clipboard. Select and copy the code manually.';
}
} finally {
button.disabled = false;
window.setTimeout(() => {
if (button.isConnected) button.textContent = 'Copy code';
}, 1800);
}
});
});
}
enhanceCodeBlocks();
// Astro ClientRouter can replace the article without a full page refresh.
document.addEventListener('astro:page-load', enhanceCodeBlocks);
</script>
The component intentionally contains three parts: a polite screen-reader announcement region, scoped-to-content global styles, and a small TypeScript-capable Astro client script. Because the button is inserted after Markdown rendering, you do not need to change every old post in Decap CMS.
The initializer marks each <pre> with data-copy-ready="true". That guard prevents the same block from receiving two buttons when the routine is invoked again. The wrapper places the button outside the <pre> scroll region, so scrolling a long command horizontally does not make the button disappear.
Important implementation detail: Some code renderers insert visual line numbers or prompts inside the <code> element. Those characters may then appear in textContent. Test what actually reaches the clipboard; for advanced rendering, use a source-preserving transformer or a known unmodified source field instead of blindly stripping characters.
6. Integrate It into the Existing Article Layout
Import the component once in the article layout, not once per post. A minimal illustration is:
---
// Illustration only: merge these lines into your existing article layout.
// Do NOT replace your current layout with this partial file.
import CopyCodeButtons from '../components/CopyCodeButtons.astro';
// Content is supplied by your existing Markdown rendering pipeline.
const { Content } = Astro.props;
---
<article class="article-content prose dark:prose-invert">
<Content />
</article>
<CopyCodeButtons />
This is deliberately a partial example. A real Astro project may retrieve content through getCollection(), call render(), or render Markdown differently. Merge only the import, .article-content wrapper, and <CopyCodeButtons /> into the layout already in use.
If the layout already uses <article class="prose">, simply add article-content to its class list. Do not create a second nested article or duplicate the existing <Content /> rendering. If your site renders HTML with set:html, apply .article-content to the actual HTML container.
An Astro site deployed to Cloudflare Pages does not need a Pages Function for this feature. It is a purely client-side enhancement to static HTML.
7. Why the Clipboard API Needs a Real Click
The browser’s asynchronous clipboard method is:
await navigator.clipboard.writeText(codeText);
Modern browsers restrict clipboard writing to secure contexts, and they may additionally require recent user activation or enforce permission policies. A button click supplies an appropriate user gesture. Calling clipboard writing automatically during page load is not an acceptable substitute.
Check for the API before using it. A browser that blocks clipboard access should keep the code selectable and show an understandable message. We intentionally avoid relying on the deprecated document.execCommand('copy') workaround.
A successful writeText() promise means the browser accepted the clipboard operation. It does not tell you whether the pasted code will execute successfully or whether that command is safe to run.
8. Provide Accessible Success and Failure Feedback
We use a native HTML button, which supports focus, Enter, and Space without reimplementing keyboard behavior. The visible label changes briefly from Copy code to Copied! after success.
A separate element with role="status" announces a short message without stealing keyboard focus. That role implies polite live-region behavior, so a screen reader can communicate that the operation succeeded or failed.
If the clipboard API is unavailable or throws an error, the component says Copy failed and tells the reader to select and copy manually. Avoid making the interface falsely report success after a rejected promise.

Figure 2. The copy action starts with a user gesture and ends with visible and assistive-technology feedback.
9. Preserve Syntax Highlighting and Source Accuracy
For typical Shiki output, code tokens are wrapped in spans inside <code>. Reading textContent returns the visible text rather than the HTML attributes. This is a useful default, but it must be verified against your production markup.
Pay particular attention to these cases:
- Line numbers: Some third-party transformers insert numbering into the DOM. If numbers are copied, remove the numbering at the renderer/transformer level instead of using a brittle regex on code lines.
- Shell prompts: A code block beginning with
$ npm run buildmay be instructional display rather than a copy-ready command. Decide whether your tutorial should include the$in the actual source. - HTML entities: Rendered text should copy literal characters such as
<,>, and&, not HTML entity spellings. - Trailing newline: Pasting into a terminal may execute a command immediately if a newline is appended. Inspect the original Markdown content and decide whether to preserve or trim a terminal newline.
- Long lines: Ensure the code area still scrolls horizontally and the copy button remains visible.
This tutorial preserves textContent as-is; it does not modify the source or silently remove terminal newlines. That conservative choice is safer than guessing which characters are decorative.
10. Support Light and Dark Themes
The component’s default button styling uses a dark blue surface with light text, which fits a developer blog but should be adjusted to your existing design tokens. Keep the button clearly distinguishable over both light and dark syntax themes.
The important CSS properties are position: relative for the wrapper, position: absolute for the button, and overflow-x: auto for the <pre>. A visible :focus-visible outline must remain readable over the code background.
Do not override the Shiki token colors globally merely to style this button. If the site already provides theme-aware color variables, reuse those variables instead of adding a second theme implementation.
11. Handle Astro ClientRouter Without Duplicate Buttons
Astro normally performs full-page browser navigation. If you opt into <ClientRouter />, a navigation can replace article HTML without a traditional reload. A one-time setup that only runs when the first document loads may leave later pages unenhanced.
The component runs enhanceCodeBlocks() at initialization and listens for astro:page-load. This event occurs after a completed client-side navigation. The data-copy-ready guard prevents duplicate enhancements on blocks already processed.
This code is not a reason to add ClientRouter if your website does not need it. Introducing client-side routing simply to support Copy code would add complexity and could affect existing GA4 page-view tracking, cookie controls, or third-party widgets.
If an individual article dynamically adds code blocks without navigation, the implementation does not automatically observe new nodes. For such a site, call the enhancement function after rendering dynamic content or consider a carefully scoped MutationObserver.
12. Security and Privacy Considerations
The feature uses the clipboard only after a deliberate user click. It does not read the visitor’s existing clipboard contents, collect personal data, or make a network request.
Still, consider these safeguards:
- Never populate copied text from an untrusted
data-*attribute when the<code>source already exists. - Do not use
innerHTMLto reconstruct copied code. - Do not assume clipboard writing proves a command is safe or verified.
- Do not bypass Content Security Policy to make an inline script work; use Astro’s normal processed script pipeline and review the site’s
script-srcrules. - Do not silently execute code after copying it.
- Keep the code block readable even if JavaScript fails or is disabled.
A strict CSP may need to allow scripts from the site’s own origin. The correct rule depends on the existing build and deployment architecture. Do not set script-src 'unsafe-inline' as a blanket workaround.
13. Test Mouse, Touch, Keyboard, and Clipboard Errors
Create a test article with JavaScript, Bash, HTML, and a long single-line command. Verify that every block gets a button and inline code such as npm run build does not.
Test the following cases on the Cloudflare Pages preview deployment:
| Scenario | Expected behavior |
|---|---|
| Click Copy code | Code text reaches the clipboard |
| Focus the button and press Enter | Copy operation starts |
| Focus the button and press Space | Copy operation starts |
| Click on mobile | Button remains usable and code can scroll |
| Block clipboard permission | Failure feedback appears; text remains selectable |
| Navigate to another article through ClientRouter | New blocks receive a button exactly once |
| Reload the article | No duplicate buttons |
| Switch to light and dark themes | Focus and contrast remain visible |
| JavaScript disabled | Plain Markdown code blocks remain readable |
Also paste the copied text into a plain-text editor and compare it with the original fenced source. A visually correct code block can still contain an unwanted prompt or line-number character.
14. Add a Pre-Publish Quality Checklist
Before deploying to production, verify the real DOM, keyboard flow, clipboard behavior, visual layout, and compatibility with existing blog tools. A successful build alone does not prove the browser clipboard can be used in every environment.

Figure 3. Validate real browser interactions, not just the presence of the button in generated HTML.
Quality checklist
- The content selector matches code blocks in the deployed article layout.
- The original code is still selectable when JavaScript fails.
- No code block receives duplicate buttons.
- The button has clear text and visible keyboard focus.
- The screen-reader status announces the outcome.
- Clipboard rejection gives a useful fallback.
- Long lines are still readable and horizontally scrollable.
- The feature does not interfere with the site’s Shiki/Prism theme.
- Astro ClientRouter navigation has been tested if enabled.
- The page does not ship a second copy-code plugin unnecessarily.
15. Troubleshoot Common Problems
No Copy code button appears. Inspect the actual HTML. The example targets .article-content pre with a direct child <code>. Your Markdown pipeline may emit different elements or use a different content wrapper. Also confirm the component is rendered once and the client script is included.
The button appears but nothing copies. Check browser DevTools for a clipboard permission or security-context error. Ensure the page is HTTPS and that the API call originates from a genuine user click, not an automatic initializer.
The copy button moves when code scrolls. Confirm that the wrapper contains the <pre> and button as siblings. If the button was placed inside the scrollable <pre>, it can move with horizontal scrolling.
Line numbers are included in the clipboard. Inspect the <code> descendants and determine whether your highlighting plugin writes line numbers into their textContent. Use a renderer-aware source extraction strategy.
Buttons disappear after switching articles. If ClientRouter is enabled, check that astro:page-load executes and that the new article still has the .article-content wrapper.
The page shows two copy buttons. You may already have a copy feature in Expressive Code or a custom remark/rehype plugin. Disable one implementation, rather than adding CSS to hide the duplicate.
16. When a Plugin Is Better Than Custom JavaScript
Custom code is a good choice for a small blog with predictable Markdown output. However, you might prefer a maintained code-block integration when you need filenames, line highlighting, collapsible examples, copy transformations, callouts, or complex multi-language code tabs.
For example, an Expressive Code integration can handle many presentational features in one rendering pipeline. The trade-off is additional configuration and potentially a change to existing Markdown output. Compare bundle size, accessibility behavior, maintenance, theme support, and content migration costs before switching.
For a site that already renders code blocks correctly, this small enhancement is less intrusive than replacing the syntax-highlighting system.
17. Frequently Asked Questions
Can I use this with Decap CMS?
Yes, provided that Decap CMS saves regular Markdown code fences and Astro renders them to <pre><code> elements. The button is added by the article layout after rendering, so old posts do not need an editor-by-editor update.
Does this require a paid service?
No. The browser Clipboard API is built in, and this implementation requires neither a subscription nor a Cloudflare Pages Function.
Will it work without HTTPS?
The Clipboard API requires a secure context. HTTPS is expected for production, and localhost generally works in development. A non-secure deployment should retain selectable code and show a meaningful failure state.
Does Copy code improve Google rankings?
There is no guaranteed direct SEO benefit. It is a user-experience enhancement. Assess its value through usability testing or relevant engagement signals rather than claiming a ranking improvement.
Why not copy the highlighted HTML?
Highlighted HTML contains markup and styling. Readers need the underlying code text, not <span> tags. textContent works for common code renderers but should be verified if line-number transformers are installed.
Can I add a copy button to inline code?
You can, but this tutorial intentionally limits the feature to fenced code blocks. Putting a button beside every inline token would add clutter and hurt readability.
18. Conclusion
A useful Copy code button does more than call a browser API. It must extract the intended source, respect browser permissions, preserve Markdown formatting, remain keyboard-friendly, and behave correctly when the article DOM changes.
Start with the simplest version that fits your current Astro renderer. Test on a preview branch with real articles before updating a shared layout. If the blog grows into richer code tutorials, revisit a renderer-level solution instead of piling custom behavior on top of every code block.
Continue Reading
- How to Build an Astro Blog with Decap CMS and Cloudflare Pages — Understand the editing and publishing pipeline behind the Markdown content.
- How to Find and Fix Broken Links in Astro with GitHub Actions — Add automated quality checks to your publishing workflow.
- How to Build a Secure Contact Form in Astro — More examples of accessible UI and security boundaries.
Official References
- Astro — Syntax Highlighting
- Astro — View Transitions and ClientRouter
- MDN — Clipboard.writeText()
- MDN — ARIA status role
Editorial note: Code is a reproducible reference example, not a claim of deployment or performance testing on a live production website. Validate browser behavior, the existing code renderer, and the repository’s layout before applying it.






