Search code examples
amazon-web-servicesaws-lambdaamazon-cloudfront

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


I have a Lambda function (a packaged next.js app) which I'm trying to access via CloudFront. The web app works unless I try to hit the homepage.

When I hit /search or /video/{videoId} the page loads just fine.

When I try to hit the homepage, I get the following error page:

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}

Why would just the homepage be invalid JSON? Where can I see this JSON to determine what is wrong? I created a mock Cloudfront request test in the Lambda function and it just returns successfully.


Solution

  • The problem was due to the 1 MB size limit of CloudFront Lambda@Edge responses. I didn't realize that Next.js's serverside rendering was creating a large <script id="__NEXT_DATA__"> tag on my homepage with all the fetched info from my API duplicated multiple times over. This resulted in my app's homepage being >2 MB.

    I refactored my app to only send one network request, and made sure that data is only put into the __NEXT_DATA__ tag once. The app now works.