WalshyDev

CDN with B2 + CF Workers

Mar 3rd, 2021 (edited)
440
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. 'use strict';
  2.  
  3. const desiredDomain = 'cdn.YOUR_DOMAIN.XYZ';
  4. const b2Url = 'https://f002.backblazeb2.com';
  5. const b2Bucket = 'BUCKET_NAME';
  6.  
  7. const b2UrlPath = `/file/${b2Bucket}/`;
  8. addEventListener('fetch', event => {
  9.     return event.respondWith(fileReq(event));
  10. });
  11.  
  12. // define the file extensions we wish to add basic access control headers to
  13. const corsFileTypes = ['png', 'jpg', 'gif', 'jpeg', 'webp'];
  14.  
  15. // backblaze returns some additional headers that are useful for debugging, but unnecessary in production. We can remove these to save some size
  16. const removeHeaders = [
  17.     'x-bz-content-sha1',
  18.     'x-bz-file-id',
  19.     'x-bz-file-name',
  20.     'x-bz-info-src_last_modified_millis',
  21.     'X-Bz-Upload-Timestamp',
  22.     'x-bz-info-user',
  23.     'Expires'
  24. ];
  25. const expiration = 31536000; // override browser cache for images - 1 year
  26.  
  27. // define a function we can re-use to fix headers
  28. const fixHeaders = function(url, status, headers){
  29.     let newHdrs = new Headers(headers);
  30.     // add basic cors headers for images
  31.     if (corsFileTypes.includes(url.pathname.split('.').pop())) {
  32.         newHdrs.set('Access-Control-Allow-Origin', '*');
  33.     }
  34.     // override browser cache for files when 200
  35.     if (status === 200) {
  36.         newHdrs.set('Cache-Control', "public, max-age=" + expiration);
  37.     } else {
  38.         // only cache other things for 5 minutes
  39.         newHdrs.set('Cache-Control', 'public, max-age=300');
  40.     }
  41.     // set ETag for efficient caching where possible
  42.     const ETag = newHdrs.get('x-bz-content-sha1') || newHdrs.get('x-bz-info-src_last_modified_millis') || newHdrs.get('x-bz-file-id');
  43.     if (ETag) {
  44.         newHdrs.set('ETag', ETag);
  45.     }
  46.     // remove unnecessary headers
  47.     removeHeaders.forEach(header => {
  48.         newHdrs.delete(header);
  49.     });
  50.     return newHdrs;
  51. };
  52.  
  53. async function fileReq(event) {
  54.     const cache = caches.default; // Cloudflare edge caching
  55.     const url = new URL(event.request.url);
  56.  
  57.     let response = await cache.match(url); // try to find match for this request in the edge cache
  58.    
  59.     if (response) {
  60.         // use cache found on Cloudflare edge. Set X-Worker-Cache header for helpful debug
  61.         let newHdrs = fixHeaders(url, response.status, response.headers);
  62.         newHdrs.set('X-Worker-Cache', "true");
  63.         return new Response(response.body, {
  64.             status: response.status,
  65.             statusText: response.statusText,
  66.             headers: newHdrs
  67.         });
  68.     }
  69.  
  70.     // no cache, fetch image, apply Cloudflare lossless compression
  71.     response = await fetch(b2Url + '/file/' + b2Bucket + url.pathname,
  72.         {cf: {polish: "lossless"}}
  73.     );
  74.     let newHdrs = fixHeaders(url, response.status, response.headers);
  75.     response = new Response(response.body, {
  76.         status: response.status,
  77.         statusText: response.statusText,
  78.         headers: newHdrs
  79.     });
  80.  
  81.     event.waitUntil(cache.put(url, response.clone()));
  82.     return response;
  83. }
RAW Paste Data