Santiago Medina
Santiago Medina

Reputation: 579

Problem with AWS CloudFront and Server Side Rendering (Nuxt)

I have a problem with AWS CloudFront and Nuxt Server Side Rendering

This are the components of my application:

As an entry point of the application, I have a CloudFront distribution that splits the backend requests (/api/*) to the EC2 instance, and the frontend requests (default) to the API Gateway endpoint so the frontend is server side rendered by Lambda.

The frontend code performs an HTTP request to the backend to retrieve data, using the public CloudFront URL (because the render is hybrid, the first time is run server-side, but if the user navigates back to the home page it's rendered client-side).

So this is the invocation flow:

Browser => CloudFront (frontend path) => API Gateway => Lambda (render app) => CloudFront (backend path) => EC2

The Lambda function receives a 403 error ('x-cache': [ 'Error from cloudfront' ]) when invoking CloudFront, with no additional detail.

But if I browse the frontend in API Gateway directly (bypassing CloudFront), everything works:

Browser => API Gateway => Lambda (render app) => CloudFront (backend path) => EC2

I'm not understanding why invoking the Lambda function through CloudFront affects its ability to make an HTTP request to a CloudFront URL, or in other words why CloudFront reject that request.

Upvotes: 1

Views: 2003

Answers (1)

Santiago Medina
Santiago Medina

Reputation: 579

AWS support clarified the problem.

There is a "Via" header where an extra value is added each time CF is involved, and there is a limitation that the header cannot include more than 2 CF references.

The API Gateway generated by Serverless is Edge-Optimized, so it involves going through the nearest CF Edge Location, and the number of CF distributions involved in the request becomes 3, and that's not allowed.

The solution was using a regional API Gateway instead of an Edge-Optimized API gateway, reducing by 1 the number of CF distributions involved.

Upvotes: 2

Related Questions