Skip to content
cloudflare-static-assets logo

Cloudflare Static Assets

cloudflare-static-assets

Configure and use Cloudflare Static Assets with React Router, ensuring compatibility across development and production environments with automatic fallback handling. Use when deploying React Router applications to Cloudflare Workers that need to access files from the public directory.

SKILL.md

Full skill instructions

Cloudflare Static Assets

Overview

This skill provides a robust solution for handling static assets in React Router applications deployed to Cloudflare Workers. It addresses the common issue where files in the public directory work in development (Vite) but fail with 404 errors in production due to differences in how assets are served.

Problem Context

Development vs Production Mismatch:

  • Development (Vite): Files in public/ are automatically served at the root path
  • Production (Cloudflare Workers): Static files need to be configured separately as Static Assets

This causes code like fetch('/​data/​config.json') to work locally but fail with 404 in production.

Solution: Configuration + Utility Functions

Step 1: Configure wrangler.jsonc

Enable Static Assets by adding the assets configuration:

{
  "compatibility_date": "2024-11-18",
  "assets": {
    "directory": "./​public",
    "binding": "ASSETS"
  }
}

Step 2: Create Utility Functions

Create app/​lib/​utils/​static-assets.ts (or similar path) with the following implementation:

/​**
 * Static Assets Utility
 * 
 * Provides unified access to static files across different environments:
 * - Development (Vite): Uses standard fetch()
 * - Production (Cloudflare Workers): Uses ASSETS binding
 * - Build time (Node.js): Falls back to file system access
 */

interface CloudflareContext {
  cloudflare?: {
    env: Env;
  };
}

/​**
 * Determines if we have access to Cloudflare Workers ASSETS binding
 */
function hasAssetsBinding(context?: CloudflareContext): boolean {
  return !!context?.cloudflare?.env?.ASSETS;
}

/​**
 * Fetches a static asset with automatic fallback between ASSETS and standard fetch
 */
export async function fetchStaticAsset(
  path: string,
  context?: CloudflareContext,
  request?: Request,
): Promise<Response> {
  const normalizedPath = path.startsWith("/") ? path : `/​${path}`;

  // Try Static Assets first if available
  if (hasAssetsBinding(context) && context?.cloudflare?.env?.ASSETS) {
    try {
      const assetUrl = new URL(normalizedPath, "https://example.com");
      const assetRequest = new Request(assetUrl.toString());
      const response = await context.cloudflare.env.ASSETS.fetch(assetRequest);

      if (response.ok) return response;

      // Log fallback only in development
      if (typeof process !== "undefined" && process.env.NODE_ENV === "development") {
        console.warn(
          `[Static Assets] Failed for ${normalizedPath} (${response.status}), using fallback`
        );
      }
    } catch (error) {
      // Log errors only in development
      if (typeof process !== "undefined" && process.env.NODE_ENV === "development") {
        console.warn(`[Static Assets] Error for ${normalizedPath}:`, error);
      }
    }
  }

  // Fallback: Use standard fetch
  let url = normalizedPath;
  if (request) {
    const requestUrl = new URL(request.url);
    url = `${requestUrl.origin}${normalizedPath}`;
  }

  const response = await fetch(url);
  if (!response.ok) {
    throw new Error(
      `Static asset not found: ${normalizedPath} (${response.status})`
    );
  }

  return response;
}

/​**
 * Fetches and parses a JSON static asset
 */
export async function fetchStaticJSON<T>(
  path: string,
  context?: CloudflareContext,
  request?: Request,
): Promise<T> {
  try {
    const response = await fetchStaticAsset(path, context, request);
    const json = await response.json();
    return json as T;
  } catch (error) {
    // Log detailed errors only in development
    if (typeof process !== "undefined" && process.env.NODE_ENV === "development") {
      console.error(`Failed to fetch static JSON ${path}:`, error);
    }
    throw new Error(`Failed to load JSON asset: ${path}`);
  }
}

/​**
 * Fetches a text static asset
 */
export async function fetchStaticText(
  path: string,
  context?: CloudflareContext,
  request?: Request,
): Promise<string> {
  try {
    const response = await fetchStaticAsset(path, context, request);
    const text = await response.text();
    return text;
  } catch (error) {
    // Log detailed errors only in development
    if (typeof process !== "undefined" && process.env.NODE_ENV === "development") {
      console.error(`Failed to fetch static text ${path}:`, error);
    }
    throw new Error(`Failed to load text asset: ${path}`);
  }
}

Usage Examples

In React Router Loaders

import type { Route } from './​+types/​route';
import { fetchStaticJSON } from '~/​lib/​utils/​static-assets';

interface AppConfig {
  apiUrl: string;
  features: string[];
}

export async function loader({ request, context }: Route.LoaderArgs) {
  // Same code works in all environments
  const config = await fetchStaticJSON<AppConfig>(
    '/​data/​config.json',
    context,
    request
  );

  return { config };
}

export default function ConfigPage({ loaderData }: Route.ComponentProps) {
  const { config } = loaderData;
  
  return (
    <div>
      <h1>App Configuration</​h1>
      <p>API URL: {config.apiUrl}</​p>
      <ul>
        {config.features.map(feature => (
          <li key={feature}>{feature}</​li>
        ))}
      </​ul>
    </​div>
  );
}

Fetching Text Files

import { fetchStaticText } from '~/​lib/​utils/​static-assets';

export async function loader({ request, context }: Route.LoaderArgs) {
  const markdown = await fetchStaticText(
    '/​content/​about.md',
    context,
    request
  );

  return { markdown };
}

Benefits

  1. Environment-Agnostic: Same code works in development and production
  2. Automatic Fallback: Gracefully handles missing ASSETS binding
  3. Type Safety: TypeScript support for JSON parsing
  4. Proper Error Handling: Detailed logs in development, clean errors in production
  5. Performance: Uses Cloudflare edge for fast delivery in production

Important Considerations

Security

  • Ensure sensitive files are not in the public directory
  • Static assets are publicly accessible

File Organization

project/
├── public/
│   ├── data/
│   │   └── config.json
│   ├── content/
│   │   └── about.md
│   └── images/
│       └── logo.png
├── app/
│   └── lib/
│       └── utils/
│           └── static-assets.ts
└── wrangler.jsonc

References

More skills from majiayu000

xiaohongshu logo
majiayu000/claude-arsenal

xiaohongshu

xiaohongshu

286 148
View
agent-task-conductor logo
majiayu000/claude-skill-registry

agent-task-conductor

Conduct multi-agent task orchestration and workflow coordination.

663 1
View
conductor-setup logo
majiayu000/claude-skill-registry

conductor-setup

Initialize project with Conductor artifacts (product definition,

663 1
View
animation-designer logo
majiayu000/claude-skill-registry

animation-designer

Expert in web animations, transitions, and motion design using Framer Motion and CSS

663 1
View
diagramming logo
majiayu000/claude-skill-registry

diagramming

Creates Mermaid and ASCII diagrams for flowcharts, architecture, ERDs, state machines, mindmaps, and more. Use when user mentions diagram, flowchart, mermaid, ASCII diagram, text diagram, terminal diagram, visualize, C4, mindmap, architecture diagram, sequence diagram, ERD, or needs visual docume...

663 1
View
h3-pg logo
majiayu000/claude-skill-registry-data

h3-pg

PostgreSQL bindings for H3 hexagonal grid system. Use when working with H3 cells in Postgres, including spatial indexing, geometry/geography integration, and raster analysis.

23 1
View
conductor-development logo
majiayu000/claude-skill-registry

conductor-development

Context-Driven Development skill for projects using Conductor. Use this skill when you detect a `conductor/` directory in the project, when working on tasks defined in a `plan.md` file, or when the user asks about tracks, specs, or plans. Automatically applies TDD workflow, tracks task completion...

663 1
View
conductor-status logo
majiayu000/claude-skill-registry

conductor-status

Display project status, active tracks, and next actions

663 1
View
dockerization logo
majiayu000/claude-skill-registry

dockerization

Official Stakpak application containerization standard operating procedure, a step-by-step guidline to properly dockerize applications. This is a rule book curated by the Stakpak Team.

663 1
View

Popular AI tools

Kaiber logo
Video

Kaiber

Generate, edit, and beat-sync AI video with leading models in one workspace.

Paid
View
Vimcal logo
Productivity

Vimcal

The world's fastest calendar for remote work

Free
View

Transform Your Design with AI Designer by ImgCreator.ai

Freemium
View
Akool AI logo
Content & writing

Akool AI

Revolutionizing Video Production with AI-Powered Creativity

Paid
View

Extend an image past the frame and let AI fill the new aspect ratio.

Freemium
View
StarByFace logo
Security

StarByFace

Discover your celebrity doppelgänger with StarByFace!

Free
View
C

ChainClarity explains 700+ crypto whitepapers in plain English, with layered summaries, comparisons, research tools, alerts, and a $4.99 Pro plan.

Freemium
View
Opus Clip logo
Coding & apps

Opus Clip

Opus.ai: Revolutionize Your Web Experience

Free
View