rehype-external-links

rehype plugin to automatically add `target` and `rel` attributes to external links

Downloads in past

Stats

StarsIssuesVersionUpdatedCreatedSize
rehype-external-links
2202.0.13 months agoa year agoMinified + gzip package size for rehype-external-links in KB

Readme

rehype-external-links
!Buildbuild-badgebuild !Coveragecoverage-badgecoverage !Downloadsdownloads-badgedownloads !Sizesize-badgesize !Sponsorssponsors-badgecollective !Backersbackers-badgecollective !Chatchat-badgechat
rehype plugin to add rel (and target) to external links.

Contents

*   [`unified().use(rehypeExternalLinks[, options])`](#unifieduserehypeexternallinks-options)
*   [Example: dynamic options](#example-dynamic-options)

What is this?

This package is a unified
(rehype) plugin to add rel (and target) attributes to external links. It is particularly useful when displaying user content on your reputable site, because users could link to disreputable sources (spam, scams, etc), as search engines and other bots will discredit your site for linking to them (or legitimize their sites). In short: linking to something signals trust, but you can’t trust users. This plugin adds certain rel attributes to prevent that from happening.
unified is a project that transforms content with abstract syntax trees (ASTs). rehype adds support for HTML to unified. hast is the HTML AST that rehype uses. This is a rehype plugin that adds rel (and target) to <a>s in the AST.

When should I use this?

This project is useful when you want to display user content from authors you don’t trust (such as comments), as they might include links you don’t endorse, on your website.

Install

This package is ESM only. In Node.js (version 12.20+, 14.14+, or 16.0+), install with npm:
npm install rehype-external-links

In Deno with esm.shesmsh:
import rehypeExternalLinks from 'https://esm.sh/rehype-external-links@1'

In browsers with esm.shesmsh:
<script type="module">
  import rehypeExternalLinks from 'https://esm.sh/rehype-external-links@1?bundle'
</script>

Use

Say our module example.js looks as follows:
import {unified} from 'unified'
import remarkParse from 'remark-parse'
import remarkRehype from 'remark-rehype'
import rehypeExternalLinks from 'rehype-external-links'
import rehypeStringify from 'rehype-stringify'

const file = await unified()
  .use(remarkParse)
  .use(remarkRehype)
  .use(rehypeExternalLinks, {rel: ['nofollow']})
  .use(rehypeStringify)
  .process('[rehype](https://github.com/rehypejs/rehype)')

console.log(String(file))

Now running node example.js yields:
<p><a href="https://github.com/rehypejs/rehype" rel="nofollow">rehype</a></p>

API

This package exports no identifiers. The default export is rehypeExternalLinks.

unified().use(rehypeExternalLinks[, options])

Add rel (and target) to external links.
options
Configuration (optional).
options.target
How to open external documents (string?: _self, _blank, _parent, or _top, default: undefined). Can also be a function called with the current element to get target dynamically. The default (nothing) is to not set targets on links.
👉 Note: you should likely not configure thiscss-tricks.
options.rel
Link typesmdn-rel to hint about the referenced documents (Array<string> or string, default: ['nofollow']). Can also be a function called with the current element to get rel dynamically. Pass an empty array ([]) to not set rels on links.
👉 Note: you should at least set ['nofollow'].

⚠️ Danger: when using a target, add noopener and noreferrermdn-a to avoid exploitation of the window.opener API.
options.protocols
Protocols to see as external, such as mailto or tel (Array<string>, default: ['http', 'https']). Can also be a function called with the current element to get protocols dynamically.
options.content
hast content to insert at the end of external links (Nodenode or Childrenchildren, optional). Can also be a function called with the current element to get content dynamically. The content will be inserted in a <span> element.
👉 Note: you should set this when using target to adhere to accessibility guidelines by giving users advanced warning when opening a new windowg201.
options.contentProperties
Attributes to add to the <span>s wrapping options.content (Propertiesproperties, optional). Can also be a function called with the current element to get contentProperties dynamically.

Examples

Example: dynamic options

This example shows how to define options dynamically. That means that you can choose per element what to generate.
Each option can be a function which is called with the current element (Element) and returns the corresponding value.
Taking the above example.js and applying the following diff:
const file = await unified()
  .use(remarkParse)
  .use(remarkRehype)
-  .use(rehypeExternalLinks, {rel: ['nofollow']})
+  .use(rehypeExternalLinks, {
+    target(element) {
+      return element.properties && element.properties.id === '5'
+        ? '_blank'
+        : undefined
+    },
+    rel: ['nofollow']
+  })
  .use(rehypeStringify)
  .process('[rehype](https://github.com/rehypejs/rehype)')

Changes to apply target="_blank" on the element with an id="5".

Types

This package is fully typed with TypeScript. It exports an Options type, which specifies the interface of the accepted options.

Compatibility

Projects maintained by the unified collective are compatible with all maintained versions of Node.js. As of now, that is Node.js 12.20+, 14.14+, and 16.0+. Our projects sometimes work with older versions, but this is not guaranteed.
This plugin works with rehype-parse version 3+, rehype-stringify version 3+, rehype version 4+, and unified version 6+.

Security

Improper use of rehype-external-links can open you up to a cross-site scripting (XSS)xss attack.
Either do not combine this plugin with user content or use rehype-sanitizerehype-sanitize.

Contribute

See contributing.mdcontributing in rehypejs/.githubhealth for ways to get started. See support.mdsupport for ways to get help.
This project has a code of conductcoc. By interacting with this repository, organization, or community you agree to abide by its terms.

License

MITlicense © Titus Wormerauthor