You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SSE本地运行正常但部署到Vercel后失效,求技术解决方案

问题原因

Vercel的Serverless Functions默认会缓冲所有响应,直到请求处理完毕才一次性返回,这直接破坏了SSE流式传输的核心逻辑——分块实时推送数据。所以才会出现本地正常但部署后变成整包返回、Content-Length替代Transfer-Encoding的情况。

解决步骤

1. 切换到Vercel Edge Functions

Serverless Functions不支持流式响应,必须改用Edge Functions,它原生支持流式传输和实时响应。需要将你的API路由配置为Edge运行时。

2. 调整代码适配Edge环境

直接用pipe在Edge环境下可能存在兼容问题,建议改用fetch获取OpenAI的流,再直接返回流对象。同时确保OpenAI请求明确开启流式:

import { NextResponse } from 'next/server';

export const config = {
  runtime: 'edge', // 关键:指定为Edge运行时
};

export async function POST(req) {
  // 获取客户端请求体
  const clientBody = await req.json();

  // 请求OpenAI的流式接口
  const openAIRes = await fetch('https://api.openai.com/v1/chat/completions', {
    method: 'POST',
    headers: {
      'Authorization': `Bearer MY_AUTH_TOKEN`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      ...clientBody,
      stream: true, // 必须开启流式返回
    }),
  });

  // 将OpenAI的流直接返回给客户端
  return new NextResponse(openAIRes.body, {
    headers: {
      'Content-Type': 'text/event-stream',
      'Cache-Control': 'no-cache',
      'Connection': 'keep-alive',
      'X-Accel-Buffering': 'no',
    },
  });
}

3. 移除无效响应头

Vercel Edge环境会自动处理分块传输,手动设置Transfer-Encoding: chunked会被平台覆盖,无需添加。

额外注意
  • 必须确保OpenAI请求中stream参数设为true,否则OpenAI不会返回流式数据
  • Edge Functions有60秒运行时长限制,超长对话场景需要注意
  • 本地测试用vercel dev命令,避免和生产环境行为不一致

内容的提问来源于stack exchange,提问作者Pat Trudel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 09:27:40