The hidden cost of CDN for static assets

published at

CDN or Content Delivery Network is great. Probably they give you functionality like compressing & minify-ing your static assets on-the-fly, caching static assets for your end-user across the party, or setting you up some "static assets ceremony" so you don't need to deal with the build tools.

The most popular CDN to serve you some static assets are jsDevlir, cdnjs, unpkg, and Google Fonts CDN. Those services are great, free, and open source. I don't hate CDN but I will try to avoid it as possible.

CDN features

As the acronym said: Content Delivery Network. It will deliver you some content across the network. Not matter does your users are from Japan, Yogyakarta, California, or Semarang although your server was located at Jakarta, they all will get *almost fast *experience by conneting to the nearest edge.

So if one of my user is from California but my server is in Jakarta, they will get *the same content *like it come from the nearest their location (San Francisco for example). Also, CDN will do caching it for you. So your user will not hit your server again and again since the CDN provider have the cache for that.

Beside the core features, basically CDN will give you some additional feature like in Security. They will secure your server by hiding the real IP address, they will guard you from DDoS attack, etc.

CDN for static assets

Setting up new web project is quite overwhelm. First, you need some libraries. Second, you need some fancy fonts. Third, you need to deal with versioning so your users will get the right (and latest) assets you have.

To make your web fast, you need to deal with compression (like gzip & brotli), HTTP/2 thing, caching thing, SSL thing, etc. Fortunately, CDN basically has that feature. So although your web app only use HTTP, the CDN can serve your web in HTTPS via their load balancer. This is done using Flexible SSL like what Cloudflare did.

Back to the context, rather than we setup our new project manually (doing some curl, doing some yarn add, setup some gulp/webpack, etc), just load it from CDN is the best way to make prototype faster :)

The hidden cost?

First thing we should know is the little file that stored in our computer: Cookie. Almost all CDN require cookie, the 3rd-party cookie. One of the biggest CDN provider like Cloudflare will set you a cookie with _cfduid as a key. The value was just a hashed-anonymyzed end-user IP address to identify malicious user to their customer.

Since the Cloudflare business was not in personal data, this is not a big problem.

So, let's back to the context. Either Unpkg, CDNJS, and jsDelivr is using Cloudflare for one of their CDN services. Google Fonts CDN was using Google's in-house CDN obviously.

Let's see the interesting part of this. I only see Privacy Policy page on jsDelivr site. They don't collect any personal data, but they may collect any "Usage data", they said:

We may collect information how the Service is accessed and used ("Usage Data"). This Usage Data may include information such as your computer's** Internet Protocol address** (e.g. IP address),** browser type** ,** browser version** ,** the pages of our Service that you visit** ,** the time and date of your visit** ,** the time spent on those pages** ,** unique device identifiers** and** other diagnostic data** .

So, if you visit my girlfriend page [https://faultable.dev/dewi](/dewi) and if I'm using jsDelivr, you give them such information like:

"use strict";function instanceof(e,t){return null!=t&&"undefined"!=typeof Symbol&&t[Symbol.hasInstance]?!!tSymbol.hasInstance:e instanceof t}function _classCallCheck(e,t){if(!_instanceof(e,t))throw new TypeError("Cannot call a class as a function")}function _defineProperties(e,t){for(var a=0;a<t.length;a++){var n=t[a];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}function _createClass(e,t,a){return t&&_defineProperties(e.prototype,t),a&&_defineProperties(e,a),e}var FP=function(){function n(e,t){var a=this;if(_classCallCheck(this,n),this.svgNS="http://www.w3.org/2000/svg",this.svgBox=document.createElementNS(this.svgNS,"svg"),this.svgBox.setAttributeNS(null,"viewBox","0 0 660 656"),this.svgBox.setAttributeNS(null,"id","fingerPrint"),this.svgBox.setAttributeNS(null,"fill","#fff"),this.svgBox.style.fontFamily="monospace",this.svgBox.style.fontSize="12px",this.svgBox.style.fontWeight="bold",this.svgBox.style.width="70%",this.svgBox.style.display="block",this.svgBox.style.margin="0 auto",e&&"string"!=typeof e)throw new Error("FP constructor needs a querySelector string");t&&t.mobileDebug&&(window.onerror=function(e,t,a){return alert("Error message: "+e+"\nURL: "+t+"\nLine Number: "+a),!0}),this.fontList=this.getFonts(),this.canv=this.getCanvasFingerPrint(),(window.crypto||window.msCrypto)&&this.hashIt(this.canv,function(e){document.getElementById("fp").textContent=e.substr(35),a.canv=e,a.all=a.updateAll()}),this.all=this.updateAll(),this.lines=[]}return _createClass(n,[{key:"curveText",value:function(e,t,a){var n=document.createElementNS(this.svgNS,"path");n.setAttributeNS(null,"id","curve".concat(t)),n.setAttributeNS(null,"d",e),n.style.fill="transparent",this.svgBox.appendChild(n);var i=document.createElementNS(this.svgNS,"text");i.setAttributeNS(null,"x",25);var o=document.createElementNS(this.svgNS,"textPath");return o.setAttributeNS("http://www.w3.org/1999/xlink","xlink:href","#curve".concat(t)),o.textContent=a,i.appendChild(o),this.svgBox.appendChild(i),o}},{key:"allOffset",value:function(e){var t=this.all.substr(e,100);return t.length<100&&(t+=" :: "+this.all.substr(0,100-t.length)),t}},{key:"animate",value:function(){var t=this;setTimeout(function(){t.animate()},100),this.lines.forEach(function(e){e.index++,e.index>t.all.length&&(e.index=0),e.element.textContent=t.allOffset(e.index)})}},{key:"updateAll",value:function(){return" :: "+this.userAgent+" :: "+this.language+" :: "+this.doNotTrack+" :: "+this.plugins+" :: "+this.resolution+" :: "+this.colorDepth+" :: "+this.timeZone+" :: "+this.platform+" :: "+this.cpu+" :: "+this.gpu+" :: "+this.touch+" :: "+this.localStorage+" :: "+this.sessionStorage+" :: "+this.indexedDB+" :: "+this.canvas+" :: "+this.fonts}},{key:"str2ArrayBuffer",value:function(e){for(var t=new Uint8Array(e.length),a=0;a<e.length;a++)t[a]=e.charCodeAt(a);return t}},{key:"arrayBuffer2Hex",value:function(e){var t,a,n,i=new DataView(e),o="";for(t=0,a=i.byteLength;t<a;t++)(n=i.getUint8(t).toString(16)).length<2&&(n="0"+n),o+=n;return o}},{key:"hashIt",value:function(e,a){var t,n=this,i=window.crypto||window.msCrypto,o={name:"SHA-256"};if(i.webkitSubtle)t=i.webkitSubtle.digest(o,this.str2ArrayBuffer(e));else{if(!i.subtle)return a(e);t=i.subtle.digest(o,this.str2ArrayBuffer(e))}t.then(function(e){var t=n.arrayBuffer2Hex(e);a(t)})}},{key:"getCanvasFingerPrint",value:function(){var e=document.createElement("canvas"),a=e.getContext("2d");return a.textBaseline="top",a.font="14px 'Arial'",a.textBaseline="alphabetic",a.fillStyle="#f60",a.fillRect(20,1,62,100),["abcdefghijklmnopqrstuvwxyzABCDEFGHIJKL","MNOPQRSTUVWXYZ`~1!2@3#4$5%6^7&8*9","(0)-=+[{]}|;:',<.>/?"].forEach(function(e,t){a.fillStyle="#069",a.fillText(e,2,18*(t+1)),a.fillStyle="rgba(102, 204, 0, 0.7)",a.fillText(e,4,20*(t+1))}),a.globalCompositeOperation="multiply",a.fillStyle="#f60",a.fillRect(200,1,62,100),e.toDataURL()}},{key:"getFonts",value:function(){function u(){var e=document.createElement("span");return e.style.position="absolute",e.style.left="-9999px",e.style.fontSize="72px",e.style.fontStyle="normal",e.style.fontWeight="normal",e.style.letterSpacing="normal",e.style.lineBreak="auto",e.style.lineHeight="normal",e.style.textTransform="none",e.style.textAlign="left",e.style.textDecoration="none",e.style.textShadow="none",e.style.whiteSpace="normal",e.style.wordBreak="normal",e.style.wordSpacing="normal",e.innerHTML="mmmmmmmmmmlli",e}function e(e){for(var t=!1,a=0;a<d.length;a++)if(t=e[a].offsetWidth!==n[d[a]]||e[a].offsetHeight!==o[d[a]])return t;return t}var d=["monospace","sans-serif","serif"],h=["Andale Mono","Arial","Arial Black","Arial Hebrew","Arial MT","Arial Narrow","Arial Rounded MT Bold","Arial Unicode MS","Bitstream Vera Sans Mono","Book Antiqua","Bookman Old Style","Calibri","Cambria","Cambria Math","Century","Century Gothic","Century Schoolbook","Comic Sans","Comic Sans MS","Consolas","Courier","Courier New","Geneva","Georgia","Helvetica","Helvetica Neue","Impact","Lucida Bright","Lucida Calligraphy","Lucida Console","Lucida Fax","LUCIDA GRANDE","Lucida Handwriting","Lucida Sans","Lucida Sans Typewriter","Lucida Sans Unicode","Microsoft Sans Serif","Monaco","Monotype Corsiva","MS Gothic","MS Outlook","MS PGothic","MS Reference Sans Serif","MS Sans Serif","MS Serif","MYRIAD","MYRIAD PRO","Palatino","Palatino Linotype","Segoe Print","Segoe Script","Segoe UI","Segoe UI Light","Segoe UI Semibold","Segoe UI Symbol","Tahoma","Times","Times New Roman","Times New Roman PS","Trebuchet MS","Verdana","Wingdings","Wingdings 2","Wingdings 3","Abadi MT Condensed Light","Academy Engraved LET","ADOBE CASLON PRO","Adobe Garamond","ADOBE GARAMOND PRO","Agency FB","Aharoni","Albertus Extra Bold","Albertus Medium","Algerian","Amazone BT","American Typewriter","American Typewriter Condensed","AmerType Md BT","Andalus","Angsana New","AngsanaUPC","Antique Olive","Aparajita","Apple Chancery","Apple Color Emoji","Apple SD Gothic Neo","Arabic Typesetting","ARCHER","ARNO PRO","Arrus BT","Aurora Cn BT","AvantGarde Bk BT","AvantGarde Md BT","AVENIR","Ayuthaya","Bandy","Bangla Sangam MN","Bank Gothic","BankGothic Md BT","Baskerville","Baskerville Old Face","Batang","BatangChe","Bauer Bodoni","Bauhaus 93","Bazooka","Bell MT","Bembo","Benguiat Bk BT","Berlin Sans FB","Berlin Sans FB Demi","Bernard MT Condensed","BernhardFashion BT","BernhardMod BT","Big Caslon","BinnerD","Blackadder ITC","BlairMdITC TT","Bodoni 72","Bodoni 72 Oldstyle","Bodoni 72 Smallcaps","Bodoni MT","Bodoni MT Black","Bodoni MT Condensed","Bodoni MT Poster Compressed","Bookshelf Symbol 7","Boulder","Bradley Hand","Bradley Hand ITC","Bremen Bd BT","Britannic Bold","Broadway","Browallia New","BrowalliaUPC","Brush Script MT","Californian FB","Calisto MT","Calligrapher","Candara","CaslonOpnface BT","Castellar","Centaur","Cezanne","CG Omega","CG Times","Chalkboard","Chalkboard SE","Chalkduster","Charlesworth","Charter Bd BT","Charter BT","Chaucer","ChelthmITC Bk BT","Chiller","Clarendon","Clarendon Condensed","CloisterBlack BT","Cochin","Colonna MT","Constantia","Cooper Black","Copperplate","Copperplate Gothic","Copperplate Gothic Bold","Copperplate Gothic Light","CopperplGoth Bd BT","Corbel","Cordia New","CordiaUPC","Cornerstone","Coronet","Cuckoo","Curlz MT","DaunPenh","Dauphin","David","DB LCD Temp","DELICIOUS","Denmark","DFKai-SB","Didot","DilleniaUPC","DIN","DokChampa","Dotum","DotumChe","Ebrima","Edwardian Script ITC","Elephant","English 111 Vivace BT","Engravers MT","EngraversGothic BT","Eras Bold ITC","Eras Demi ITC","Eras Light ITC","Eras Medium ITC","EucrosiaUPC","Euphemia","Euphemia UCAS","EUROSTILE","Exotc350 Bd BT","FangSong","Felix Titling","Fixedsys","FONTIN","Footlight MT Light","Forte","FrankRuehl","Fransiscan","Freefrm721 Blk BT","FreesiaUPC","Freestyle Script","French Script MT","FrnkGothITC Bk BT","Fruitger","FRUTIGER","Futura","Futura Bk BT","Futura Lt BT","Futura Md BT","Futura ZBlk BT","FuturaBlack BT","Gabriola","Galliard BT","Gautami","Geeza Pro","Geometr231 BT","Geometr231 Hv BT","Geometr231 Lt BT","GeoSlab 703 Lt BT","GeoSlab 703 XBd BT","Gigi","Gill Sans","Gill Sans MT","Gill Sans MT Condensed","Gill Sans MT Ext Condensed Bold","Gill Sans Ultra Bold","Gill Sans Ultra Bold Condensed","Gisha","Gloucester MT Extra Condensed","GOTHAM","GOTHAM BOLD","Goudy Old Style","Goudy Stout","GoudyHandtooled BT","GoudyOLSt BT","Gujarati Sangam MN","Gulim","GulimChe","Gungsuh","GungsuhChe","Gurmukhi MN","Haettenschweiler","Harlow Solid Italic","Harrington","Heather","Heiti SC","Heiti TC","HELV","Herald","High Tower Text","Hiragino Kaku Gothic ProN","Hiragino Mincho ProN","Hoefler Text","Humanst 521 Cn BT","Humanst521 BT","Humanst521 Lt BT","Imprint MT Shadow","Incised901 Bd BT","Incised901 BT","Incised901 Lt BT","INCONSOLATA","Informal Roman","Informal011 BT","INTERSTATE","IrisUPC","Iskoola Pota","JasmineUPC","Jazz LET","Jenson","Jester","Jokerman","Juice ITC","Kabel Bk BT","Kabel Ult BT","Kailasa","KaiTi","Kalinga","Kannada Sangam MN","Kartika","Kaufmann Bd BT","Kaufmann BT","Khmer UI","KodchiangUPC","Kokila","Korinna BT","Kristen ITC","Krungthep","Kunstler Script","Lao UI","Latha","Leelawadee","Letter Gothic","Levenim MT","LilyUPC","Lithograph","Lithograph Light","Long Island","Lydian BT","Magneto","Maiandra GD","Malayalam Sangam MN","Malgun Gothic","Mangal","Marigold","Marion","Marker Felt","Market","Marlett","Matisse ITC","Matura MT Script Capitals","Meiryo","Meiryo UI","Microsoft Himalaya","Microsoft JhengHei","Microsoft New Tai Lue","Microsoft PhagsPa","Microsoft Tai Le","Microsoft Uighur","Microsoft YaHei","Microsoft Yi Baiti","MingLiU","MingLiU_HKSCS","MingLiU_HKSCS-ExtB","MingLiU-ExtB","Minion","Minion Pro","Miriam","Miriam Fixed","Mistral","Modern","Modern No. 20","Mona Lisa Solid ITC TT","Mongolian Baiti","MONO","MoolBoran","Mrs Eaves","MS LineDraw","MS Mincho","MS PMincho","MS Reference Specialty","MS UI Gothic","MT Extra","MUSEO","MV Boli","Nadeem","Narkisim","NEVIS","News Gothic","News GothicMT","NewsGoth BT","Niagara Engraved","Niagara Solid","Noteworthy","NSimSun","Nyala","OCR A Extended","Old Century","Old English Text MT","Onyx","Onyx BT","OPTIMA","Oriya Sangam MN","OSAKA","OzHandicraft BT","Palace Script MT","Papyrus","Parchment","Party LET","Pegasus","Perpetua","Perpetua Titling MT","PetitaBold","Pickwick","Plantagenet Cherokee","Playbill","PMingLiU","PMingLiU-ExtB","Poor Richard","Poster","PosterBodoni BT","PRINCETOWN LET","Pristina","PTBarnum BT","Pythagoras","Raavi","Rage Italic","Ravie","Ribbon131 Bd BT","Rockwell","Rockwell Condensed","Rockwell Extra Bold","Rod","Roman","Sakkal Majalla","Santa Fe LET","Savoye LET","Sceptre","Script","Script MT Bold","SCRIPTINA","Serifa","Serifa BT","Serifa Th BT","ShelleyVolante BT","Sherwood","Shonar Bangla","Showcard Gothic","Shruti","Signboard","SILKSCREEN","SimHei","Simplified Arabic","Simplified Arabic Fixed","SimSun","SimSun-ExtB","Sinhala Sangam MN","Sketch Rockwell","Skia","Small Fonts","Snap ITC","Snell Roundhand","Socket","Souvenir Lt BT","Staccato222 BT","Steamer","Stencil","Storybook","Styllo","Subway","Swis721 BlkEx BT","Swiss911 XCm BT","Sylfaen","Synchro LET","System","Tamil Sangam MN","Technical","Teletype","Telugu Sangam MN","Tempus Sans ITC","Terminal","Thonburi","Traditional Arabic","Trajan","TRAJAN PRO","Tristan","Tubular","Tunga","Tw Cen MT","Tw Cen MT Condensed","Tw Cen MT Condensed Extra Bold","TypoUpright BT","Unicorn","Univers","Univers CE 55 Medium","Univers Condensed","Utsaah","Vagabond","Vani","Vijaya","Viner Hand ITC","VisualUI","Vivaldi","Vladimir Script","Vrinda","Westminster","WHITNEY","Wide Latin","ZapfEllipt BT","ZapfHumnst BT","ZapfHumnst Dm BT","Zapfino","Zurich BlkEx BT","Zurich Ex BT","ZWAdobeF"],t=document.getElementsByTagName("body")[0],i=document.createElement("div"),g=document.createElement("div"),n={},o={},a=function(){for(var e=[],t=0,a=d.length;t<a;t++){var n=u();n.style.fontFamily=d[t],i.appendChild(n),e.push(n)}return e}();t.appendChild(i);for(var r=0,l=d.length;r<l;r++)n[d[r]]=a[r].offsetWidth,o[d[r]]=a[r].offsetHeight;var s=function(){for(var e,t,a,n={},i=0,o=h.length;i<o;i++){for(var r=[],l=0,s=d.length;l<s;l++){var c=(e=h[i],t=d[l],a=void 0,(a=u()).style.fontFamily="'".concat(e,"',").concat(t),a);g.appendChild(c),r.push(c)}n[h[i]]=r}return n}();t.appendChild(g);for(var c=[],B=0,T=h.length;B<T;B++)e(s[h[B]])&&c.push(h[B]);return c}},{key:"curvePoints",get:function(){return["M 67, 398 C 44, 350, 62, 221, 95, 202","M 107, 172 C 179, 54, 359, 30, 455, 86","M 485, 104 C 552, 145, 613, 256, 604, 339","M 99, 398 C 57, 222, 191, 66, 367, 94","M 400, 102 C 511, 136, 601, 247, 573, 461","M 93, 472 C 132, 414, 141, 414, 125, 333","M 128, 299 C 148, 100, 479, 19, 538, 322","M 541, 354 C 545, 429, 538, 468, 523, 526","M 117, 498 C 233, 373, 82, 329, 226, 195","M 260, 175 C 305, 149, 394, 152, 442, 200 ","M 468, 227 C 514, 286, 524, 428, 476, 563","M 135, 528 C 162, 501, 179, 476, 191, 448","M 201, 411 C 133, 115, 548, 108, 466, 465","M 460, 503 C 456, 519, 442, 568, 428, 588","M 161, 547 C 318, 419, 125, 268, 342, 227","M 377, 239 C 435, 256, 482, 411, 381, 601","M 191, 567 C 247, 518, 281, 414, 266, 357","M 262, 321 C 296, 222, 417, 249, 404, 393","M 404, 431 C 403, 480, 368, 569, 338, 606","M 223, 586 C 244, 561, 279, 511, 286, 484","M 297, 451 C 315, 363, 286, 343, 304, 306","M 326, 296 C 386, 285, 399, 461, 297, 604","M 257, 597 C 345, 490, 341, 410, 331, 326"]}},{key:"userAgent",get:function(){return"user-agent:".concat(navigator.userAgent)}},{key:"language",get:function(){return"language:".concat(navigator.language)}},{key:"canvas",get:function(){return"canvas-hash:".concat(this.canv)}},{key:"doNotTrack",get:function(){var e=navigator.doNotTrack;return 1==e?e="enabled":0==e&&(e="disabled"),"do-not-track:".concat(e)}},{key:"plugins",get:function(){for(var e="",t=0;t<navigator.plugins.length;t++){e+="plugin-".concat(t+1,":").concat(navigator.plugins[t].name,"; ")+"".concat(navigator.plugins[t].description,"; ")+"".concat(navigator.plugins[t].filename," ");for(var a=0;a<navigator.plugins[t].length;a++)e+="(".concat(navigator.plugins[t][a].description,"; ")+"".concat(navigator.plugins[t][a].type,"; ")+"".concat(navigator.plugins[t][a].suffixes,") ")}return e}},{key:"resolution",get:function(){return"resolution:".concat(screen.width,"x").concat(screen.height)}},{key:"colorDepth",get:function(){return"color-depth:".concat(screen.colorDepth)}},{key:"timeZone",get:function(){return"timezone:".concat(Intl.DateTimeFormat().resolvedOptions().timeZone?Intl.DateTimeFormat().resolvedOptions().timeZone:(new Date).getTimezoneOffset())}},{key:"platform",get:function(){return"platform:".concat(navigator.platform)}},{key:"fonts",get:function(){return"font-list:".concat(this.fontList)}},{key:"cpu",get:function(){return"CPU-cores:".concat(navigator.hardwareConcurrency)}},{key:"gpu",get:function(){var e=document.createElement("canvas").getContext("webgl"),t=e.getExtension("WEBGL_debug_renderer_info"),a=e.getParameter(e.VENDOR),n=e.getParameter(e.RENDERER);return t&&(a=e.getParameter(t.UNMASKED_VENDOR_WEBGL),n=e.getParameter(t.UNMASKED_RENDERER_WEBGL)),"GPU-vendor:".concat(a,"; GPU-renderer:").concat(n)}},{key:"touch",get:function(){var e=" -webkit- -moz- -o- -ms- ".split(" ");if("ontouchstart"in window||window.DocumentTouch&&_instanceof(document,DocumentTouch))return"touch-device:Yes";var t,a=["(",e.join("touch-enabled),("),"heartz",")"];return a=a.join(""),t=a,window.matchMedia(t).matches?"touch-device:Yes":"touch-device:No"}},{key:"localStorage",get:function(){return window.localStorage?"local-storage:Yes":"local-storage:No"}},{key:"sessionStorage",get:function(){return window.sessionStorage?"session-storage:Yes":"session-storage:No"}},{key:"indexedDB",get:function(){return window.indexedDB?"indexedDB-storage:Yes":"indexedDB-storage:No"}}]),n}();

window.onload = function () { const navigator = window.navigator const id = id => document.getElementById(id)

new FP()

window.fetch('https://api.ipify.org?format=json').then(_ => _.json()).then(res => { id('ip').innerText = res.ip })

let seconds = 0

id('browser').innerText = navigator.product id('browser_ver').innerText = navigator.userAgent id('page').innerText = window.location.href id('timestamp').innerText = new Date().toString() id('time').innerText = 0 id('pageload').innerText = ((window.performance.timing.domContentLoadedEventEnd- window.performance.timing.navigationStart) / 1000) || 'N/A'

const ticker = setInterval(() => { seconds++ id('time').innerText = seconds }, 1000)
}

Those information is not useful until it is.

That's only from one service, I don't talk about another services and another services they depend (like analytics, for example).

Conclusion

I will avoid using CDN as I can especially if my target users is not world-wide. CDN is great in another case but for my case is not. I use Cloudflare for my DNS resolver but I don't use their CDN service since I use Traefik as my load balancer.

The hidden cost here is just some "information-sharing thing" that not necessary for you and your user.

But for me, it was.

My website is fast enough  and only load little dependencies. So, why should I use CDN if I can just curl -JOI and npx uglifyjs --compress --mangle something?

Thank you.