Astro - Open external link (from MDX) in new tab
I recently moved my personal website from NextJS to Astro and have a new blog space on it. After everything is settled, I notice that links in MDX will navigate current tab away from my website.
Oh, that’s not what I want! So, I’ve explored ways to make all external links in my blog open in a new tab while keeping internal links unaffected. Here’s the solution I came up.
Solution: Update config of mdx plugin
For those just want to get the solution, here’s config for your astro.config.mjs
export default defineConfig({
site: "https://lukenguyen.me",
integrations: [
mdx({
/* This is what you need */
rehypePlugins: [
() => {
return (tree) => {
visit(tree, "element", (node) => {
if (
node.tagName === "a" &&
node.properties?.href &&
node.properties.href.toString().startsWith("http") &&
!node.properties.href.toString().includes("yourdomain.com")
) {
node.properties["target"] = "_blank";
}
});
};
},
],
}),
sitemap(),
react(),
tailwind({
applyBaseStyles: false,
}),
],
});
Why You Need to Open External Links in a New Tab
Preserves User Engagement + Improve Navigation + Prevents Loss of Progress + Modern Web Experience
Opening external links in a new tab keeps users on your site while letting them explore other content. It’s super handy for preventing them from losing their place, especially if they’re filling out a form or working on something. Plus, it’s what most people expect these days—no one likes hitting the back button a million times!
What is rehype in this context?
You can think of rehype
acts as a processor that takes the MDX content (Markdown with embedded JSX) generated by Astro and allows you to manipulate the HTML structure programmatically. For example, you can use rehype plugins to modify the behavior of specific elements, like ensuring external links automatically open in a new tab.
Final words
And that’s it! With just a few tweaks using rehype, you can make external links smarter and your site more user-friendly. Small details like this might seem minor, but they add up to a better experience for everyone visiting your site.
Thanks for reading