CloudFront is configured with custom error pages that serve index.html for 403 and 404 responses. This causes API endpoints (like /api/ai/chat) to return HTML instead of JSON when they return error status codes.
Configure CloudFront to exclude /api/* paths from custom error pages using a CloudFront Function.
- Go to CloudFront Console → Functions
- Create a new function with the following code:
function handler(event) {
var request = event.request;
var uri = request.uri;
// Don't apply custom error pages to API routes
if (uri.startsWith("/api/")) {
// For API routes, return the original error response
return request;
}
// For non-API routes, allow CloudFront custom error pages to work
return request;
}- Go to your CloudFront distribution
- Edit the distribution
- Go to "Behaviors" tab
- Edit the default behavior (or create a new one for
/api/*) - Under "Function associations", set:
- Viewer request: Select the function created above
- Save changes
Alternatively, create a separate behavior for /api/* paths that does NOT have custom error responses:
- Create a new behavior with path pattern:
/api/* - Set origin and settings same as default behavior
- Do NOT configure custom error responses for this behavior
- Set the default behavior to have lower priority (higher number)
Keep the custom error responses for 403/404, but they will only apply to non-API paths due to the function or behavior configuration above.
After deployment:
/api/ai/chatwith authentication failure should return JSON:{"error": "Authentication required..."}- Non-API routes (like
/some-page) should still serveindex.htmlfor 404 errors (SPA routing)
The distribution currently has:
- 403 →
/index.html(status 200) - 404 →
/index.html(status 200)
This needs to be modified to exclude /api/* paths.