Cloudflare 03 ☁️ Workers Static Assets & wrangler.jsonc — Deploying SPAs and full-stack apps using Cloudflare’s unified Workers + Assets model
For years, the Cloudflare ecosystem was split into two distinct products: “Pages” for static site hosting and “Workers” for dynamic edge compute. While this separation worked for simple use cases, it created massive complexity for full-stack applications that required server-side logic (like authentication, SSR, or dynamic data) alongside static assets (images, CSS, JS). If you wanted both, you had to maintain two deployment pipelines or “glue” them together using complex routing or multiple subdomains.
The unified “Workers + Assets” model changes this paradigm. By leveraging the wrangler.jsonc configuration file and binding static assets directly to a Worker, you treat your deployment as a single atomic unit. The Worker acts as the intelligent router, deciding whether to serve a static file from the internal asset store or execute dynamic code to generate a response. This unification streamlines the CI/CD process, reduces cold starts, and places the entire application lifecycle—code and content—under a single deployment command.
This chapter covers the transition to the unified asset deployment model. We will examine the structure of wrangler.jsonc, the logic required to proxy requests from your Worker to your static assets using the ASSETS.fetch method, and the architectural benefits of bundling your full-stack logic with your frontend files.
Key point: The unified deployment model treats static assets as a bound resource within a Cloudflare Worker, allowing you to use a single Worker as a sophisticated proxy that serves static files by default and intercepts specific routes for dynamic backend execution.
Why X exists
The “two-pipeline” problem. Managing separate deployment pipelines for a static frontend and a dynamic backend is operationally expensive. You have to coordinate versions between two systems, manage two sets of environment variables, and deal with two distinct deployment logs. The unified model exists to consolidate these into a single command (wrangler deploy), ensuring the frontend and backend are always in sync.
The routing complexity. When a frontend (SPA) and a backend (API) are hosted separately, you often run into CORS issues and cookie-sharing limitations. By unifying them under one domain and one Worker, the backend is effectively the “host” of the frontend, eliminating cross-origin headaches and making session management significantly simpler.
The cold-start trade-off. While Pages is excellent for pure static content, it doesn’t offer the deep runtime control of Workers. Workers, however, were not originally designed for massive static file storage. This unification bridges the gap, allowing you to use the raw power of the V8 isolate runtime while still having access to a high-performance, edge-optimized file system for your assets.
The configuration drift. Maintaining wrangler.toml for some projects and pages.config for others leads to configuration drift. The shift toward wrangler.jsonc provides a schema-validated, standardized configuration format that supports comments and better structure, making it easier to manage complex enterprise deployments.
The atomic deployment requirement. In the old world, if your static files updated but your API did not, you could end up with an incompatible frontend/backend mismatch. Atomic deployments—where assets and logic are bundled and deployed simultaneously—guarantee that users never hit an incompatible API version for a given set of static files.
a. The Unified Assets Model
In the unified model, static assets are no longer just “uploaded” to a storage bucket; they are bundled or bound to the Worker environment. You define an assets directory in your wrangler.jsonc configuration. When you deploy, Wrangler uploads these assets to Cloudflare’s internal storage, and the Worker is granted a special binding (often called ASSETS) that allows it to fetch these files at the edge.
This removes the need for Pages entirely if you choose, or it allows you to migrate existing Pages projects into a Worker-based architecture. The Worker is the entry point for every request. If a user requests style.css, the Worker checks its internal logic. If the route isn’t caught by a dynamic function, it passes the request to env.ASSETS.fetch(request), which retrieves the file from the asset binding.
b. Configuring wrangler.jsonc
wrangler.jsonc replaces the legacy wrangler.toml. It is a JSON-with-comments file that provides structured, type-safe configuration. The most important section is the assets key, which tells Wrangler where to look for your built frontend files, and the main key, which points to your Worker entry point.
{
"main": "src/index.ts",
"compatibility_date": "2024-01-01",
"assets": {
"directory": "./dist",
"binding": "ASSETS"
}
}
This configuration ensures that every time you run wrangler deploy, the contents of ./dist are packaged alongside your Worker code. The binding key (ASSETS) is the variable name you will use inside your TypeScript/JavaScript code to access these files.
c. The Worker as the Router
The logic inside your Worker must explicitly handle the routing. You effectively have a “catch-all” handler. If a request matches a dynamic API route, you execute your custom code (e.g., database queries, SSR, auth). If it does not match, you delegate to the asset binding.
export default {
async fetch(request, env, ctx): Promise<Response> {
const url = new URL(request.url);
// Dynamic API logic
if (url.pathname.startsWith("/api/")) {
return handleApiRequest(request);
}
// Fallback to static assets
return env.ASSETS.fetch(request);
}
};
This pattern gives you total control. You can implement custom caching headers for static files, add basic auth to the entire site, or inject custom headers before the file is served. The Worker becomes the middleware for your entire application.
Complete Example Session
// ============================================
// PART 1: WRANGLER CONFIGURATION (wrangler.jsonc)
// ============================================
{
"main": "src/index.ts",
"compatibility_date": "2024-10-01",
"assets": {
"directory": "./dist",
"binding": "ASSETS"
}
}
// ============================================
// PART 2: THE WORKER ENTRY POINT (src/index.ts)
// ============================================
export interface Env {
ASSETS: Fetcher;
}
export default {
async fetch(request: Request, env: Env): Promise<Response> {
const url = new URL(request.url);
// 1. Handle API routes
if (url.pathname.startsWith("/api/")) {
return new Response(JSON.stringify({ status: "ok" }), {
headers: { "content-type": "application/json" }
});
}
// 2. Handle SPA Fallback (Redirect to index.html for React/Vue)
const assetResponse = await env.ASSETS.fetch(request);
if (assetResponse.status === 404) {
return env.ASSETS.fetch(new Request(`${url.origin}/index.html`));
}
// 3. Serve assets directly
return assetResponse;
}
};
// ============================================
// PART 3: BUILD AND DEPLOY
// ============================================
// 1. Build your frontend:
// npm run build (outputs to ./dist)
// 2. Deploy to Cloudflare:
// wrangler deploy
// ============================================
// PART 4: VERIFYING ASSET HEADERS
// ============================================
// You can modify headers before serving
const response = await env.ASSETS.fetch(request);
const newResponse = new Response(response.body, response);
newResponse.headers.set("Cache-Control", "public, max-age=31536000");
return newResponse;
The steps above covered setting up the wrangler.jsonc file, implementing the route handler that distinguishes between API calls and static assets, handling SPA fallbacks, and managing headers.
Quick Reference
Configuration Keys (wrangler.jsonc)
| Key | Description |
|---|---|
main | Path to Worker entry point |
assets.directory | Folder containing frontend files |
assets.binding | Variable name for env binding |
compatibility_date | Environment API version |
Asset Handling Logic
| Route Pattern | Handler |
|---|---|
/api/* | Custom Worker logic |
/* (files) | env.ASSETS.fetch(request) |
/* (no match) | env.ASSETS.fetch(index.html) |
CLI Commands
| Command | Action |
|---|---|
wrangler dev | Local development with assets |
wrangler deploy | Build and deploy everything |
Best Practices
✅ Do This:
// Always handle 404s for SPA routing // ✅
// Set Cache-Control headers for static assets // ✅
// Use TypeScript interfaces for Env bindings // ✅
// Use wrangler.jsonc for configuration // ✅
// Keep the asset directory distinct from src // ✅
❌ Don’t Do This:
// Ignore the 404 fallback for SPAs // ❌
// Hardcode the binding name (use Env interface) // ❌
// Mix logic and assets in the same directory // ❌
// Deploy without testing `wrangler dev` first // ❌
// Expose sensitive files in the asset directory // ❌
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| 404 on SPA Routes | Missing fallback logic | Add SPA fallback to index.html |
| Wrong MIME Types | Cloudflare auto-detect failure | Check file extensions in dist |
| Assets not found | Wrong directory path | Verify wrangler.jsonc path |
| API collisions | Route overlap | Prefix APIs with /api |
| Bloated Worker | Logic mixed with build files | Use build-step to isolate |
Real-World Examples
1. React SPA
Worker serves index.html for all non-file requests.
2. Remix/SSR App
Worker runs server-side logic and serves generated assets.
3. API-First Frontend
Worker manages auth tokens, serves frontend, and proxies API calls.
4. Legacy Site Migration
Worker wraps old static files with new dynamic HTTP headers.
5. Documentation Site
Worker injects dynamic search results into a static documentation set.
6. Micro-frontend aggregator
Worker assembles static assets from multiple sub-folders.
7. Secure Asset Proxy
Worker checks authentication cookie before serving files from assets.
8. A/B Testing Worker
Worker serves different static asset versions based on cookie headers.
9. Image Optimization Proxy
Worker intercepts image requests and optimizes them before serving.
10. Multi-tenant Dashboard
Worker selects different dist folders based on hostname.
Visual
Unified Request Flow
┌──────────────────────────────────────────────┐
│ USER REQUEST (e.g., /api/user) │
│ │ │
│ ▼ │
│ [ WORKER ENTRY ] │
│ ├── Matches /api/* ? ──► Execute API Logic │
│ └── Matches File? ──► env.ASSETS.fetch() │
│ └── No Match? ──► Fallback index.html│
└──────────────────────────────────────────────┘
The wrangler.jsonc Structure
┌──────────────────────────────────────────────┐
│ PROJECT ROOT │
│ ├── src/index.ts (The Worker Logic) │
│ ├── dist/ (The Frontend Files) │
│ └── wrangler.jsonc (The Glue) │
│ ├── main: "src/index.ts" │
│ └── assets: { "directory": "./dist" } │
└──────────────────────────────────────────────┘
Atomic Deployment Bundle
┌──────────────────────────────────────────────┐
│ DEPLOYMENT BUNDLE (Uploaded Together) │
│ │
│ [ Worker Code (JS/TS) ] │
│ + │
│ [ Static Assets (HTML/CSS/JS/Images) ] │
│ │
│ Result: Single version, atomic update. │
└──────────────────────────────────────────────┘
Summary
| Item | Value |
|---|---|
| Config Format | wrangler.jsonc |
| Asset Binding | ASSETS |
| Asset Method | env.ASSETS.fetch() |
| SPA Strategy | 404 Fallback to index.html |
| Deployment | Atomic (Logic + Assets) |
| Runtime | V8 Isolate |
Key takeaways:
- Unify your deployments. The unified model eliminates the friction of managing separate pipelines for frontend and backend code.
- The Worker is the router. By placing the Worker at the center, you gain complete control over every request, enabling features like dynamic headers, A/B testing, and custom routing.
- Assets are first-class citizens. Using
env.ASSETS.fetchallows your Worker to treat your static files as a virtual filesystem, which is both performant and easy to manage. - Use
wrangler.jsonccarefully. Ensure your paths are relative to the project root and that your build directory is correctly referenced. - SPA Fallbacks are mandatory. If you are serving a Single Page Application, your Worker must handle 404s by serving
index.htmlto ensure the client-side router functions correctly.
Remember: This unified model represents the future of Cloudflare development. By moving away from separate products and towards a single, code-centric deployment, you gain architectural clarity and operational simplicity. Treat your Worker as the brain of the application and the Asset binding as its high-speed storage layer.
Stop using slow, ad-bloated tool sites! 🤮
🔎 Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)
⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free
🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!