Next.js App目录下@vercel/og的ImageResponse返回问题求助
解决Next.js App Router中使用@vercel/og生成OG图片的405/500错误
错误原因分析
- 错误包裹Response:
ImageResponse本身就是标准的Response实例,无需用new Response()二次包装,这会导致响应格式异常。 - 未执行生成函数:第一段代码中直接返回了
ogImage函数本身,而非调用函数后得到的ImageResponse实例。 - 语法与配置缺失:第二段代码存在语法错误(
ImageResponse括号未闭合),且缺少@vercel/og导入和Edge Runtime配置,这是运行@vercel/og的必要条件。
正确实现代码示例
在app/api/og/route.js(或你需要的路由路径)中编写以下代码:
import { ImageResponse } from '@vercel/og'; // 必须配置Edge Runtime,@vercel/og依赖此环境运行 export const config = { runtime: 'edge', }; export async function GET() { return new ImageResponse( ( <div style={{ fontSize: 128, background: '#ffffff', width: '100%', height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#000000', fontWeight: 'bold', }} > Hello World! </div> ), { width: 1200, height: 630, // 遵循OG图片推荐的1.91:1比例 }, ); }
关键注意事项
- 确保已安装依赖:执行
npm install @vercel/og或yarn add @vercel/og - Edge Runtime限制:代码不能使用Node.js专属API(如
fs、path),需兼容Edge环境 - JSX使用限制:仅支持基础HTML元素,不能导入自定义React组件
- 响应头自动处理:
ImageResponse会自动设置Content-Type: image/png,无需手动配置
内容的提问来源于stack exchange,提问作者Titas Mallick
相关产品推荐
相关产品推荐

