Skip to content

Instantly share code, notes, and snippets.

@irfanfadilah
Created April 8, 2024 13:33
Show Gist options
  • Save irfanfadilah/c3e835b087155425b5c9e79cb55fd683 to your computer and use it in GitHub Desktop.
Save irfanfadilah/c3e835b087155425b5c9e79cb55fd683 to your computer and use it in GitHub Desktop.
Dynamic OpenGraph Image on Cloudflare Workers
import { ImageResponse } from 'workers-og'
export default {
async fetch(request) {
let param = request.url.split('/').pop() || '@_irfanfadilah'
if (param.length > 50) {
param = 'Text Too Long!'
}
const content = decodeURIComponent(param.replace(/\+/g, '%20'))
const html = `
<div style="
display: flex;
align-items: center;
justify-content: center;
font-family: sans-serif;
background: #2a3440;
color: #ffffff;
padding: 3rem;
height: 100vh;
width: 100vw;
">
<h1 style=" font-size: 3rem; font-weight: bold;">${content}</h1>
</div>
`
return new ImageResponse(html, { width: 600, height: 315 })
}
}
@irfanfadilah
Copy link
Author

You can add more data by including another fetch to send a request to your server based on the given parameters inside the function. E.g.:

const user = await fetch(`https://yourserver.com/api/${username}`).then(res => res.json())

const html = `
  <div>
    <h1>${ user.name }</h1>
    <h2>${ user.website }</h2>
  </div>
`

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment