-
Notifications
You must be signed in to change notification settings - Fork 158
feat: opengraph image #203
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
thomasyuill-livekit
merged 7 commits into
main
from
thomasyuill/dex-1529-can-we-generate-og-image-dynamically-based-on-the-host
Jul 25, 2025
Merged
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
60a8af3
feat: opengraph image
thomasyuill-livekit 4dda7db
add dynamic elements
thomasyuill-livekit 6da38e3
fix lockfile
thomasyuill-livekit 5be575c
getAppConfig fail safely
thomasyuill-livekit 087d788
update page meta description
thomasyuill-livekit 4d488af
fix font loading
thomasyuill-livekit 8251461
cleanup default page title
thomasyuill-livekit File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,253 @@ | ||
import { headers } from 'next/headers'; | ||
import { ImageResponse } from 'next/og'; | ||
import getImageSize from 'buffer-image-size'; | ||
import mime from 'mime'; | ||
import { existsSync } from 'node:fs'; | ||
import { readFile } from 'node:fs/promises'; | ||
import { join } from 'node:path'; | ||
import { APP_CONFIG_DEFAULTS } from '@/app-config'; | ||
import { getAppConfig } from '@/lib/utils'; | ||
|
||
type Dimensions = { | ||
width: number; | ||
height: number; | ||
}; | ||
|
||
type ImageData = { | ||
base64: string; | ||
dimensions: Dimensions; | ||
}; | ||
|
||
// Image metadata | ||
export const alt = 'About Acme'; | ||
export const size = { | ||
width: 1200, | ||
height: 628, | ||
}; | ||
|
||
function isRemoteFile(uri: string) { | ||
return uri.startsWith('http'); | ||
} | ||
|
||
function doesLocalFileExist(uri: string) { | ||
return existsSync(join(process.cwd(), uri)); | ||
} | ||
|
||
// LOCAL FILES MUST BE IN PUBLIC FOLDER | ||
async function loadFileData(filePath: string): Promise<ArrayBuffer> { | ||
if (isRemoteFile(filePath)) { | ||
const response = await fetch(filePath); | ||
if (!response.ok) { | ||
throw new Error(`Failed to fetch ${filePath} - ${response.status} ${response.statusText}`); | ||
} | ||
return await response.arrayBuffer(); | ||
} | ||
|
||
// Try file system first (works in local development) | ||
if (doesLocalFileExist(filePath)) { | ||
const buffer = await readFile(join(process.cwd(), filePath)); | ||
return buffer.buffer.slice( | ||
buffer.byteOffset, | ||
buffer.byteOffset + buffer.byteLength | ||
) as ArrayBuffer; | ||
} | ||
|
||
// Fallback to fetching from public URL (works in production) | ||
const publicFilePath = filePath.replace('public/', ''); | ||
const fontUrl = `https://${process.env.VERCEL_URL}/${publicFilePath}`; | ||
|
||
const response = await fetch(fontUrl); | ||
if (!response.ok) { | ||
throw new Error(`Failed to fetch ${fontUrl} - ${response.status} ${response.statusText}`); | ||
} | ||
|
||
return await response.arrayBuffer(); | ||
} | ||
|
||
async function getImageData(uri: string, fallbackUri?: string): Promise<ImageData> { | ||
try { | ||
const fileData = await loadFileData(uri); | ||
const buffer = Buffer.from(fileData); | ||
const mimeType = mime.getType(uri); | ||
|
||
return { | ||
base64: `data:${mimeType};base64,${buffer.toString('base64')}`, | ||
dimensions: getImageSize(buffer), | ||
}; | ||
} catch (e) { | ||
if (fallbackUri) { | ||
return getImageData(fallbackUri, fallbackUri); | ||
} | ||
throw e; | ||
} | ||
} | ||
|
||
function scaleImageSize(size: { width: number; height: number }, desiredHeight: number) { | ||
const scale = desiredHeight / size.height; | ||
return { | ||
width: size.width * scale, | ||
height: desiredHeight, | ||
}; | ||
} | ||
|
||
function cleanPageTitle(appName: string) { | ||
if (appName === APP_CONFIG_DEFAULTS.pageTitle) { | ||
return 'Voice agent'; | ||
} | ||
|
||
return appName; | ||
} | ||
|
||
export const contentType = 'image/png'; | ||
|
||
// Image generation | ||
export default async function Image() { | ||
const hdrs = await headers(); | ||
const appConfig = await getAppConfig(hdrs); | ||
|
||
const pageTitle = cleanPageTitle(appConfig.pageTitle); | ||
const logoUri = appConfig.logoDark || appConfig.logo; | ||
const isLogoUriLocal = logoUri.includes('lk-logo'); | ||
const wordmarkUri = logoUri === APP_CONFIG_DEFAULTS.logoDark ? 'public/lk-wordmark.svg' : logoUri; | ||
|
||
// Load fonts - use file system in dev, fetch in production | ||
let commitMonoData: ArrayBuffer | undefined; | ||
let everettLightData: ArrayBuffer | undefined; | ||
|
||
try { | ||
commitMonoData = await loadFileData('public/commit-mono-400-regular.woff'); | ||
everettLightData = await loadFileData('public/everett-light.woff'); | ||
} catch (e) { | ||
console.error('Failed to load fonts:', e); | ||
// Continue without custom fonts - will fall back to system fonts | ||
} | ||
|
||
// bg | ||
const { base64: bgSrcBase64 } = await getImageData('public/opengraph-image-bg.png'); | ||
|
||
// wordmark | ||
const { base64: wordmarkSrcBase64, dimensions: wordmarkDimensions } = isLogoUriLocal | ||
? await getImageData(wordmarkUri) | ||
: await getImageData(logoUri); | ||
const wordmarkSize = scaleImageSize(wordmarkDimensions, isLogoUriLocal ? 32 : 64); | ||
|
||
// logo | ||
const { base64: logoSrcBase64, dimensions: logoDimensions } = await getImageData( | ||
logoUri, | ||
'public/lk-logo-dark.svg' | ||
); | ||
const logoSize = scaleImageSize(logoDimensions, 24); | ||
|
||
return new ImageResponse( | ||
( | ||
// ImageResponse JSX element | ||
<div | ||
style={{ | ||
display: 'flex', | ||
alignItems: 'center', | ||
justifyContent: 'center', | ||
width: size.width, | ||
height: size.height, | ||
backgroundImage: `url(${bgSrcBase64})`, | ||
backgroundSize: '100% 100%', | ||
backgroundPosition: 'center', | ||
backgroundRepeat: 'no-repeat', | ||
}} | ||
> | ||
{/* wordmark */} | ||
<div | ||
style={{ | ||
position: 'absolute', | ||
top: 30, | ||
left: 30, | ||
display: 'flex', | ||
alignItems: 'center', | ||
gap: 10, | ||
}} | ||
> | ||
<img src={wordmarkSrcBase64} width={wordmarkSize.width} height={wordmarkSize.height} /> | ||
</div> | ||
{/* logo */} | ||
<div | ||
style={{ | ||
position: 'absolute', | ||
top: 200, | ||
left: 460, | ||
display: 'flex', | ||
alignItems: 'center', | ||
gap: 10, | ||
}} | ||
> | ||
<img src={logoSrcBase64} width={logoSize.width} height={logoSize.height} /> | ||
</div> | ||
{/* title */} | ||
<div | ||
style={{ | ||
position: 'absolute', | ||
bottom: 100, | ||
left: 30, | ||
width: '380px', | ||
display: 'flex', | ||
flexDirection: 'column', | ||
gap: 16, | ||
}} | ||
> | ||
<div | ||
style={{ | ||
backgroundColor: '#1F1F1F', | ||
padding: '2px 8px', | ||
borderRadius: 4, | ||
width: 72, | ||
fontSize: 12, | ||
fontFamily: 'CommitMono', | ||
fontWeight: 600, | ||
color: '#999999', | ||
letterSpacing: 0.8, | ||
}} | ||
> | ||
SANDBOX | ||
</div> | ||
<div | ||
style={{ | ||
fontSize: 48, | ||
fontWeight: 300, | ||
fontFamily: 'Everett', | ||
color: 'white', | ||
lineHeight: 1, | ||
}} | ||
> | ||
{pageTitle} | ||
</div> | ||
</div> | ||
</div> | ||
), | ||
// ImageResponse options | ||
{ | ||
// For convenience, we can re-use the exported opengraph-image | ||
// size config to also set the ImageResponse's width and height. | ||
...size, | ||
fonts: [ | ||
...(commitMonoData | ||
? [ | ||
{ | ||
name: 'CommitMono', | ||
data: commitMonoData, | ||
style: 'normal' as const, | ||
weight: 400 as const, | ||
}, | ||
] | ||
: []), | ||
...(everettLightData | ||
? [ | ||
{ | ||
name: 'Everett', | ||
data: everettLightData, | ||
style: 'normal' as const, | ||
weight: 300 as const, | ||
}, | ||
] | ||
: []), | ||
], | ||
} | ||
); | ||
} |
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
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
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
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
Binary file not shown.
Binary file not shown.
This file was deleted.
Oops, something went wrong.
This file was deleted.
Oops, something went wrong.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@rektdeckard the 🪄