Skip to main content

External Links

Learn how to leverage custom components to automatically handle external links.

Problem

When writing markdown, you often want to link to external resources:

		[Click here to go to Google](https://google.com)
	

But by default, this renders as a standard link that takes users away from your site without any indication that it's external. You want to:

  • Open external links in new tabs
  • Add visual indicators for external links
  • Keep internal links in the same tab

Solution

Create a custom a component that automatically detects external links and handles them appropriately.

Implementation

Create the Custom Link Component

src/lib/blueprints/default/a.svelte
		<script lang="ts">
	import type { HTMLAnchorAttributes } from 'svelte/elements';
	import type { Snippet } from 'svelte';
 
	let { href, children, ...restProps }: HTMLAnchorAttributes & { children: Snippet } = $props();
 
	const isExternal = $derived(!href.startsWith('/'));
	const target = $derived(isExternal ? '_blank' : undefined);
</script>
 
<a {href} {target} class="text-blue-600 hover:text-blue-800" {...restProps}>
	{@render children?.()}
	{#if isExternal}
		<svg class="ml-1 inline h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
			<path
				stroke-linecap="round"
				stroke-linejoin="round"
				stroke-width="2"
				d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14"
			/>
		</svg>
	{/if}
</a>
	

Export from Blueprint

src/lib/blueprints/default/blueprint.svelte
		<script lang="ts" module>
	export { default as a } from '$lib/blueprints/default/a.svelte';
</script>
 
{@render children?.()}
	

Configure MDSX

mdsx.config.js
		import { defineConfig } from 'mdsx';
 
export const mdsxConfig = defineConfig({
	extensions: ['.md'],
	blueprints: {
		default: {
			path: 'src/lib/blueprints/default/blueprint.svelte',
		},
	},
});
	

Usage

Now all your markdown links will automatically be handled:

src/content/page.md
		# My Page
 
Here are some links:
 
- [Internal page](/about) - Opens in same tab
- [External site](https://google.com) - Opens in new tab with icon
- [Another external](https://github.com) - Also opens in new tab
	

Result

  • Internal links (/about) open in the same tab
  • External links (https://...) open in new tabs with external link icons