Astro Guide: How to automatically open markdown external links in new tabs with Rehype
Introduction
When developing a website, if you care about user retention, it’s important to open most external links in new tabs, so that the user can easily go back to your website.
Think a business brand, if they have a link to another website like a guide or a partner, when the user clicks it, they will lose track of your website, while if it opens in a new tab, then the user will have your website present in their tabs.
Now, you probably know that you can easily do that by writing target="_blank" in any <a> link. The problem arises when some of your pages are posted using markdown code, where links are written like this: [My link](https://example.com).
The crappy solution
You can, of course, write HTML directly in your Astro markdown files, so in theory you can just do:
<a href="https://example.com" target="_blank">
My link
</a>
And that will 100% work, but it’s such A PAIN in the 🍑:
- Having to write this for every single link
- If the link is at the end of the parragraph and you have Prettier or other markdown formatting tools, it will put the link in a new line.
Horrible stuff.
The super cool solution (Wooo!)
- You just write normal markdown links
- Astro will add the
targer=_blankautomatically to any external links
How do we do this? Easy: 🌈javascript🌈
Step 1: Install rehype-external-links
You thought we would code this ourselves? Hell no.
Rehype has a super useful library for this that get’s any external links on your site and adds rel and target attributes to them automatically.
Start by installing it:
npm install rehype-external-links
Step 2: Configure it in your Astro configure
Open astro.config.mjs and add the plugin like so:
// ...
import rehypeExternalLinks from 'rehype-external-links';
export default defineConfig({
// ...
integrations: [
// ...
markdown({
rehypePlugins: [[rehypeExternalLinks, { target: '_blank', rel: [] }]],
}),
],
});
Note that if you also want this to work on .mdx files you need to specify it as well:
// ...
import rehypeExternalLinks from 'rehype-external-links';
export default defineConfig({
// ...
integrations: [
// ...
markdown({
rehypePlugins: [[rehypeExternalLinks, { target: '_blank', rel: [] }]],
}),
mdx({
rehypePlugins: [[rehypeExternalLinks, { target: '_blank', rel: [] }]],
}),
],
});
That’s it!
Easy right? Now any external link in your markdown files will have the target blank attribute!
More external link customizations
Astro docs has a cool guide on how to add icons to any external links in your markdown files.
The set up is super similar:
// ...
import rehypeExternalLinks from 'rehype-external-links';
export default defineConfig({
// ...
markdown: {
rehypePlugins: [
[
rehypeExternalLinks,
{
content: { type: 'text', value: ' 🔗' },
},
],
],
},
});