Skip to content

rehype plugin to add rel (and target) to external links

License

Notifications You must be signed in to change notification settings

rehypejs/rehype-external-links

Repository files navigation

rehype-external-links

Build Coverage Downloads Size Sponsors Backers Chat

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

Install

This package is ESM only: Node 12+ is needed to use it and it must be imported instead of required.

npm:

npm install rehype-external-links

Use

Say we have the following module, example.js:

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 input = '[rehype](https://github.com/rehypejs/rehype)'

unified()
  .use(remarkParse)
  .use(remarkRehype)
  .use(rehypeExternalLinks, {target: false, rel: ['nofollow']})
  .use(rehypeStringify)
  .process(input)
  .then((file) => {
    console.log(String(file))
  })

Now, running node example 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])

Automatically add target and rel attributes to external links.

options
options.target

How to display referenced documents (string?: _self, _blank, _parent, or _top, default: _blank). Pass false to not set targets on links.

options.rel

Link types to hint about the referenced documents (Array.<string> or string, default: ['nofollow', 'noopener', 'noreferrer']). Pass false to not set rels on links.

Note: when using a target, add noopener and noreferrer to avoid exploitation of the window.opener API.

options.protocols

Protocols to check, such as mailto or tel (Array.<string>, default: ['http', 'https']).

options.content

hast content to insert at the end of external links (Node or Children). Will be inserted in a <span> element.

Useful for improving accessibility by giving users advanced warning when opening a new window.

options.contentProperties

Properties to add to the span wrapping content, when given.

Security

Improper use of rehype-external-links can open you up to a cross-site scripting (XSS) attack.

Either do not combine this plugin with user content or use rehype-sanitize.

Contribute

See contributing.md in rehypejs/.github for ways to get started. See support.md for ways to get help.

This project has a code of conduct. By interacting with this repository, organization, or community you agree to abide by its terms.

License

MIT © Titus Wormer