SEO 分享与数据统计
14.6 Open Graph分享
Tip
在 14.1 中我们手工配置了静态的cover.png。但如果你有 1000 篇博客,每篇都去 PS 做一张封面太累了。Next.js ImageResponse 允许你用代码 (JSX) 来“画”图。
1. 为什么要学这个?
你分享了文章 A,封面是网站 Logo。 你分享了文章 B,封面还是网站 Logo。 用户觉得这些文章都是一样的,没兴趣点。
你希望能像 Notion 或 GitHub 一样,自动把文章标题、作者、阅读时间印在封面上,让每一张分享图都像是专属定制的海报。
2. 核心概念:Edge Image Generation
Next.js (基于 @vercel/og) 提供了一个非常黑科技的功能:
它在 Edge Function (边缘节点) 运行。
它接受 JSX (HTML/CSS),并在毫秒级时间内将其渲染并截图为 PNG。
优势:
- 速度快:比传统的 Puppeteer 截图快 10 倍。
- 即时性:改了标题,图片立马变。
- 个性化:甚至可以把访问者的名字印上去。
3. 解决方案 (HOW)
3.1 创建 opengraph-image.tsx
在 app/posts/[slug]/ 目录下新建 opengraph-image.tsx。
import { ImageResponse } from 'next/og'
export const runtime = 'edge' // 必须运行在 edge
export const alt = '文章封面'
export const size = { width: 1200, height: 630 }
export const contentType = 'image/png'
export default async function Image({ params }: { params: { slug: string } }) {
const post = await getPost(params.slug)
return new ImageResponse(
(
// 就像写 React 组件一样,但只能用部分 CSS 特性 (flexbox)
<div
style={{
width: '100%',
height: '100%',
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'center',
background: 'linear-gradient(to bottom right, #e0e7ff, #c7d2fe)',
color: '#3730a3',
}}
>
<div style={{ fontSize: 96, fontWeight: 'bold' }}>{post.title}</div>
<div style={{ fontSize: 48, marginTop: 40 }}>Vibe Coding Tutorial</div>
</div>
),
{ ...size }
)
}
3.2 动态渲染流程图
graph TD
Twitter["Twitter 爬虫"] -->|"Step 1: 请求图片 URL"| Edge["Edge Function"]
subgraph Satori ["渲染引擎 (@vercel/og)"]
JSX["JSX 代码"] --> HTML["HTML/CSS"]
HTML --"Step 2: 布局计算"--> SVG["SVG 矢量图"]
end
Edge --> JSX
SVG --"Step 3: 栅格化"--> PNG["PNG 图片"]
Edge --"Step 4: 返回二进制流"--> Twitter
style Edge fill:#e1bee7,stroke:#8e24aa
style Satori fill:#c8e6c9,stroke:#2e7d32
4. 避坑指南
| ❌ 不要这样做 | ✅ 应该这样做 | 为什么 |
|---|---|---|
| 复杂 CSS | Flexbox | Satori 引擎不支持 Grid 或 Float。只用最基础的 Flexbox 布局。 |
| Node.js Runtime | Edge Runtime | 生成图片非常吃 CPU。Edge 环境启动极快,能在 Twitter 爬虫超时的几秒内返回图片。 |
| 本地字体 | 加载字体文件 | 中文必须加载 .ttf 字体文件,否则全是乱码 (Tofu)。需要 fetch 一个字体文件传给 ImageResponse。 |
5. 真实案例
Story
2023年,GitHub 的社交图
以前,分享 GitHub 仓库链接只能看到 GitHub 的 LOGO。 后来 GitHub 上线了动态 OG Image。当你分享一个仓库时,图片上会显示:仓库名、Stars 数、Contributors 头像、编程语言占比。 这一个小小的改动,让 GitHub 项目在社交媒体上的点击率 (CTR) 提升了 40%。因为它把最有价值的信息(Star 数)直接展示在了预览图中,利用了人们的从众心理。
Vibe 心法:一张动态生成的 OG 图片,抵得上一千字的描述。利用 Vercel OG,把你的 Data(数据)可视化为 Image(图片),在社交网络的洪流中,用视觉冲击力为你的内容争取那宝贵的"停留一秒"。
6. 本章小结
- ImageResponse:是前端生成图片的魔法。
- JSX:用写代码的方式画图。
- Unique:让你的每一个链接都与众不同。