AWS CloudFront + Lambda@Edge "The JSON output is not parsable"

AWS CloudFront + Lambda@Edge "The JSON output is not parsable"

我有一个 Lambda 函数(一个打包的 next.js 应用程序),我正在尝试通过 CloudFront 访问它。网络应用程序工作 除非 我尝试访问主页。

当我点击 /search 或 /video/{videoId} 时,页面加载正常。

当我尝试访问主页时,出现以下错误页面:

502 ERROR
The request could not be satisfied.
The Lambda function returned invalid JSON: The JSON output is not parsable. We can't connect to the server for this app or website at this time. There might be too much traffic or a configuration error. Try again later, or contact the app or website owner.
If you provide content to customers through CloudFront, you can find steps to troubleshoot and help prevent this error by reviewing the CloudFront documentation.
Generated by cloudfront (CloudFront)
Request ID: {id}

为什么只有主页无效JSON?我在哪里可以看到这个 JSON 来确定哪里出了问题?我在 Lambda 函数中创建了一个模拟 Cloudfront 请求测试,它刚刚 returns 成功。

问题是由于 CloudFront Lambda@Edge 响应的大小限制为 1 MB。我没有意识到 Next.js 的服务器端呈现在我的主页上创建了一个大的 <script id="__NEXT_DATA__"> 标记,其中从我的 API 中获取的所有信息都重复了多次。这导致我的应用程序的主页超过 2 MB。

我重构了我的应用程序以仅发送一个网络请求,并确保数据仅被放入 __NEXT_DATA__ 标记一次。该应用程序现在可以使用了。