{
  "id": "generate-og-images-at-build-time",
  "type": "prompts",
  "category": "prompts",
  "locale": "es",
  "url": "/es/prompts/generate-og-images-at-build-time",
  "title": "Prompt para generar imágenes OG en tiempo de compilación",
  "description": "Prompt de agente de IA para generar imágenes Open Graph por página en tiempo de compilación en Astro o Next.js usando Satori y sharp, sin servicio externo.",
  "tools": [
    "Cursor",
    "Claude Code",
    "Codex",
    "Windsurf"
  ],
  "stack": [
    "Astro",
    "Next.js",
    "TypeScript"
  ],
  "tags": [
    "seo",
    "astro",
    "nextjs",
    "typescript"
  ],
  "difficulty": "medium",
  "updated": "2026-06-08",
  "markdown": "Dale este prompt a tu agente para generar una imagen PNG OG única para cada página en\ntiempo de compilación usando Satori y sharp — evitando la latencia y el costo de los servicios\nde imágenes OG en tiempo de ejecución como Vercel OG.\n\n## Prompt principal\n\n```txt title=\"Main Prompt\"\nYou are working in an existing Astro 5 static site with TypeScript.\n\nTask: generate a static Open Graph PNG image for every blog post at build time.\n\nRequirements:\n- Install `satori` and `sharp`.\n- Create `src/lib/generate-og.ts` that exports `generateOgImage({ title, description }: OgData): Promise<Buffer>`.\n  - Use Satori to render a JSX template (800 x 420 px) with: site name top-left, post title\n    (large, bold, white), description (smaller, gray), a solid dark background (#0f172a).\n  - Convert the Satori SVG output to PNG using `sharp(Buffer.from(svg)).png().toBuffer()`.\n  - Use only system-safe fonts or load `src/fonts/Inter-Bold.ttf` (create a note to add the file).\n- Create `src/pages/og/[slug].png.ts` as an Astro endpoint:\n  - `getStaticPaths`: call `getCollection('blog')` and return a path per post.\n  - `GET`: call `generateOgImage` with the post's title and description, set\n    `Content-Type: image/png`, return the buffer.\n- In the blog post layout, set `<meta property=\"og:image\" content={ogImageUrl} />` where\n  `ogImageUrl` is constructed as `/og/${post.slug}.png`.\n- Do NOT use `@vercel/og`, `next/og`, or any cloud image generation service.\n- Do NOT use Canvas or puppeteer.\n\nStop and list all planned file changes before writing any code.\n```\n\n## Notas de implementación\n\n- Satori acepta objetos similares a JSX (sintaxis de elementos React), pero NO utiliza el runtime de React.\n  Pasa el elemento como un árbol de objetos plano usando directamente el primer argumento de `satori`.\n- Carga de fuentes: Satori requiere al menos una fuente. Usa `fs.readFileSync` para cargar el archivo `.ttf`\n  en tiempo de compilación — esto está bien en una compilación estática de Astro.\n- Los PNG generados estarán en la carpeta `dist/og/` después de `astro build`. Revisa su tamaño; a\n  800x420 deberían tener menos de 100 KB cada uno si usas un fondo de color plano.\n- Para Next.js en lugar de Astro: usa un Route Handler en `app/og/[slug]/route.ts` y llama a\n  `NextResponse` con el buffer PNG.\n\n## Cambios esperados en archivos\n\n```txt\nsrc/lib/generate-og.ts              (new)\nsrc/pages/og/[slug].png.ts          (new — Astro endpoint)\nsrc/layouts/BlogPost.astro          (edited — add og:image meta)\nsrc/fonts/Inter-Bold.ttf            (add manually — not auto-generated)\npackage.json                        (edited — add satori, sharp)\n```\n\n## Criterios de aceptación\n\n- `astro build` genera un archivo `.png` en `dist/og/` para cada entrada del blog.\n- Cada PNG tiene 800 x 420 píxeles.\n- El layout de la entrada del blog incluye `og:image` apuntando a la ruta correcta `/og/<slug>.png`.\n- Abrir la URL de la imagen OG en un navegador muestra una tarjeta estilizada con el título del artículo.\n\n## Comandos de prueba\n\n```bash\nbun add satori sharp\nbun run build\nls dist/og/\nfile dist/og/my-first-post.png   # should output \"PNG image data, 800 x 420\"\ncurl -I http://localhost:4321/og/my-first-post.png | grep content-type\n```\n\n## Errores comunes de IA\n\n- Importar React e intentar renderizar con `ReactDOMServer` — Satori no usa el runtime de React.\n- Olvidar cargar una fuente, lo que provoca que Satori lance `\"No font found for the first character\"`.\n- Establecer `og:image` en una ruta relativa como `./og/slug.png` — debe ser una URL absoluta en producción.\n- Usar el paquete `canvas` que require enlaces nativos incompatibles con muchos entornos CI.\n\n## Prompt de corrección\n\n```txt title=\"Fix Prompt\"\nSatori throws a font error or the PNG is blank. Fix in order:\n1. Add font loading: `const fontData = fs.readFileSync('src/fonts/Inter-Bold.ttf'); fonts: [{ name: 'Inter', data: fontData, weight: 700 }]` in the satori call.\n2. Make sure the JSX-like element passed to satori is a plain object, not a JSX expression — call `satori(element, options)` directly.\n3. For the og:image meta tag, use an absolute URL: `const base = import.meta.env.SITE; ogImageUrl = new URL(\\`/og/\\${slug}.png\\`, base).toString();`\nShow only the corrected diff.\n```"
}