Skip to content

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
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
253 changes: 253 additions & 0 deletions app/(app)/opengraph-image.tsx
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();
}
Comment on lines +37 to +65
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@rektdeckard the 🪄


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,
},
]
: []),
],
}
);
}
2 changes: 1 addition & 1 deletion app/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ export default async function RootLayout({ children }: RootLayoutProps) {
<head>
{styles && <style>{styles}</style>}
<title>{pageTitle}</title>
<meta name="description" content={pageDescription + '\n\nBuilt with LiveKit Agents.'} />
<meta name="description" content={pageDescription} />
<ApplyThemeScript />
</head>
<body
Expand Down
10 changes: 5 additions & 5 deletions lib/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,11 +39,11 @@ export const getAppConfig = cache(async (headers: Headers): Promise<AppConfig> =
if (CONFIG_ENDPOINT) {
const sandboxId = SANDBOX_ID ?? headers.get('x-sandbox-id') ?? '';

if (!sandboxId) {
throw new Error('Sandbox ID is required');
}

try {
if (!sandboxId) {
throw new Error('Sandbox ID is required');
}

const response = await fetch(CONFIG_ENDPOINT, {
cache: 'no-store',
headers: { 'X-Sandbox-ID': sandboxId },
Expand All @@ -66,7 +66,7 @@ export const getAppConfig = cache(async (headers: Headers): Promise<AppConfig> =

return config;
} catch (error) {
console.error('!!!', error);
console.error('ERROR: getAppConfig() - lib/utils.ts', error);
}
}

Expand Down
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,12 @@
"@radix-ui/react-slot": "^1.2.3",
"@radix-ui/react-toggle": "^1.1.9",
"@radix-ui/react-toolbar": "^1.1.10",
"buffer-image-size": "^0.6.4",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"livekit-client": "^2.13.3",
"livekit-server-sdk": "^2.13.0",
"mime": "^4.0.7",
"motion": "^12.16.0",
"next": "15.4.2",
"next-themes": "^0.4.6",
Expand Down
21 changes: 21 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Binary file added public/commit-mono-400-regular.woff
Binary file not shown.
Binary file added public/everett-light.woff
Binary file not shown.
1 change: 0 additions & 1 deletion public/file.svg

This file was deleted.

1 change: 0 additions & 1 deletion public/globe.svg

This file was deleted.

10 changes: 5 additions & 5 deletions public/lk-logo-dark.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading