Deploying JavaScript Apps (CDN, Minification, Bundling)

    Master production deployment: CDNs, bundlers, minification, caching, and everything needed to ship fast, globally optimized JavaScript applications.

    What You'll Learn

    • CDNs and edge delivery
    • Minification & compression
    • Code splitting for fast loads
    • Cache strategies
    • CI/CD pipelines
    • Security headers

    ๐Ÿ’ก This lesson covers advanced deployment concepts including build systems (Webpack, Vite), CDN configuration, cache strategies, and production optimization techniques used by major companies.

    Why Deployment Is More Than "Upload Files"

    Shipping a JavaScript app to the world means getting it to load fast, load globally, be secure, be versioned correctly, use caching properly, and serve as few bytes as possible.

    Development Mode

    • โ€ข Full readable JS
    • โ€ข Large files
    • โ€ข Slow load
    • โ€ข No caching
    • โ€ข Source maps
    • โ€ข Unnecessary code included

    Production Mode

    • โ€ข Minified
    • โ€ข Bundled
    • โ€ข Optimized
    • โ€ข Cached
    • โ€ข Fast & small
    • โ€ข Code-split & compressed

    Your goal: Max performance, low bandwidth cost, global speed, zero unnecessary code.

    Understanding CDNs (Content Delivery Networks)

    A CDN is a global network of servers that stores ("caches") your files and delivers them to users from the closest location. This makes your app load WAY faster globally.

    ๐Ÿ’ก When a user visits your site, they get the file from the nearest CDN node, NOT your origin server. This reduces latency by hundreds of milliseconds.

    Popular CDNs:

    • โ€ข Cloudflare - Most popular, free tier
    • โ€ข Vercel CDN - Built into Vercel deployments
    • โ€ข Netlify Edge - Built into Netlify
    • โ€ข AWS CloudFront - Enterprise-grade
    • โ€ข Fastly - Used by GitHub, Stripe

    CDNs host JavaScript bundles, CSS, images, videos, and sometimes API responses.

    Minification (Shrinking Your Code)

    Minification removes spaces, newlines, long variable names, unused code, comments, and formatting.

    Minification Demo

    See how minification reduces file size

    Try it Yourself ยป
    JavaScript
    // ===== Minification Demo =====
    // Before minification (readable):
    function calculateTotal(price, quantity) {
      const subtotal = price * quantity;
      const tax = subtotal * 0.1;
      return subtotal + tax;
    }
    
    // Let's test it!
    const total = calculateTotal(100, 5);
    console.log("Price: $100, Quantity: 5");
    console.log("Total with 10% tax: $" + total);
    
    // After minification (production), this becomes:
    // function calculateTotal(e,t){const n=e*t;return n+.1*n}
    // 
    // Typical size reduction: 30-70% sma
    ...

    Popular Minification Tools:

    • โ€ข Terser - Most common, used by Webpack/Vite
    • โ€ข esbuild minifier - Extremely fast
    • โ€ข SWC minifier - Rust-based, very fast
    • โ€ข Google Closure Compiler - Most aggressive

    Bundling (Combining Files for Fewer Requests)

    Browsers load faster when 1 big file loads instead of 30 small ones. Bundlers do tons of work:

    • โœ” Join modules into bundles
    • โœ” Remove unused code (tree-shaking)
    • โœ” Rewrite imports
    • โœ” Optimize assets
    • โœ” Split bundles into chunks
    • โœ” Handle CSS, images, fonts
    • โœ” Inject hashes for cache busting
    • โœ” Minify everything

    Popular Bundlers:

    Vite (Recommended)

    Fastest, uses esbuild for dev and Rollup for production

    Webpack

    Most configurable, huge plugin ecosystem

    Rollup

    Best for libraries and SDKs

    esbuild

    Extremely fast, written in Go

    Tree Shaking โ€” Removing Unused Code

    Tree shaking automatically removes code you import but never use.

    Tree Shaking Demo

    See how unused code is removed

    Try it Yourself ยป
    JavaScript
    // ===== Tree Shaking Demo =====
    // Imagine we have a math utilities module:
    
    // math.js exports these functions:
    function add(a, b) { return a + b; }
    function subtract(a, b) { return a - b; }
    function multiply(a, b) { return a * b; }
    function divide(a, b) { return a / b; }
    
    // In our app, we only USE add():
    const result = add(5, 3);
    console.log("Using add(5, 3):", result);
    
    // Tree Shaking Analysis:
    console.log("\n๐Ÿ“ฆ What happens in production build:");
    console.log("โœ“ add() is INCLUDED (we use 
    ...

    Code Splitting (Huge Performance Boost)

    Instead of one giant bundle, create chunks. Only load what the page needs.

    Code Splitting Demo

    Understand how code splitting works

    Try it Yourself ยป
    JavaScript
    // ===== Code Splitting Demo =====
    
    // Without code splitting:
    // One huge bundle: app.js (500KB)
    // User waits for EVERYTHING to load before seeing anything
    
    // With code splitting - separate bundles:
    const bundles = {
      "home.bundle.js": "50KB",
      "dashboard.bundle.js": "150KB", 
      "profile.bundle.js": "80KB",
      "charts.bundle.js": "200KB"
    };
    
    console.log("๐Ÿ“ฆ Code-split bundles:");
    Object.entries(bundles).forEach(([file, size]) => {
      console.log(`  ${file}: ${size}`);
    });
    
    // Dynamic import s
    ...

    Hashing & Cache Busting

    Browsers aggressively cache JS files. If you deploy updates but the old file is cached, users see OLD code. Solve this with hashed filenames.

    Hashing & Cache Busting Demo

    Learn how hashed filenames work

    Try it Yourself ยป
    JavaScript
    // ===== Hashing & Cache Busting Demo =====
    
    // Production build creates hashed filenames:
    const buildOutput = {
      files: [
        "app.8c1f19a.js",      // Hash changes when code changes
        "vendor.5a9e02d.js",   // Separate vendor bundle
        "styles.9fc3a44.css"   // CSS also hashed
      ]
    };
    
    console.log("๐Ÿ“ Production build output:");
    buildOutput.files.forEach(file => console.log("  " + file));
    
    // When you update your code:
    console.log("\n๐Ÿ”„ After code update:");
    console.log("  OLD: app.8c1f19a.
    ...

    Compression (Gzip & Brotli)

    Browsers support compressed JS files. CDNs automatically compress your bundles.

    Gzip

    Older, still common. ~60-70% compression.

    Brotli

    Newest, best compression. ~70-80% smaller.

    A 600KB file can become 80KB with Brotli. CDNs like Cloudflare and Vercel handle this automatically.

    Modern Build Systems

    Vite Configuration (Recommended)

    Vite Configuration Reference

    See Vite build configuration

    Try it Yourself ยป
    JavaScript
    // ===== Vite Configuration Reference =====
    // This is what vite.config.js looks like:
    
    console.log("๐Ÿ“„ vite.config.js structure:");
    const viteConfig = {
      build: {
        minify: "terser",       // Use Terser for minification
        sourcemap: true,         // Generate source maps for debugging
        rollupOptions: {
          output: {
            manualChunks: {
              vendor: ["lodash", "axios"]  // Split vendor code
            }
          }
        }
      }
    };
    
    console.log(JSON.stringify(viteConfig, null, 2));
    
    conso
    ...

    Webpack Configuration (Full Control)

    Webpack Configuration Reference

    See Webpack build configuration

    Try it Yourself ยป
    JavaScript
    // ===== Webpack Configuration Reference =====
    // This is what webpack.prod.js looks like:
    
    console.log("๐Ÿ“„ webpack.prod.js structure:");
    const webpackConfig = {
      mode: "production",
      output: {
        filename: "js/[name].[contenthash].js",
        clean: true
      },
      optimization: {
        minimize: true,
        splitChunks: { chunks: "all" }
      },
      plugins: ["MiniCssExtractPlugin"]
    };
    
    console.log(JSON.stringify(webpackConfig, null, 2));
    
    console.log("\n๐Ÿ”ง Key Webpack features:");
    console.log("  โœ” Product
    ...

    Cache-Control Headers

    These headers decide when browser reloads files, what gets cached, and how long it stays cached.

    Cache-Control Headers Demo

    Understand cache headers

    Try it Yourself ยป
    JavaScript
    // ===== Cache-Control Headers Demo =====
    
    console.log("๐Ÿ“ฆ Cache-Control Headers Explained:\n");
    
    // For hashed JS/CSS files (app.8c1f19a.js):
    console.log("For HASHED files (app.8c1f19a.js):");
    console.log("  Cache-Control: public, max-age=31536000, immutable");
    console.log("  โ†’ Cache for 1 YEAR");
    console.log("  โ†’ NEVER revalidate");
    console.log("  โ†’ Hash guarantees uniqueness");
    console.log("  โ†’ INSTANT load for returning visitors!");
    
    // For HTML files (index.html):
    console.log("\nFor HTML fi
    ...

    Automated Deployment (CI/CD)

    Push to GitHub โ†’ CI builds your JS โ†’ CI uploads to CDN โ†’ deployment is fully automatic.

    CI/CD Pipeline Demo

    Learn about automated deployment

    Try it Yourself ยป
    JavaScript
    // ===== CI/CD Pipeline Demo =====
    // GitHub Actions automatically builds and deploys your app!
    
    console.log("๐Ÿ”„ CI/CD Pipeline Steps:\n");
    
    const pipelineSteps = [
      "1. Developer pushes code to 'main' branch",
      "2. GitHub Actions triggers workflow",
      "3. Checkout code from repository",
      "4. Setup Node.js environment",
      "5. Run: npm install",
      "6. Run: npm run build (creates optimized bundle)",
      "7. Deploy to CDN (Cloudflare, Vercel, etc.)",
      "8. App is live globally in seconds!"
    ];
    
    pip
    ...

    SPA Rewrite Rules (Critical!)

    For history mode routing, all routes must serve index.html. Without this rule, refreshing SPA pages will crash.

    SPA Rewrite Rules Demo

    Understand SPA routing rules

    Try it Yourself ยป
    JavaScript
    // ===== SPA Rewrite Rules Demo =====
    // Without these rules, refreshing /dashboard gives 404!
    
    console.log("๐Ÿ”ง SPA Rewrite Rules by Platform:\n");
    
    const platforms = {
      "Netlify": "_redirects file: /*  /index.html  200",
      "Vercel": 'vercel.json: { "rewrites": [{ "source": "/(.*)", "destination": "/" }] }',
      "NGINX": "try_files $uri $uri/ /index.html;",
      "Apache": "RewriteRule ^ index.html [L]"
    };
    
    Object.entries(platforms).forEach(([platform, rule]) => {
      console.log(`${platform}:`);
      con
    ...

    HTTP Security Headers

    Large companies REQUIRE these headers for production apps.

    HTTP Security Headers Demo

    Learn about security headers

    Try it Yourself ยป
    JavaScript
    // ===== HTTP Security Headers Demo =====
    // These headers protect your production app!
    
    console.log("๐Ÿ”’ Essential Security Headers:\n");
    
    const securityHeaders = [
      {
        header: "Content-Security-Policy",
        purpose: "Prevents XSS attacks",
        example: "default-src 'self'; script-src 'self'"
      },
      {
        header: "Strict-Transport-Security",
        purpose: "Forces HTTPS",
        example: "max-age=31536000; includeSubDomains"
      },
      {
        header: "X-Frame-Options",
        purpose: "Prevents clickjack
    ...

    The Ultimate Production Checklist

    Performance

    • โœ” Minified
    • โœ” Tree-shaken
    • โœ” Code-split
    • โœ” Brotli compressed
    • โœ” CDN cached
    • โœ” Pre-fetch enabled

    Security

    • โœ” CSP headers
    • โœ” HTTPS enforced
    • โœ” CORS configured
    • โœ” No inline scripts
    • โœ” Sanitized user input

    Stability

    • โœ” Monitoring enabled
    • โœ” Sentry for errors
    • โœ” Fallback API endpoints
    • โœ” Failover routing

    Deployment

    • โœ” Hashed filenames
    • โœ” SPA rewrite rule
    • โœ” Environment variables
    • โœ” 404/500 pages

    Key Takeaways

    • โœ” CDNs deliver your app globally from edge servers closest to users
    • โœ” Minification shrinks code by 30-70% by removing whitespace and shortening names
    • โœ” Bundlers combine files, tree-shake unused code, and optimize assets
    • โœ” Code splitting loads only what's needed for each page
    • โœ” Hashed filenames enable aggressive caching without stale code
    • โœ” Brotli/Gzip compression reduces transfer size by 70-80%
    • โœ” CI/CD automates the entire build and deploy process
    • โœ” Security headers protect your app from XSS and other attacks

    Sign up for free to track which lessons you've completed and get learning reminders.

    Previous