Astro doesn’t offer a built-in integration specifically for automatically opening external links in new tabs, but we can easily implement it using a Markdown (or MDX) plugin. This runs at build time, giving you a clean, dependency-free solution.
Astro’s docs recommend using rehype-external-links as your go-to plugin for external link behavior in Markdown content.
Install plugin
To install rehype-external-links, run the following command in a Node.js (version 16+) environment:
npm install rehype-external-linksApply plugin
In your astro.config.mjs, import rehype-external-links. You can set your own target or rel.
import rehypeExternalLinks from "rehype-external-links";
export default defineConfig({ ... markdown: { rehypePlugins: [ [ rehypeExternalLinks, { target: "\_blank", rel: ["noopener", "noreferrer", "external"], }, ], ], }, ...});Output
<a href="https://github.com/odhyp/" rel="noopener noreferrer external" target="_blank"> GitHub</a>The target and rel will be added to every external anchor tag after npm run build (or npm run dev).
Comments
Comments are closed. Discussion happens elsewhere.