#Wrap IMG tags in markdown output with anchor tag with same url

4 messages · Page 1 of 1 (latest)

mental quartz
#

I'm trying to configure Astro so that it wraps all Markdown output <img>s with <a> tags that link to the image directly. (So clicking on an image takes you directly to the source).
I thought creating a rehype plugin was the way to go, but I'm seeing Astro rewrite the img src tags later in the pipeline.
Given a source:

![alt](./IMG_20250825.jpg)

A rehype plugin to wrap with an <a> tag results in something like the following (for prod build):

<a href="./IMG_20250825.jpg"><img alt="alt" loading="lazy" decoding="async" fetchpriority="auto" width="4096" height="3072" src="/_astro/IMG_20250825.CWrw5d7V_1OQslT.webp" ></a>

When my desired outcome is:

<a href="/_astro/IMG_20250825.CWrw5d7V_1OQslT.webp"><img alt="alt" loading="lazy" decoding="async" fetchpriority="auto" width="4096" height="3072" src="/_astro/IMG_20250825.CWrw5d7V_1OQslT.webp" ></a>

(notice the href attribute)
Is there any way to achieve this? I want to essentially execute my rehype plugins AFTER Astro's own rewriting.

tired sunBOT
#

Hi @mental quartz. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

Short answer: not directly. Astro processes Markdown with remark/rehype and also performs its own image handling that can change img src after your plugins run. The docs note you can add rehype plugins and control their order relative to other rehype plugins, but not after Astro’s own image optimization step. You can insert Astro’s rehypeHeadingIds earlier if needed, but there’s no documented hook to run a plugin after Astro rewrites image URLs (Markdown plugins; markdown.rehypePlugins; Heading IDs and plugins).

Workarounds you can consider, depending on your setup:

  • Use MDX instead of MD for image-heavy content and render a custom component that wraps <Image /> or <img> with an <a> using the final src you pass in. MDX supports components and imports (Images in MDX files).
  • Use Markdoc with a custom image node/tag that renders an Astro component and controls both href and img src consistently (Custom image components; Create a custom Markdoc image tag).
  • If you stay with Markdown, note that Markdown image syntax is optimized by Astro and you can’t use <Image /> directly in .md; MDX/Markdoc are recommended when you need more control over attributes (Images in Markdown files).
#

I’m sorry, but there’s no information in the docs about a way to run a rehype plugin after Astro’s image URL rewriting stage.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: