This example demonstrates how to build a Python Worker that dynamically injects OpenGraph meta tags into web pages based on the request path. This is perfect for controlling how your content appears when shared on social media platforms like Facebook, Twitter, LinkedIn, and Slack.
The Worker:
- Receives a request for a specific URL path (e.g.,
/blog/my-article) - Generates OpenGraph metadata dynamically based on the path
- Fetches the original HTML from your target website
- Uses Cloudflare's HTMLRewriter to inject OpenGraph meta tags into the HTML
<head>section - Returns the enhanced HTML with proper social media preview tags
This example showcases how to use Cloudflare's powerful HTMLRewriter API from Python Workers via the js module interop.
First ensure that uv is installed:
https://docs.astral.sh/uv/getting-started/installation/#standalone-installer
Now, if you run uv run pywrangler dev within this directory, it should use the config
in wrangler.jsonc to run the example.
uv run pywrangler devThen visit:
http://localhost:8787/- Home page with default metadatahttp://localhost:8787/blog/python-workers-intro- Blog post examplehttp://localhost:8787/products/awesome-widget- Product page examplehttp://localhost:8787/about- About page example
Deploy to Cloudflare Workers:
uv run pywrangler deployTo adapt this example for your own website:
-
Update the target URL in
src/entry.py:target_url = f"https://your-website.com{path}"
-
Customize metadata patterns in the
get_opengraph_data()method:if path.startswith("/your-section/"): og_data.update({ "title": "Your Custom Title", "description": "Your custom description", "image": "https://your-image-url.com/image.jpg" })
-
Add more URL patterns to match your site structure
Use these tools to validate your OpenGraph tags: