NextJs+tRPC搭配Nginx反向代理出现Transfer-Encoding: chunked重复头问题
解决tRPC useMutation触发重复Transfer-Encoding: chunked请求头问题
问题概述
客户端使用tRPC的.useMutation()钩子时,会发送重复的Transfer-Encoding: chunked请求头,导致NextJs+tRPC生产环境部署失败。Nginx(开启调试模式)、Traefik、Caddy等反向代理均会触发该错误,日志显示收到重复的Transfer-Encoding: chunked头。
复现细节
- 项目基于create-t3-app生成,主页面仅设一个调用客户端mutation的按钮,该mutation仅返回字符串"TEST"
- 复现步骤:
- 执行
docker compose up启动项目 - 访问
http://localhost
- 执行
错误日志示例
nginx-1 | 2025/08/24 14:49:34 [debug] 22#22: *7 http proxy header: "Content-Type: application/json" nginx-1 | 2025/08/24 14:49:34 [debug] 22#22: *7 http proxy header: "Transfer-Encoding: chunked" nginx-1 | 2025/08/24 14:49:34 [debug] 22#22: *7 http proxy header: "Content-Encoding: gzip" nginx-1 | 2025/08/24 14:49:34 [debug] 22#22: *7 http proxy header: "Date: Sun, 24 Aug 2025 14:49:34 GMT" nginx-1 | 2025/08/24 14:49:34 [debug] 22#22: *7 http proxy header: "Transfer-Encoding: chunked" nginx-1 | 2025/08/24 14:49:34 [error] 22#22: *7 upstream sent duplicate header line: "Transfer-Encoding: chunked", previous value: "Transfer-Encoding: chunked" while reading response header from upstream, client: 192.168.148.1, server: localhost, request: "POST /api/trpc/post.create?batch=1 HTTP/1.1", upstream: "http://192.168.148.2:3000/api/trpc/post.create?batch=1", host: "localhost", referrer: "http://localhost/"
解决方案
方案1:关闭Next.js自动压缩
在next.config.js中添加compress: false,禁用Next.js自带的gzip压缩,由反向代理统一处理压缩,避免头信息重复:
/** @type {import('next').NextConfig} */ const nextConfig = { compress: false, // 其他原有配置 } module.exports = nextConfig
方案2:反向代理层清除重复头
以Nginx为例,在location配置中隐藏并重新设置Transfer-Encoding头,强制覆盖重复项:
location /api/trpc/ { proxy_pass http://your-upstream-address; proxy_hide_header Transfer-Encoding; proxy_set_header Transfer-Encoding chunked; // 其他代理配置(如header转发、超时设置等) }
方案3:升级依赖版本
检查tRPC(@trpc/client、@trpc/server)、Next.js的版本,升级到最新稳定版,该问题可能是特定版本组合的已知bug,新版本已修复。
内容的提问来源于stack exchange,提问作者Miki 15
相关产品推荐
相关产品推荐

