Key Components
1. corsHeaders
Defines CORS and content-type headers to allow cross-origin requests from the main 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. hasValidHeader(request, env)
Checks if the incoming request contains a valid X-Custom-Auth-Key
header matching the secret in the environment (env.R2_KEY_SECRET
).
Returns: true
if valid, false
otherwise.
4. fetch(request, env)
The main entry point for the worker. Handles HTTP requests for JSON file operations.
Request Handling:
-
OPTIONS:
Returns CORS headers for preflight requests. -
Authentication:
Rejects requests without a validX-Custom-Auth-Key
header. -
Filename Validation:
Only allows access to files ending with.json
. -
Bucket Access:
Usesenv.STRIAE_DATA
as the R2 bucket for file storage.
Supported Methods:
-
GET:
Retrieves and returns the contents of the specified JSON file. Returns an empty array if the file does not exist. -
PUT:
Replaces the contents of the specified JSON file with the request body. -
DELETE:
Deletes the specified JSON file from the bucket. -
Default:
Returns a 405 error for unsupported methods.
Error Handling:
-
Returns a 400 error for invalid file types.
-
Returns a 403 error for authentication failures.
-
Returns a 404 error if a file to delete does not exist.
-
Returns a 500 error for unexpected exceptions, logging the error to the console.
Usage
This worker is intended to be deployed on Cloudflare and used as a backend for secure, authenticated JSON data storage and retrieval, with CORS enabled for the main application domain.