Skip to content

Instantly share code, notes, and snippets.

@bagusnl
Created July 6, 2023 00:56
Show Gist options
  • Save bagusnl/acd066eb784119309c690a9dfb66b950 to your computer and use it in GitHub Desktop.
Save bagusnl/acd066eb784119309c690a9dfb66b950 to your computer and use it in GitHub Desktop.
Setting up Cloudflare R2 as CDN with HTTP frontend also uploads files from GitHub repository to said CDN with Actions

Setting up Cloudflare R2 as CDN

This guide will set up a CDN with URL frontend and sync them up from GitHub Repo with Actions

Things needed:

  • A domain that is tied to Cloudflare (free CF account is probably enough, depends on the load to your CDN)

Steps:

  1. Make a Cloudflare R2 bucket

    Take a note of its bucket name.

  2. Clone the frontend

    For frontend, I used render (either kotx' Render or Erisa' Multirender, use either depending on what you need). Set up the frontend following respective guides in the README file. I personally disable folder indexing and set the cache as no-cache Push the frontend to Cloudflare as workers using their actions method.

  3. On Cloudflare Dashboard, go to Worker & Pages and open your render worker.

    Set up Custom Domains using your Cloudflare connected domain (this will be the HTTP frontend your CDN uses)

  4. On GitHub repo that you'll sync up the files from to the CDN, make a new Action

    I used ryand's r2-upload-action Make sure to grab any of the secrets needed in its README and set it up to the repository action secrets! Here the workflow file I used:

    name: Upload to R2
    on:
      push:
        branches: [ "main" ]
      workflow_dispatch:
    
    jobs:
      Upload-to-R2:
        runs-on: ubuntu-latest
        steps:
          - uses: actions/checkout@v3
            with:
              path: cl-cdn
              
          - name: cleanup
            run: |
              rm -rf ./cl-cdn/.git
              rm -rf ./cl-cdn/.github
              rm -rf ./cl-cdn/.gitignore
              rm -rf ./cl-cdn/LICENSE
              rm -rf ./cl-cdn/pack.bat
              rm -rf ./cl-cdn/start_reindex.bat
              
          - uses: ryand56/[email protected]
            with:
              r2-account-id: ${{ secrets.R2_ACCOUNT_ID }}
              r2-access-key-id: ${{ secrets.R2_ACCESS_KEY_ID }}
              r2-secret-access-key: ${{ secrets.R2_SECRET_ACCESS_KEY }}
              r2-bucket: ${{ secrets.R2_BUCKET }}
              source-dir: cl-cdn
              destination-dir: cl-cdn

Adjust all the path/dirs and cleanup sequence as needed, do not forget to delete the .git folder or else the action would fail.

  1. Try to run the action and see your frontend URL if all the files are uploaded.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment