A Cloudflare Worker for proxying and caching images, with optional rate limiting and a convenient setup process.
MIT License
To prevent exorbitant Cloudflare bills, I developed this worker after several unsuccessful attempts with other repositories. The major advantage of this solution is that you can use Cloudflare image resizing without incurring excessive costs.
This approach significantly reduces the number of image transformations performed by Cloudflare, thereby minimizing costs while still leveraging Cloudflare's powerful image resizing capabilities.
While this worker is designed to help manage costs, bugs can happen and unforeseen issues may arise. Always monitor your usage and costs when implementing any new solution.
Before you begin, ensure you have met the following requirements:
Clone the repository:
git clone https://github.com/yourusername/cloudflare-image-proxy-worker.git
cd cloudflare-image-proxy-worker
Install dependencies:
npm install
Run the initialization script:
npm run init
Follow the prompts to enter your Cloudflare configuration details. This will create a .env
file and update your wrangler.toml
file.
(Optional) Manually edit the .env
file to adjust any settings.
Once deployed, the worker will handle image requests in the following format:
https://your-worker-subdomain.workers.dev/<id>-<variant>.png
id
: The image name or path to find the image on the old server and use as id in R2variant
: The desired variant or size of the image (e.g., 'original', 'thumbnail', etc.) as created in Cloudflare imagesThe worker will fetch the image from your source URL, cache it in R2, and serve it through Cloudflare's CDN.
Response:
The image response will be a binary if it is found on R2 or Cloudflare Images. If it's needed to be uploaded from the source url you will be redirect to the new path of the image on your configured live domain:
# Without variant
https://cdn.example.com/id.extension
# With variant
https://cdn.example.com/id-variant.extension
To run the worker locally for development:
npm run dev
This will start a local development server using Wrangler.
To deploy the worker to Cloudflare:
npm run deploy
This script will update the configuration, build the worker, and deploy it to your Cloudflare account.
Contributions are welcome! Please feel free to submit a Pull Request.
This project is licensed under the MIT License.