- Newest
- Most votes
- Most comments
You're on the right track with your setup for hosting an SPA using S3 and CloudFront, and your approach to handling API requests through the same domain is a good practice to avoid CORS issues and improve performance.
For handling 404 errors and returning the index.html file for unknown routes while maintaining a 200 status code, you have a few options:
-
CloudFront Function: Instead of using Lambda@Edge, you can use a CloudFront Function, which is a lightweight, purpose-built feature for CloudFront that can handle this scenario at a lower cost. You can create a function that checks if the request is for a non-API route and rewrites it to /index.html. This approach allows you to serve the SPA's index.html file for all non-API routes without returning a 404 status.
-
Custom Error Page: You can configure CloudFront to use a custom error page for 404 errors. Set up your S3 bucket to return index.html for 404 errors, and then configure CloudFront to use this as a custom error response. In the CloudFront distribution settings, you can specify to replace the 404 status code with 200.
-
Origin Response Lambda@Edge: While this does incur additional costs, it provides the most flexibility. You can create a Lambda@Edge function triggered on the Origin Response event that checks for 404 responses from your S3 origin (excluding API routes) and modifies them to return index.html with a 200 status code.
-
S3 Routing Rules: If you're using S3 static website hosting, you can set up routing rules in your S3 bucket to redirect requests for non-existent files to index.html. However, this approach still returns a 3xx redirect status rather than a 200.
Among these options, using a CloudFront Function is likely the most cost-effective and efficient solution for your needs. It allows you to handle the routing logic at the edge, returning the appropriate content with the desired status code without incurring the higher costs associated with Lambda@Edge.
Remember to thoroughly test your chosen solution to ensure it works as expected for all your routes, including API calls and various SPA routes.
Sources
Deploy a React-based single-page application to Amazon S3 and CloudFront - AWS Prescriptive Guidance
How to redirect URL paths in CloudFront with S3 Bucket? | AWS re:Post
Backend and Frontend on same domain Cloudfront error | AWS re:Post
Specifying different error behaviors for different S3 origins on CloudFront | AWS re:Post
Relevant content
- asked 8 days ago
- AWS OFFICIALUpdated 2 months ago