Cookie Consent by Free Privacy Policy Generator

Generate Missing Meta Descriptions using Cloudflare Workers

Looking for a quick and effortless way to generate meta descriptions for pages missing them? If so, this lightweight Cloudflare Workers script might be exactly what you’re looking for. It ensures every page on your site has a meaningful description without you needing to manually check or edit a single line of HTML.

Here’s how it works: the script scans your HTML for a <meta name="description"> tag. If it finds the tag missing or empty, it automatically creates one using the first sentence of the first paragraph on the page. To keep things SEO friendly, the description is capped at 160 characters, making it concise and to the point.

This approach is fast, lean, and entirely automated. By leveraging Cloudflare Workers, you can dynamically apply this fix across your entire site in real time without touching your source code or making server-side changes. It’s a simple yet effective way to enhance your site’s SEO and accessibility without breaking a sweat.

How the Script Works

  1. Intercepts HTML Responses
    The script processes only responses with Content-Type: text/html, ensuring it works exclusively on HTML pages.
  2. Checks for an Existing Meta Description
    It scans the <head> section for an existing <meta name="description" content="..."> tag. If one is found, the script leaves the page unchanged.
  3. Extracts the First Paragraph
    The script locates the first <p> tag on the page and captures its content.
  4. Generates a New Description
    Using the first sentence of the first paragraph, the script creates a meta description. If the sentence exceeds 160 characters, it truncates the text to keep it concise.
  5. Injects the Meta Description
    The newly generated <meta name="description"> tag is inserted just before the closing </head> tag in the HTML.

Example​


Before
Code:
<!DOCTYPE html>
<html lang="en">
<head>
  <title>Example Page</title>
</head>
<body>
  <p>This is the first paragraph on the page. It contains multiple sentences. Here's another one.</p>
  <p>This is another paragraph.</p>
</body>
</html>

After
Code:
<!DOCTYPE html>
<html lang="en">
<head>
  <title>Example Page</title>
  <meta name="description" content="This is the first paragraph on the page.">
</head>
<body>
  <p>This is the first paragraph on the page. It contains multiple sentences. Here's another one.</p>
  <p>This is another paragraph.</p>
</body>
</html>


The Script​

Code:
export default {
  async fetch(request) {
    const response = await fetch(request);
    const contentType = response.headers.get('Content-Type') || '';

    // Process only HTML responses
    if (!contentType.includes('text/html')) {
      return response;
    }

    const html = await response.text();

    // Modify HTML to add or fix meta description
    const modifiedHtml = addMetaDescription(html);

    return new Response(modifiedHtml, {
      headers: { ...response.headers, 'Content-Type': 'text/html' },
      status: response.status,
    });
  },
};

/**
 * Adds or fixes the meta description tag in the HTML.
 */
function addMetaDescription(html) {
  // Check if a meta description already exists
  const metaDescriptionRegex = /<meta\s+name=["']description["']\s+content=["'].*?["']\s*\/?>/i;
  const hasMetaDescription = metaDescriptionRegex.test(html);

  if (hasMetaDescription) {
    // If the meta description exists, return the original HTML
    return html;
  }

  // Extract the first <p> tag content
  const firstParagraphRegex = /<p\b[^>]*>(.*?)<\/p>/i;
  const firstParagraphMatch = html.match(firstParagraphRegex);

  if (!firstParagraphMatch) {
    // If no <p> tag is found, return the original HTML
    return html;
  }

  // Extract the first sentence from the first paragraph
  const firstParagraph = firstParagraphMatch[1];
  const firstSentence = firstParagraph.split('. ')[0].trim(); // Splits on the first full stop
  const description = firstSentence.length > 160 
    ? firstSentence.slice(0, 157) + '...' // Truncate to 160 chars if too long
    : firstSentence;

  // Create the meta description tag
  const metaTag = `<meta name="description" content="${description}">`;

  // Inject the meta tag into the <head> section
  return html.replace(
    '</head>',
    `${metaTag}\n</head>`
  );
}

This Cloudflare Workers script is a quick and effective way to ensure all your pages have populated meta descriptions without manually editing your site. It’s lightweight, dynamic, and completely automated, saving you time while improving your SEO and user experience.
 
Back
Top