How to use AWS CloudFront and API Gateway side by side for the same domain

amazon-api-gatewayamazon-cloudfrontamazon-web-services

I'm putting that static assets of my website on S3, and setting up CloudFront to distribute them. These essentially holds the content users would need for any GET request on my site, to existing paths that is, with a catchall for errors.

I also have some POST requests I need to handle. Form submissions, sending emails, notifications, interacting with the database.

How can I set up Lambda (or API Gateway) side by side with CloudFront for the same domain so that CloudFront handles GET requests, and API Gateway handles requests with a body or POST requests. Or can I do it by individual URL somehow?

Best Answer

I run multiple web apps exactly with your proposed design, and I extracted gofaas, an educational Go and Lambda app, to share the techniques.

You need two separate domains, e.g. www.gofaas.net for S3 + CloudFront and api.gofaas.net for API Gateway + Lambda.

Then you can let your static site interact with the API with an API Gateway CORS configuration and some JavaScript:

fetch(`https://api.gofaas.net/work`, {
    method: "POST",
    mode: "cors",
    headers: {
        "Accept": "application/json",
        ...
    },
    body: JSON.stringify(...)
})
    .then(function(response) {
        return response.json();
    })
    .then(function (json) {
        // use response
    })
    .catch(function (err) {
        console.log("fetch error", err);
    });

Here are some guides for setting all this up:

Static Websites with S3, CloudFront and ACM

API Security with Lambda, API Gateway, CORS and JWT