Better OG

はじめに

適応レイアウトと多言語フォントを備えた、プラットフォーム対応の Open Graph レンダリング。

概要

better-og は、画像を取得するプラットフォームに応じてサイズとレイアウトを自動調整する Open Graph 画像ツールキットです。

  • 実際の request シグナルによるプラットフォーム検出。
  • すぐ使えるアスペクト比とセーフエリア。
  • Next.js、Workers、TanStack Start 向けアダプター。

インストール

必要なランタイム向けパッケージだけを導入し、同じ OG コンポーネントを各環境で再利用できます。

pnpm add @better-og/core next react

最初のルート

OG ハンドラーを作成し、フォントを読み込み、最終画像として描画するコンポーネントを返します。

app/og/[lang]/route.tsx
import { resolveFontSetup } from "@better-og/core";
import {
  createOgRouteHandler,
  loadGoogleFontForImageResponse,
} from "@better-og/next";

export const runtime = "nodejs";
export const revalidate = false;

const fontSetup = await resolveFontSetup({
  baseFonts: await loadGoogleFontForImageResponse({
    family: "Geist",
    weights: [400, 700],
  }),
  fallbackLocales: ["ja"],
});

export const GET = createOgRouteHandler({
  component: (ogContext) => (
    <div
      style={{
        display: "flex",
        width: "100%",
        height: "100%",
        alignItems: "center",
        justifyContent: "center",
        fontFamily: fontSetup.families.base,
        paddingBottom: 32 + ogContext.safeArea.bottom,
        background: "linear-gradient(135deg, #0d192c, #174a70, #4993d6)",
        color: "white",
      }}
    >
      <div style={{ fontSize: 64, fontWeight: 700 }}>Hello from better-og</div>
    </div>
  ),
  baseFonts: fontSetup.fonts,
});

プロキシの追加

withOgRewrite を追加すると、platformlayoutaspect_ratio が自動的に補完されます。

proxy.ts
import { withOgRewrite } from "@better-og/next";
import type { NextRequest } from "next/server";

export async function proxy(request: NextRequest) {
  return await withOgRewrite(request);
}

export const config = {
  matcher: ["/og/:path*"],
};

Next.js 設定

Node で Takumi を使う場合は、Next.js 設定で外部パッケージとして扱います。

next.config.ts
import type { NextConfig } from "next";

const nextConfig: NextConfig = {
  serverExternalPackages: ["@takumi-rs/image-response"],
};

export default nextConfig;
Edit on GitHub

Last updated on

On this page