HTML rewrite via Worker Service not working


I’m trying to automatically rewrite a SEO tag (canonical) within the HTML on every page of my website The measures of success are:

  1. For
    automated rewrite <link rel="canonical" href="">
    to <link rel="canonical" href="">

  2. For
    automated rewrite <link rel="canonical" href="">
    to <link rel="canonical" href="">

I’ve deployed a Worker Service called canonical-tag-rewriter with a route at least 15 days ago, but it is not automatically rewriting the line of HTML on any pages. This is my first attempt to implement HTML rewrite. I’m on a paid subscription and paid workers plan. I’ve exhausted all online documentation. Any assistance appreciated - thanks.

Worker settings:

Worker Triggers > Custom Domain =
Worker Triggers > Route = **
All other settings are default.

Worker Javascript deployed:

// start
const OLD_URL = '';
const NEW_URL = '';

async function handleRequest(req) {
  const res = await fetch(req);
  const contentType = res.headers.get('Content-Type');

  // If the response is HTML, it can be transformed with
  // HTMLRewriter -- otherwise, it should pass through
  if (contentType.startsWith('text/html')) {
    return rewriter.transform(res);
  } else {
    return res;


class AttributeRewriter {
  constructor(attributeName) {
    this.attributeName = attributeName;
  element(element) {
    const attribute = element.getAttribute(this.attributeName);
    if (attribute) {
      element.setAttribute(this.attributeName, attribute.replace(/replace.OLD_URL/g, NEW_URL));


const rewriter = new HTMLRewriter()
  .on('link', new AttributeRewriter('href'));

addEventListener('fetch', event => {


// end

Compare this line from your worker

With the one from the Rewrite links · Cloudflare Workers docs example

element.setAttribute(this.attributeName, attribute.replace(OLD_URL, NEW_URL));

Hi - thanks for your suggestion. That is how I originally had my code. I’ve reverted it, and now works in combination with changing:

    const attribute = element.getAttribute(this.attributeName);


    var attribute = element.getAttribute(this.attributeName);

Turns out Javascript will not throw an error if you execute replace() on a constant. Instead it returns the original value.

I cut and paste the erroneous "const attribute " code from the example on Cloudflares /introducing-htmlrewriter/ page. I’ll let Cloudflare know that example has the bug.


I have used this, exactly as the demo code I linked to shows, without issue.