Deploying JavaScript Apps (CDN, Minification, Bundling)

Published by Brayan K

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

Part of the free JavaScript course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.

Deploy the artifact you tested, with the paths it expects

A successful development server does not prove that the production files are correct. A deployment connects a particular built artifact to response headers, routing rules, a public base path and a release process. Start with a reproducible source revision and lockfile, build it, inspect the output, and run the built version through the journeys users need.

const htmlAssets = ["app-new.js", "styles-new.css"];
const uploaded = new Set(["app-old.js", "styles-old.css", "app-new.js"]);
// Check the release's dependency set before switching its HTML into service.
const missing = htmlAssets.filter(name => !uploaded.has(name));
console.log(missing.join(","));
uploaded.add("styles-new.css");
console.log(htmlAssets.every(name => uploaded.has(name)));

// ✅ Expected output:
// styles-new.css
// true

This set check models release ordering; it does not upload files or verify a real host. Publish the required assets before exposing HTML that references them, or use the host’s atomic release mechanism. Keep a tested previous release and its assets available for rollback. Module Bundlers: Webpack, Parcel, Vite (Overview) owns creating and inspecting the bundle; this lesson owns serving and switching it.

For Vite, vite build creates a production artifact and vite preview helps inspect that artifact locally. Preview is not intended as a production server. The built files must be served by an appropriate static host or application server. Verify the project’s actual output directory rather than assuming every tool uses dist.

The base path is part of the artifact’s contract

const documentURL = "https://site.example.test/practice/tasks";
console.log(new URL("assets/app.js", documentURL).pathname);
console.log(new URL("/assets/app.js", documentURL).pathname);
console.log(new URL("/practice/assets/app.js", documentURL).pathname);

// ✅ Expected output:
// /practice/assets/app.js
// /assets/app.js
// /practice/assets/app.js

A deep route changes how a relative reference resolves. Configure the bundler’s public base for the intended hosting path, then test a direct deep-link load and reload. Do not patch one generated filename by hand while leaving dynamic imports, CSS URLs or preload references wrong. The real Vite fixture in the bundler lesson checks a subpath build; an actual deployment still needs its own host-path verification.

Check URL casing on the target host, because a local case-insensitive filesystem can hide a broken import or asset name. Check redirects and the final content type as well as status 200. A request for JavaScript that returns the app’s HTML shell can produce a MIME or syntax error even though the HTTP status looks successful.

Cache documents and versioned assets according to different lifetimes

function cacheFor(kind, versioned) {
  if (kind === "private-response") return "private, no-store";
  if (kind === "asset" && versioned) return "public, max-age=31536000, immutable";
  return "no-cache";
}
console.log(cacheFor("document", false));
console.log(cacheFor("asset", true));
console.log(cacheFor("private-response", false));

// ✅ Expected output:
// no-cache
// public, max-age=31536000, immutable
// private, no-store

This is an example policy, not a universal header prescription. A content-versioned public asset can remain fresh for a long time only when the same URL keeps the same bytes. A document that points to current assets usually needs a shorter freshness or revalidation strategy. Never mark personalized responses public merely because a CDN supports caching.

no-cache permits storage but requires successful validation before reuse. no-store asks caches not to store the response. private excludes shared-cache storage; it does not encrypt the response or replace authentication. Validators such as ETag support conditional requests, and a 304 response reuses a previously stored representation rather than providing a new full body.

const oldPage = { lazyChunk: "report-old.js" };
const currentAssets = new Set(["app-new.js", "report-new.js"]);
console.log(currentAssets.has(oldPage.lazyChunk));
currentAssets.add("report-old.js");
console.log(currentAssets.has(oldPage.lazyChunk));

// ✅ Expected output:
// false
// true

Removing every old chunk immediately can break an older tab when the user later opens a lazy feature. Retain assets for the release/cache lifetime your host and application support, and handle dynamic-import failure with an actionable recovery path. A reload prompt must not discard unsaved user work silently. Cache invalidation and rollback need to account for browsers as well as the CDN.

Minification, compression and secrecy are different properties

const deliveredJavaScript = 'const config = { apiBase: "/api", secret: "not-a-real-secret" };';
console.log(deliveredJavaScript.includes("not-a-real-secret"));
console.log(new TextEncoder().encode("é").byteLength, "é".length);

// ✅ Expected output:
// true
// 2 1

Minification reduces source representation; it is not encryption and does not make embedded credentials private. Compression encodes a representation for transfer and requires matching Content-Encoding behavior. A compressed file served without the correct headers, or compressed twice incorrectly, can break delivery. Test the response the browser actually receives, including its content type.

Vite exposes configured VITE_ variables to client code by default, and its environment values are generally strings. Treat such values as public configuration, validate their shape and do not put server credentials into them. Changing a build-time variable after the artifact was built does not necessarily change the already emitted JavaScript. Client-Side Security Essentials (XSS, CSRF, Sanitisation) owns client/server trust boundaries.

const raw = "false";
console.log(Boolean(raw));
const enabled = raw === "true";
console.log(enabled);

// ✅ Expected output:
// true
// false

Source maps help diagnose failures, but publishing them is a deliberate visibility decision. They are not a secret-storage boundary: code and embedded values already sent to a browser remain inspectable. Keep private debugging artifacts and error-reporting uploads under the access policy your project requires. Avoid logging credentials or complete personal request data.

Fallbacks should distinguish documents from missing resources

const response = { status: 200, type: "text/html", body: "<!doctype html><title>App</title>" };
const expectedType = "text/javascript";
console.log(response.status === 200);
console.log(response.type === expectedType);

// ✅ Expected output:
// true
// false

A history-based client route may need the application document, but a missing script, stylesheet or API endpoint should not be rewritten into a successful HTML document indiscriminately. Use explicit host rules for the routes the application owns. A not-found view inside the client cannot fix an incorrect HTTP status already sent by the host. Building Simple SPAs with Vanilla JavaScript owns client navigation.

const body = "Ready";
const headers = { "content-type": "text/plain; charset=utf-8", "content-length": String(new TextEncoder().encode(body).byteLength) };
const get = { status: 200, headers, body };
const head = { status: 200, headers: { ...headers }, body: "" };
console.log(get.headers["content-length"], head.headers["content-length"]);
console.log(get.body.length, head.body.length);

// ✅ Expected output:
// 5 5
// 5 0

This example models an uncompressed representation. A real server must implement HTTP semantics, content negotiation and header behavior correctly; do not assume a JavaScript object configures those automatically. HTTPS, CSP, CORS, cookies and authentication must be verified at the actual server boundary. They cannot be established by a static bundle passing a local unit check.

A CDN changes delivery, not the correctness of your application

A CDN can serve eligible cached resources near users and reduce work at an origin. It does not make expensive JavaScript execute faster, repair a bad route, or guarantee a cache hit. Compare first and repeat loads under stated conditions, inspect requests and failures, and use a representative device before claiming an improvement. JavaScript Performance Optimization Techniques owns performance measurement.

const checks = [
  { name: "document", status: 200, correctType: true },
  { name: "script", status: 200, correctType: true },
  { name: "missing-asset", status: 404, correctType: true }
];
console.log(checks.every(item => item.correctType));
console.log(checks.find(item => item.name === "missing-asset").status);

// ✅ Expected output:
// true
// 404

After release, open the home page and a direct deep link, activate a lazy feature, reload, use back/forward, and inspect a missing asset and an unknown route. Check the deployed revision and error reporting. If the release is broken, restore the known artifact and compatible routing/configuration; rebuilding an old commit with different dependency versions may not recreate the old artifact. Database migrations require their own compatibility and rollback plan.

Guided exercise: keep document and asset responses distinct

Complete the literal hints. This small policy exercise makes a missing file visible and chooses revalidation for a changing document. It does not alter any real hosting configuration.

function plan(kind, exists) {
  if (!exists) return { status: ___, cache: "no-store" }; // 👉 replace ___ with 404
  return { status: 200, cache: kind === "document" ? ___ : "public, max-age=31536000, immutable" }; // 👉 replace ___ with "no-cache"
}
console.log(plan("document", true).cache);
console.log(plan("asset", ___).status); // 👉 replace ___ with false
console.log(plan("asset", true).status);

// ✅ Expected output:
// no-cache
// 404
// 200

Brief: an explicit static response plan

Implement createStaticPolicy with an HTML string, an asset manifest and an allowlist of document routes. Snapshot the manifest’s selected fields. Paths must begin with / and contain no query, fragment, backslash, percent escape, whitespace or .. path segment. This deliberately small model takes an already separated pathname; it does not parse HTTP requests or access a filesystem. Reject duplicate routes, duplicate assets, route/asset collisions and unsupported asset types.

Assets live under /assets/, contain string bodies, use text/javascript, text/css or image/svg+xml, and explicitly declare whether their URL is versioned. That flag is a trusted release-manifest assertion, not proof of a content hash. GET/HEAD for known assets returns their content type and the chosen immutable or no-cache policy. Known document routes return HTML with no-cache. Unknown paths return 404 text with no-store. Unsupported methods return 405 with Allow: GET, HEAD.

Include the UTF-8 byte length of the selected uncompressed representation. HEAD returns an empty body with the same status and representation headers as GET. Return fresh response/header objects. Do not include secrets, deploy anything, add compression or claim these planned objects are real server responses.

function createStaticPolicy({ html, assets, routes }) {
  if (typeof html !== "string" || !Array.isArray(assets) || !Array.isArray(routes))
    throw new TypeError("html, assets and routes are required");
  const files = new Map(), pages = new Set();
  const validPath = value => typeof value === "string" && value.startsWith("/") &&
    !/[?#\\%\s]/.test(value) && !value.split("/").includes("..");
  for (const route of routes) {
    if (!validPath(route) || pages.has(route)) throw new TypeError("invalid route");
    pages.add(route);
  }
  for (const asset of assets) {
    if (!asset || !validPath(asset.path) || !asset.path.startsWith("/assets/") ||
        files.has(asset.path) || pages.has(asset.path) || typeof asset.body !== "string" ||
        !["text/javascript", "text/css", "image/svg+xml"].includes(asset.type) ||
        typeof asset.versioned !== "boolean")
      throw new TypeError("invalid asset");
    files.set(asset.path, { body: asset.body, type: asset.type, versioned: asset.versioned });
  }
  const encoder = new TextEncoder();
  return function plan(method, path) {
    if (typeof method !== "string" || !validPath(path)) throw new TypeError("invalid request");
    let status, body, type, cache, allow;
    if (method !== "GET" && method !== "HEAD") {
      status = 405; body = "Method not allowed"; type = "text/plain"; cache = "no-store"; allow = "GET, HEAD";
    } else if (files.has(path)) {
      const file = files.get(path);
      status = 200; body = file.body; type = file.type;
      cache = file.versioned ? "public, max-age=31536000, immutable" : "no-cache";
    } else if (pages.has(path)) {
      status = 200; body = html; type = "text/html"; cache = "no-cache";
    } else {
      status = 404; body = "Not found"; type = "text/plain"; cache = "no-store";
    }
    const headers = { "content-type": type + "; charset=utf-8", "cache-control": cache,
      "content-length": String(encoder.encode(body).byteLength) };
    if (allow) headers.allow = allow;
    return { status, headers, body: method === "HEAD" ? "" : body };
  };
}
const assets = [{ path: "/assets/app-v1.js", body: 'console.log("ready");', type: "text/javascript", versioned: true }];
const plan = createStaticPolicy({ html: "<!doctype html><title>App</title>", routes: ["/", "/tasks"], assets });
for (const [method, path] of [["GET", "/tasks"], ["GET", "/assets/app-v1.js"], ["GET", "/assets/missing.js"], ["POST", "/tasks"]]) {
  const result = plan(method, path);
  console.log(result.status, result.headers["content-type"], result.headers["cache-control"]);
}
const get = plan("GET", "/tasks"), head = plan("HEAD", "/tasks");
console.log(head.body === "", head.headers["content-length"] === get.headers["content-length"]);
assets[0].body = "changed after construction";
console.log(plan("GET", "/assets/app-v1.js").body);
try { plan("GET", "/../private"); }
catch (error) { console.log(error.name, error.message); }

// ✅ Expected output:
// 200 text/html; charset=utf-8 no-cache
// 200 text/javascript; charset=utf-8 public, max-age=31536000, immutable
// 404 text/plain; charset=utf-8 no-store
// 405 text/plain; charset=utf-8 no-store
// true true
// console.log("ready");
// TypeError invalid request

The model is useful because its expected outcomes are explicit and independently testable. On a real host, verify the same outcomes from actual responses, including compressed and cached variants. A policy function alone cannot confirm CDN behavior, TLS, a certificate, a deployment permission or a successful release.

Practice quiz

Why retain some older content-versioned chunks after a release?

  • An older open page may request them later
  • They make every new page execute faster
  • They replace rollback testing
  • They hide source code

Answer: An older open page may request them later. Existing tabs and cached documents can still reference old lazy assets.

What does this complete program print? const x=new URL("assets/a.js","https://site.example.test/app/tasks");console.log(x.pathname);

  • /assets/a.js
  • /app/assets/a.js
  • /app/tasks/assets/a.js
  • assets/a.js

Answer: /app/assets/a.js. Relative paths resolve against the document URL’s directory.

What does Cache-Control: no-cache mean?

  • Never store the response
  • Encrypt the response
  • Validate before reusing a stored response
  • Cache forever

Answer: Validate before reusing a stored response. No-cache and no-store have different storage/reuse semantics.

What does this complete program print? console.log(Boolean("false"),"false"==="true");

  • false false
  • false true
  • true true
  • true false

Answer: true false. Environment strings need explicit parsing.

Why is an HTML body with status 200 wrong for a missing script?

  • The browser still needs valid JavaScript and the right content type
  • Every 200 response is valid JavaScript
  • The CDN automatically converts it
  • Scripts cannot return 404

Answer: The browser still needs valid JavaScript and the right content type. Status success alone does not establish the resource contract.

What does this complete program print? console.log(new TextEncoder().encode("é").byteLength,"é".length);

  • 1 1
  • 2 1
  • 2 2
  • 1 2

Answer: 2 1. UTF-8 bytes and UTF-16 code units are different measurements.

What does this complete program print? const required=["a.js","b.css"],available=new Set(["a.js"]);console.log(required.every(x=>available.has(x)));

  • true
  • undefined
  • false
  • null

Answer: false. The release still has a missing dependency.

What does a local response-policy test establish?

  • The live CDN uses those headers
  • A TLS certificate is valid
  • The release reached every user
  • The modeled policy returns the tested plans

Answer: The modeled policy returns the tested plans. Actual hosting and delivery behavior require deployment checks.

Continue this course

Related lessons