Skip to content

Instantly share code, notes, and snippets.

@iamakulov
Created July 21, 2022 17:03
Show Gist options
  • Save iamakulov/01ab8a413d95c3e3612e1d6401389501 to your computer and use it in GitHub Desktop.
Save iamakulov/01ab8a413d95c3e3612e1d6401389501 to your computer and use it in GitHub Desktop.
Proxying api.my-app.com under my-app.com/api, using CloudFront or Cloudflare

Here’s how to make api.my-app.com available under my-app.com/api, using CloudFront or Cloudflare.

CloudFront

If both my-app.com and api.my-app.com are hosted in AWS, you can route requests to these instances using the CloudFront CDN.

Here’s what you’ll need to do:

  1. Create a CloudFront distribution

  2. Create two origins, one pointing to the EC2 instance (or an S3 bucket) with my-app.com, and another pointing to the EC2 instance with api.my-app.com:

    CleanShot 2022-07-21 at 18 58 52

  3. Configure Behaviors to route /api requests to the api.my-app.com server:

    CleanShot 2022-07-21 at 18 59 42

  4. Point my-app.com to the CloudFront distribution.

Cloudflare

Unfortunately, to prevent abuse, Cloudflare doesn’t support reverse proxying (unless you’re on the Enterprise plan).

This means that, to proxy /api requests to api.my-app.com, we’ll have to deploy a Worker script.

Cloudflare Workers are scripts that run on each Cloudflare server. A script receives every incoming request and tells Cloudflare how to handle that request. Here’s a script that would tell Cloudflare to proxy /api requests to api.my-app.com:

addEventListener('fetch', (event) => {
  const url = new URL(event.request.url)

  // If this is a request to /api/...
  if (url.pathname.startsWith('/api/')) {
    // Build the proper API URL
    const apiServerURL = 'https://api.my-app.com/' + url

    // Send the request to the API
    const apiResponsePromise = fetch(apiServerURL, event.request)

    // Pass the API response promise back to the user
    event.respondWith(apiResponsePromise)

    return
  }

  // Otherwise, just proxy the request unmodified
  event.respondWith(fetch(event.request))
})

To deploy the worker, use Cloudflare’s tool called wrangler. Follow steps from the Cloudflare’s guide to set up and deploy it.

After deploying the worker, go to its routes and configure it to handle requests to my-app.com/*.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment