Image Worker (image-worker.js) – Function Documentation

This Cloudflare Worker script provides a secure API for uploading, deleting, and serving images using Cloudflare Images, with CORS and token-based authentication.

Key Components

1. corsHeaders

CORS and content-type headers to allow requests from the Striae app domain and support JSON payloads.


2. createResponse(data, status = 200)

Utility function to create a JSON Response object with the given data and status code, including CORS headers.


3. hasValidToken(request, env)

Checks if the incoming request contains a valid Authorization header matching the expected bearer token (env.API_TOKEN).
Returns: true if valid, false otherwise.


4. handleImageUpload(request, env)

Handles image upload requests:

  • Validates the authorization token.

  • Accepts a multipart/form-data POST request.

  • Appends requireSignedURLs=true to the form data.

  • Forwards the request to the Cloudflare Images API.

  • Returns the API response.


5. handleImageDelete(request, env)

Handles image deletion requests:

  • Validates the authorization token.

  • Extracts the image ID from the URL.

  • Sends a DELETE request to the Cloudflare Images API.

  • Returns the API response.


6. generateSignedUrl(url)

Generates a signed URL for secure image delivery:

  • Adds an expiration timestamp (exp) to the URL.

  • Signs the URL using HMAC SHA-256 with a secret key.

  • Appends the signature (sig) to the URL.

  • Returns the signed URL as a response.


7. handleImageServing(request, env)

Handles GET requests for image serving:

  • Validates the authorization token.

  • Generates and returns a signed image delivery URL.


8. fetch(request, env)

The main entry point for the worker. Handles HTTP requests for image operations.

Request Handling:

  • OPTIONS:
    Returns CORS headers for preflight requests.

  • POST:
    Calls handleImageUpload to upload an image.

  • GET:
    Calls handleImageServing to generate a signed image URL.

  • DELETE:
    Calls handleImageDelete to delete an image.

  • Default:
    Returns a 405 error for unsupported methods.

  • Error Handling:
    Returns a 500 error for unexpected exceptions.


Usage

This worker is intended to be deployed on Cloudflare and used as a backend for secure, authenticated image upload, deletion, and signed URL generation for image delivery, with CORS enabled for the main application domain.

Updated on