Created
April 8, 2024 13:33
-
-
Save irfanfadilah/c3e835b087155425b5c9e79cb55fd683 to your computer and use it in GitHub Desktop.
Dynamic OpenGraph Image on Cloudflare Workers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 }) | |
} | |
} |
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
workers-og
:Open
src/index.js
and copy the gist above.Run and test it locally:
Adjust the code to your liking and needs.
Deploy to Cloudflare Workers:
References: