What Webmentions Do and Why They Need Reinforcements

Webmention is a W3C recommendation last published on January 12, 2017, defined as a simple way to notify any URL when you mention it on your site — and, from the receiver's side, a way to request notifications when other sites mention it. In practice it lets a website announce that it has cited someone, turning the site into something of an active social channel fed by other networks such as Twitter, Instagram, Mastodon, and Facebook.

Implementation difficulty varies. WordPress users can get there with a couple of plugins, and other stacks are still fairly straightforward. The example below comes from atila.io, a server-side, pre-rendered blog written in NextJS, where Webmention requests are made client-side — so the approach carries over easily to any React app and needs little refactoring in other JavaScript projects.

Receiving: Endpoints and Social Conversions

There are two jobs on the inbound side: declare an endpoint that accepts Webmentions, and convert social media interactions into Webmentions.

Declaring an endpoint with Webmention.io

You can write your own receiving script and add it to your server, or use a service. The author chose Webmention.io, which is free; you only need to confirm ownership of the domain you register. Domain verification can happen several ways. Adding a rel="me" attribute to a link pointing at a social media profile is enough, and the author added one for every account.

<a
  href="https://twitter.com/atilafassina"
  target="_blank"
  rel="me noopener noreferrer"
>
  @AtilaFassina
</a>

With this verification method, the social profile also needs a link pointing back to your website. After that, you can return to Webmention.io and add the URL, which yields an endpoint for accepting Webmentions. The remaining step is wiring that endpoint into <link> tags in the <head> of your pages so mentions are collected.

<head>
  <link rel="webmention" href="https://webmention.io/{user}/webmention" />
  <link rel="pingback" href="https://webmention.io/{user}/xmlrpc" />
  <!-- ... -->
</head>

Replace {user} with your Webmention.io username.

Converting social interactions with Bridgy

Once the endpoint exists, Webmentions can flow — but almost nobody uses them. The fix is Bridgy, a free service that connects syndicated content and turns it into proper Webmentions. Using SSO, you line up each of your profiles one by one. The author's caveat: you had better start loving the IndieWeb, because this is squarely IndieWeb territory.

Fetching Mentions from the Webmention.io API

Third-party services can hold the data, but consuming and displaying it is your own work. The process has two stages: get the number of mentions, then fetch the mentions themselves and hook them into NextJS (optional — the data layer works anywhere).

Retrieving the count

type TMentionsCountResponse = {
  count: number
  type: {
    like: number
    mention: number
    reply: number
    repost: number
  }
}

That example object shows the shape of the response from the Webmention.io endpoint, formatted to suit the author's needs. The object received looks like this:

type TMentionsCount = {
  mentions: number
  likes: number
  total: number
}

The count endpoint lives at:

https://webmention.io/api/count.json?target=${post_url}

The request won't fail without the target, but no data will come back either. Max Böck and Swyx both combine likes with reposts and mentions with replies, since those pairs are analogous on Twitter.

const getMentionsCount = async (postURL: string): TMentionsCount => {
  const resp = await fetch(
    `https://webmention.io/api/count.json?target=${postURL}/`
  )
  const { type, count } = await resp.json()


  return {
    likes: type.like + type.repost,
    mentions: type.mention + type.reply,
    total: count,
  }
}

Retrieving the mentions themselves

The response is paginated, and the endpoint accepts three query parameters: page (the requested page), per-page (how many mentions appear on a page), and target (the URL whose Webmentions are fetched). Hitting https://webmention.io/api/mentions with those params returns an object with a single key, links, an array of mentions matching the type below:

type TMention = {
  source: string
  verified: boolean
  verified_date: string // date string
  id: number
  private: boolean
  data: {
    author: {
      name: string
      url: string
      photo: string // url, hosted in webmention.io
    }
    url: string
    name: string
    content: string // encoded HTML
    published: string // date string
    published_ts: number // ms
  }
  activity: {
    type: 'link' | 'reply' | 'repost' | 'like'
    sentence: string // pure text, shortened
    sentence_html: string // encoded html
  }
  target: string
}

That is more than enough to render a comment-like list on a site. Here is the fetch request in TypeScript:

const getMentions = async (
  page: string,
  postsPerPage: number,
  postURL: string
): { links: TWebMention[] } => {
  const resp = await fetch(
    `https://webmention.io/api/mentions?page=${page}&per-page=${postsPerPage}&target=${postURL}`
  )
  const list = await resp.json()
  return list.links
}

Wiring Mentions into NextJS

NextJS (as of version 9.3.0) offers three data-fetching methods: getStaticProps fetches at build time, getStaticPaths specifies dynamic routes to pre-render from fetched data, and getServerSideProps fetches on each request. That list is the decision point: pre-render the first batch of mentions on the server, or do the whole thing client-side. The author chose client-side, and recommends SWR for that route — a custom hook built by the Vercel team that provides caching, error and loading states, and even supports React.Suspense.

The count component

Many blogs show a comment count both at the top of a post and at the bottom, right above the comment list; the same pattern works for Webmentions. First, create a component for the count:

const MentionsCounter = ({ postUrl }) => {
  const { t } = useTranslation()
  // Setting a default value for `data` because I don't want a loading state
  // otherwise you could set: if(!data) return <div>loading...</div>
  const { data = {}, error } = useSWR(postUrl, getMentionsCount)


  if (error) {
    return <ErrorMessage>{t('common:errorWebmentions')}</ErrorMessage>
  }


  // The default values cover the loading state
  const { likes = '-', mentions = '-' } = data


  return (
    <MentionCounter>
      <li>
        <Heart title="Likes" />
        <CounterData>{Number.isNaN(likes) ? 0 : likes}</CounterData>
      </li>
      <li>
        <Comment title="Mentions" />{' '}
        <CounterData>{Number.isNaN(mentions) ? 0 : mentions}</CounterData>
      </li>
    </MentionCounter>
  )
}

SWR ensures that two instances of WebmentionsCounter still produce only one request, both sharing the cache.

The mention list

At the time of writing, useSWRpages is undocumented, and the webmention.io endpoint returns no collection information (no offset, no total page count), so the author found no way to use SWR for the list. The current implementation keeps the current page in one state, the mentions array in another, and issues requests via useEffect. The "Load More" button is disabled once the last request returns an empty array.

const Webmentions = ({ postUrl }) => {
  const { t } = useTranslation()
  const [page, setPage] = useState(0)
  const [mentions, addMentions] = useState([])


  useEffect(() => {
    const fetchMentions = async () => {
      const olderMentions = await getMentions(page, 50, postUrl)
      addMentions((mentions) => [...mentions, ...olderMentions])
    }
    fetchMentions()
  }, [page])


  return (
    <>
      {mentions.map((mention, index) => (
        <Mention key={mention.data.author.name + index}>
          <AuthorAvatar src={mention.data.author.photo} lazy />
          <MentionContent>
            <MentionText
              data={mention.data}
              activity={mention.activity.type}
            />
          </MentionContent>
        </Mention>
      ))}
      </MentionList>
      {mentions.length > 0 && (
        <MoreButton
          type="button"
          onClick={() => {
          setPage(page + 1)
        }}
        >
        {t('common:more')}
      </MoreButton>
    )}
    </>
  )
}

(The code is simplified to keep focus on the subject.)

Sending Outbound Webmentions

Outbound handling, courtesy of Remy Sharp, is easy and offers an option for every use case or preference. The quickest path is Webmention.app: get an API token and set up a web hook. With an RSS feed in place, an IFTT applet or a deploy hook is just as easy. To skip yet another third-party service, Remy has open-sourced a CLI package called wm that can run as a postbuild script.

Outbound mentions that carry more than the originating URL require microformats — a standardized, class-based notation in markup that adds semantic meaning to each piece and lets Webmention-enabled sites consume your content properly. A blog post uses two: h-entry for the post entry and h-card for the author. Most h-entry information lives in the page header, so the header component may look like this:

<header class="h-entry">
  <!-- the post date and time -->
  <time datetime="2020-04-22T00:00:00.000Z" class="dt-published">
    2020-04-22
  </time>
  <!-- the post title -->
  <h1 class="p-name">
    Webmentions with NextJS
  </h1>
</header>

In JSX, remember to swap class for className, note that datetime is camelCase (dateTime), and use Date('2020-04-22').toISOString(). The h-card works the same way; in most cases, author information sits below the article, as in this footer:

<footer class="h-card">
  <!-- the author name -->
  <span class="p-author">Atila Fassina</span>
  <!-- the authot image-->
  <img
    alt="Author’s photograph: Atila Fassina"
    class="u-photo"
    src="https://css-tricks.com/images/internal-avatar.jpg"
    lazy
  />
</footer>

With both microformats in place, every outbound mention sent from a post will present its full information to whoever receives it.