Should I Put My API Behind CloudFront or Use an ALB Directly?

0
0
Asked By MellowPine47 On

I'm deciding whether to serve an API through CloudFront in front of an Application Load Balancer, or expose the ALB directly. I originally used CloudFront so the API could live under the same domain with an /api path instead of a separate subdomain. That helped avoid some CORS and cookie complications, but it created routing problems with a single-page application hosted in S3. The SPA needs 403 or 404 responses rewritten to index.html with a 200 status so client-side routes work, but that behavior can also hide legitimate 403 and 404 responses from the API. What are the main reasons to use or avoid CloudFront for an API, and what is the cleanest way to handle the SPA and API errors?

4 Answers

Answered By VividHarbor8 On

CloudFront is still useful here. It can terminate TLS close to users, reuse connections to the origin, help with traffic spikes, and cache responses when particular API endpoints are safe to cache. Keeping the SPA and API on the same domain can also simplify CORS and cookie handling. The important part is to avoid applying the SPA fallback behavior to API requests.

Answered By CopperWren26 On

Split the CloudFront behaviors by path. Route /api/* to the ALB and let the API return its own 403 and 404 responses unchanged. Route the default behavior, or your static asset paths, to S3 and apply the index.html fallback only there. CloudFront Functions can also rewrite SPA routes selectively instead of using a distribution-wide error rule.

QuietMango61 -

A common layout is to put static assets under something like /static/ and point that path at S3, while the default or /api/* behavior goes to the API origin. That keeps S3 errors and API errors from being mixed together.

Answered By SilverKite39 On

Adding a web application firewall in front of the API is worth considering, especially for rate limits and common abusive traffic patterns. CloudFront caching should be selective—only cache responses when authentication, headers, and data freshness are well understood. It shouldn’t replace efficient API queries or origin-side authorization.

Answered By BriskNoodle5 On

If the path-based setup becomes difficult to maintain, a separate API subdomain is perfectly reasonable. /api looks tidy, but a separate hostname gives the SPA and API completely independent error handling and deployment rules. You may need to configure CORS carefully, but the architecture can be simpler.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.