Skip to content
WritingArticle
  • #aws
  • #s3
  • #cloudfront
  • #cors
  • #serverless

Host a Frontend on S3 + CloudFront and Connect It to API Gateway (Without CORS Headaches)

Pawan Joshi

3 min read

Share
Cover image for “Host a Frontend on S3 + CloudFront and Connect It to API Gateway (Without CORS Headaches)”

In Week 3 of the 4-Week AWS Serverless Roadmap, you host your frontend on Amazon S3 + CloudFront and connect it to API Gateway.

Almost every beginner hits the same three walls here:

  1. Making the S3 bucket public (insecure and unnecessary).
  2. Getting 403 Access Denied when refreshing /dashboard or /about in a Single Page App (React/Vite).
  3. Seeing CORS errors in the browser console when calling API Gateway.

Here is how to set all three up cleanly the first time.

Connecting a CloudFront + S3 OAC frontend to API Gateway with CORSKeep S3 private with OAC, rewrite 403/404s for SPAs, and configure CORS on API Gateway.


1. Keep S3 Private with Origin Access Control (OAC)

Never turn off Block All Public Access on your frontend S3 bucket. Instead:

  1. Create your S3 bucket with Block all public access = ON.
  2. Upload your built static files (dist/ or build/).
  3. Create a CloudFront distribution pointing to the S3 bucket as its origin.
  4. Under Origin access, select Origin access control settings (recommended) and create an OAC.
  5. Copy the bucket policy CloudFront gives you and paste it into S3 → Permissions → Bucket policy. It looks like this:
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "AllowCloudFrontServicePrincipal",
      "Effect": "Allow",
      "Principal": { "Service": "cloudfront.amazonaws.com" },
      "Action": "s3:GetObject",
      "Resource": "arn:aws:s3:::YOUR-BUCKET-NAME/*",
      "Condition": {
        "StringEquals": {
          "AWS:SourceArn": "arn:aws:cloudfront::ACCOUNT_ID:distribution/DISTRIBUTION_ID"
        }
      }
    }
  ]
}

Now only CloudFront can read your S3 files—direct S3 URLs are blocked.


2. Fix React / Vite SPA Routing (403 & 404 Errors)

When a user visits https://app.example.com/profile directly or hits refresh, CloudFront looks for an S3 object named profile. Because it doesn't exist (and S3 is private), S3 returns 403 AccessDenied.

Fix this in CloudFront → Error pages → Create custom error response:

  • HTTP error code: 403 → Customize error response → Response page path: /index.html → HTTP response code: 200
  • HTTP error code: 404 → Customize error response → Response page path: /index.html → HTTP response code: 200

Set Default root object in CloudFront General settings to index.html.


3. Configure API Gateway CORS Without Headaches

When your frontend at https://app.example.com calls https://xyz.execute-api.us-east-1.amazonaws.com/shorten, the browser sends a preflight OPTIONS request first. If API Gateway doesn't respond with matching CORS headers, the browser blocks your fetch() call.

In AWS SAM (template.yaml):

MyHttpApi:
  Type: AWS::Serverless::HttpApi
  Properties:
    CorsConfiguration:
      AllowOrigins:
        - "https://app.example.com"
        - "http://localhost:5173"
      AllowMethods:
        - GET
        - POST
        - OPTIONS
      AllowHeaders:
        - Content-Type
        - Authorization
      MaxAge: 600

Common CORS Mistakes to Avoid

  • Trailing slash in origin: https://app.example.com/ is invalid — use https://app.example.com (no trailing slash).
  • Wildcard * with credentials: If you send Authorization cookies/credentials, browsers reject Access-Control-Allow-Origin: *. Always list your exact domain(s).
  • 500 errors hiding CORS: If your Lambda crashes with an unhandled exception, API Gateway may return a 500/502 without CORS headers, which looks like a CORS error in DevTools! Check CloudWatch Logs if a previously working endpoint suddenly throws a CORS error.

4. Invalidate CloudFront Cache After Deploys

After uploading a new frontend build to S3, run:

aws s3 sync ./dist s3://YOUR-BUCKET-NAME --delete
aws cloudfront create-invalidation --distribution-id YOUR_DIST_ID --paths "/*"

Your updated frontend will be live globally within seconds.

Found this useful?

Share it with your group