Skip to content

secondsky/claude-skills / plugins/cloudflare-images/skills/cloudflare-images

cloudflare-images

Unverified

This skill should be used when the user asks to "upload images to Cloudflare", "implement direct creator upload", "configure image transformations", "optimize WebP/AVIF", "create image variants", "generate signed URLs", "add image watermarks", "integrate with Next.js/Remix", "configure webhooks", "debug CORS errors", "troubleshoot error 5408/9401-9413", or "build responsive images with Cloudflare Images API".

FileKindSize
SKILL.mdskill md13.9 KB
assets/diagrams/direct-upload-workflow.mdmarkdown5.0 KB
assets/diagrams/transformation-pipeline.mdmarkdown8.2 KB
assets/diagrams/variants-structure.mdmarkdown10.6 KB
examples/basic-upload/.env.exampleother474 B
examples/basic-upload/README.mdmarkdown6.5 KB
examples/basic-upload/package.jsonmanifest542 B
examples/basic-upload/public/index.htmlother12.7 KB
examples/basic-upload/src/index.tsscript2.7 KB
examples/basic-upload/wrangler.jsoncother378 B
examples/private-images/.env.exampleother631 B
examples/private-images/README.mdmarkdown12.5 KB
examples/private-images/package.jsonmanifest741 B
examples/private-images/public/index.htmlother18.0 KB
examples/private-images/src/index.tsscript5.2 KB
examples/private-images/wrangler.jsoncother427 B
examples/responsive-gallery/README.mdmarkdown4.3 KB
references/api-reference.mdmarkdown8.1 KB
references/content-credentials.mdmarkdown11.6 KB
references/custom-domains.mdmarkdown10.5 KB
references/direct-upload-complete-workflow.mdmarkdown11.2 KB
references/format-optimization.mdmarkdown7.2 KB
references/framework-integration.mdmarkdown15.4 KB
references/overlays-watermarks.mdmarkdown11.1 KB
references/polish-compression.mdmarkdown10.4 KB
references/responsive-images-patterns.mdmarkdown6.1 KB
references/setup-guide.mdmarkdown3.8 KB
references/signed-urls-guide.mdmarkdown7.5 KB
references/sourcing-kit.mdmarkdown15.0 KB
references/top-errors.mdmarkdown11.7 KB
references/transformation-options.mdmarkdown6.4 KB
references/variants-guide.mdmarkdown6.7 KB
references/webhooks-guide.mdmarkdown11.8 KB
scripts/analyze-usage.shexecutablescript6.6 KB
scripts/check-versions.shexecutablescript3.3 KB
scripts/generate-signed-url.shexecutablescript4.4 KB
scripts/test-upload.shexecutablescript4.4 KB
scripts/validate-variants.shexecutablescript5.2 KB
templates/batch-upload.tsscript7.8 KB
templates/direct-creator-upload-backend.tsscript5.4 KB
templates/direct-creator-upload-frontend.htmlother8.4 KB
templates/nextjs-integration.tsxother11.4 KB
templates/overlay-watermark.tsscript13.7 KB
templates/package.jsonmanifest387 B
templates/remix-integration.tsxother15.0 KB
templates/responsive-images-srcset.htmlother8.0 KB
templates/signed-urls-generation.tsscript6.6 KB
templates/transform-via-url.tsscript6.5 KB
templates/transform-via-workers.tsscript8.7 KB
templates/upload-api-basic.tsscript3.8 KB
templates/upload-via-url.tsscript4.9 KB
templates/variants-management.tsscript7.0 KB
templates/webhook-handler.tsscript8.8 KB
templates/wrangler-images-binding.jsoncother1.2 KB

templates/upload-api-basic.ts

View on GitHub
/**
 * Cloudflare Images - Basic Upload via API
 *
 * Uploads an image file to Cloudflare Images storage.
 *
 * Usage:
 *   const result = await uploadImageToCloudflare(file, {
 *     requireSignedURLs: false,
 *     metadata: { userId: '12345' }
 *   });
 */

interface Env {
  IMAGES_ACCOUNT_ID: string;
  IMAGES_API_TOKEN: string;
}

interface UploadOptions {
  id?: string; // Custom ID (optional, auto-generated if not provided)
  requireSignedURLs?: boolean; // true for private images
  metadata?: Record<string, string>; // Max 1024 bytes, not visible to end users
}

interface CloudflareImagesResponse {
  success: boolean;
  result?: {
    id: string;
    filename: string;
    uploaded: string;
    requireSignedURLs: boolean;
    variants: string[];
  };
  errors?: Array<{ code: number; message: string }>;
}

/**
 * Upload image to Cloudflare Images
 */
export async function uploadImageToCloudflare(
  file: File,
  options: UploadOptions = {},
  env: Env
): Promise<CloudflareImagesResponse> {
  const formData = new FormData();

  // Required: File to upload
  formData.append('file', file);

  // Optional: Custom ID (if not provided, auto-generated)
  if (options.id) {
    formData.append('id', options.id);
  }

  // Optional: Require signed URLs for private images
  if (options.requireSignedURLs !== undefined) {
    formData.append('requireSignedURLs', String(options.requireSignedURLs));
  }

  // Optional: Metadata (JSON object, max 1024 bytes)
  if (options.metadata) {
    formData.append('metadata', JSON.stringify(options.metadata));
  }

  // Upload to Cloudflare Images API
  const response = await fetch(
    `https://api.cloudflare.com/client/v4/accounts/${env.IMAGES_ACCOUNT_ID}/images/v1`,
    {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${env.IMAGES_API_TOKEN}`
        // Don't set Content-Type - FormData sets it automatically with boundary
      },
      body: formData
    }
  );

  const result: CloudflareImagesResponse = await response.json();

  if (!result.success) {
    console.error('Upload failed:', result.errors);
    throw new Error(`Upload failed: ${result.errors?.[0]?.message || 'Unknown error'}`);
  }

  return result;
}

/**
 * Example Cloudflare Worker endpoint
 */
export default {
  async fetch(request: Request, env: Env): Promise<Response> {
    if (request.method === 'POST' && new URL(request.url).pathname === '/upload') {
      try {
        // Parse multipart/form-data from request
        const formData = await request.formData();
        const file = formData.get('image') as File;

        if (!file) {
          return Response.json({ error: 'No file provided' }, { status: 400 });
        }

        // Upload to Cloudflare Images
        const result = await uploadImageToCloudflare(
          file,
          {
            requireSignedURLs: false,
            metadata: {
              uploadedBy: 'worker',
              timestamp: new Date().toISOString()
            }
          },
          env
        );

        return Response.json({
          success: true,
          imageId: result.result?.id,
          variants: result.result?.variants
        });

      } catch (error) {
        return Response.json(
          { error: error instanceof Error ? error.message : 'Upload failed' },
          { status: 500 }
        );
      }
    }

    return Response.json({ error: 'Method not allowed' }, { status: 405 });
  }
};

/**
 * Example usage from another script:
 *
 * ```typescript
 * const fileInput = document.querySelector('input[type="file"]') as HTMLInputElement;
 * const file = fileInput.files?.[0];
 *
 * if (file) {
 *   const result = await uploadImageToCloudflare(file, {
 *     requireSignedURLs: false,
 *     metadata: { source: 'user-upload' }
 *   }, env);
 *
 *   console.log('Uploaded:', result.result?.id);
 *   console.log('Serve at:', result.result?.variants[0]);
 * }
 * ```
 */
finishing-a-development-branchobra/superpowersUse when implementation is complete, all tests pass, and you need to decide how to integrate the workStars: 322kUpdated Claude CodeCodexVerifiedInstall
systematic-debuggingobra/superpowersUse when encountering any bug, test failure, or unexpected behavior, before proposing fixesStars: 322kUpdated Claude CodeCodexVerifiedInstall
test-driven-developmentobra/superpowersUse when implementing any feature or bugfix, before writing implementation codeStars: 322kUpdated Claude CodeCodexVerifiedInstall
skill-creatoranthropics/skillsCreate new skills, modify and improve existing skills, and measure skill performance. Use when users want to create a skill from scratch, edit, or optimize an existing skill, run evals to test a skill, benchmark skill performance with variance analysis, or optimize a skill's description for better triggering accuracy.Stars: 198kUpdated Claude CodeCodexVerifiedInstall