Setting up a cdn on a custom subdomain using Jsdelivr and Cloudflare Workers
  • For purely aesthetic reasons, I wanted to be able to let people add mini js to their site with a "clean" url like https://cdn.mini-js.com/1.0.1.js instead of a longer one like https://cdn.jsdelivr.net/npm/tonic-minijs@1.0.1/dist/minijs.umd.js

  • We already have a Github action that auto-releases new versions to NPM, and jsdeliver is free and works out of the box with npm. So all I needed was a cloudflare worker that would accept an incoming request, fetch the necessary file from jsdelivr, and serve it to the user.

  • Step 1 - Create a new Cloudflare worker

  • I've previously written very similar proxies, but this time I had Chat GPT write most of it (yes I checked the work - it had 2 or 3 minor issues to fix but overall was remarkably accurate and probably saved me 30 to 60 minutes). All it does is get the required parameters, send a request to jsdelivr, and serve the response, along with the necessary headers.

  • addEventListener('fetch', event => {
      event.respondWith(handleRequest(event.request))
    })
    
    async function handleRequest(request) {
      // Parse the URL of the incoming request to get the file name
      const url = new URL(request.url);
      const path = url.pathname.split('/');
      const fileName = path[1]; // Assuming the URL pattern is like /mini.js, /latest.js, etc.
    
      // Check if the request is for a minified file
      const isMinified = fileName.includes('.min');
    
      // Determine if the request is for the "latest" version based on file name
      const isLatest = fileName.startsWith('mini') || fileName.startsWith('latest');
      
      // Construct the URL to fetch the JS from jsDelivr
      let jsDelivrURL;
      if (isLatest) {
        // For latest version, omit the version in the URL
        jsDelivrURL = `https://cdn.jsdelivr.net/npm/tonic-minijs/dist/minijs.umd.${isMinified ? 'min.' : ''}js`;
      } else {
        // For specific versions, include the version in the URL
        const version = fileName.replace('.js', '').replace('.min', ''); // Remove .js and .min if present
        jsDelivrURL = `https://cdn.jsdelivr.net/npm/tonic-minijs@${version}/dist/minijs.umd.${isMinified ? 'min.' : ''}js`;
      }
    
      // Fetch the script from jsDelivr
      const response = await fetch(jsDelivrURL);
    
      // Return the fetched script as the response
      // Optionally, you can add headers to modify CORS policies, caching, etc.
      const headers = new Headers(response.headers);
      headers.set('Access-Control-Allow-Origin', '*'); // Ensure CORS compatibility
      // Example: Set caching headers
      // headers.set('Cache-Control', 'public, max-age=86400');
    
      return new Response(response.body, {
        status: response.status,
        statusText: response.statusText,
        headers: headers
      });
    }
    
  • Step 2. Add a new worker route, pointing to the newly created worker

  • We now need to tell cloudflare to direct incoming requests to the newly-created worker.

  • Step 3. Add a CNAME record for the subdomain

  • This step is a bit confusing, because you would intuit that the previous step would do this automatically. But with Cloudflare you have to also manually add the DNS record after adding the worker route. The "content" field doesn't matter here - it's a filler. What does matter is that the proxied switch is turned on.

  • That's it! Once the CNAME propagates, we now have short, pretty, CDN-served urls.


  • What about Cost?

  • Cloudflare's default CDN is completely free, and their workers free plan has 100,000 free requests per day. Because every request is cached, and the files are static, we only actually need one request per new version of mini. This means that in theory this should be able to serve millions of requests for zero cost 🤯. (This is my current understanding of Cloudflare - I'll have to monitor the actual workers usage over the next 24 hours to confirm)


  • Website Page