Trying to add Open Graph tags with Cloudflare Workers in my Vue 3 + Django e-commerce site
Hello everyone! I'm trying to inject open graph tags with a worker for an ecommerce website made with Vue + Django (using an EC2 AWS instance for Database and S3 for images), without using SSR. I tried with different slightly variations of this code, but it doesn't seem to change the og tags (still the default declared values in the index.html file ). Anyone succeded a case like this?
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
async function handleRequest(request) {
// Fetch the original response
let response = await fetch(request)
let html = await response.text()
// Generate Open Graph tags based on the request or page content
const ogTags = generateOpenGraphTags(request, html)
// Inject Open Graph tags into the HTML
const modifiedHtml = injectOpenGraphTags(html, ogTags)
// Return the modified response
return new Response(modifiedHtml, {
headers: response.headers
})
}
function generateOpenGraphTags(request, html) {
// Extract information from the request or HTML to generate appropriate OG tags
// This is a simplified example
const url = request.url
const title = extractTitle(html) || 'My Vue 3 Website'
const description = 'A description of my Vue 3 website'
return
<meta property="og:url" content="${url}" />
<meta property="og:type" content="website" />
<meta property="og:title" content="${title}" />
<meta property="og:description" content="${description}" />
<meta property="og:image" content="https://example.com/image.jpg" />
}
function extractTitle(html) {
// Simple regex to extract title from HTML
const titleMatch = html.match(/<title>(.*?)</title>/)
return titleMatch ? titleMatch[1] : null
}
function injectOpenGraphTags(html, ogTags) {
// Inject OG tags just before the closing </head> tag
return html.replace('</head>', ${ogTags}</head>
)3 Replies
I just could solve it! I had forgotten to create a new Worker route :feelskek2:
haha classic, glad you got it solved!
Thanks!