Better OG

Introduzione

Rendering Open Graph consapevole della piattaforma con layout adattivo e font multilingue.

Panoramica

better-og e un toolkit per immagini Open Graph che adatta automaticamente dimensioni e layout alla piattaforma che richiede l'immagine.

  • Rilevamento piattaforma dai segnali reali della richiesta.
  • Rapporti e safe area pronti all'uso.
  • Adattatori per Next.js, Workers e TanStack Start.

Installazione

Installa solo i pacchetti del runtime che ti serve e riusa lo stesso componente OG in ogni ambiente.

pnpm add @better-og/core next react

Prima route

Crea un handler OG, carica i font e restituisci il componente da renderizzare come immagine.

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,
});

Aggiungi il proxy

Aggiungi withOgRewrite per compilare automaticamente platform, layout e aspect_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*"],
};

Configurazione Next.js

Se usi Takumi su Node, mantieni il pacchetto esterno nella configurazione 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