Resolved

AWS S3 integration fails in Cloudflare Workers with DOMParser error

Cloudflare Workers
AWS S3
JavaScript
TypeScript
Serverless
API Integration
Frontend
Debugging

AWS SDK v3 fails in Cloudflare Workers due to missing DOMParser browser API | Environment variables inaccessible via process.env in Workers runtime

AWS S3 integration in Cloudflare Workers failed due to missing browser APIs and environment variable access issues, preventing the /inspire gallery page from loading any S3-hosted media assets.

Issue

The AWS S3 integration encountered two critical errors in Cloudflare Workers:

  • DOMParser not defined: The AWS SDK v3 failed because the DOMParser API, required for parsing S3 XML responses, was unavailable in the Workers environment.
  • Environment variables inaccessible: AWS credentials could not be accessed via process.env, resulting in missing AWS configuration errors.

This prevented the /inspire gallery page from loading any S3-hosted media assets.

Culprit

The issues stemmed from:

  • DOMParser Dependency: The AWS SDK v3 relies on the browser’s DOMParser API, which is not available in Cloudflare Workers.
  • Environment Variable Access: Cloudflare Workers do not use process.env for accessing secrets; instead, they require a different runtime pattern.
  • Build System Conflict: Leftover backup files in the build process caused confusion and obscured the primary issues.

Solution

AWS SDK Replacement with aws4fetch

The AWS SDK v3 was replaced with the lightweight aws4fetch library, designed specifically for Cloudflare Workers. This change eliminated the DOMParser dependency and reduced the bundle size significantly.

Runtime Environment Access Pattern

A dual-environment access pattern was implemented to ensure compatibility with both production and development environments, allowing access to AWS credentials correctly in the Workers runtime.

Build System Cleanup

Leftover backup files were removed or prefixed to prevent build warnings and routing conflicts, ensuring a clean environment for integration.

XML Parsing Utility

A lightweight XML parsing utility was created to replace the DOMParser functionality, ensuring compatibility with the Workers runtime.

Outcome: The AWS S3 integration now works correctly in Cloudflare Workers, enabling the /inspire gallery page to load media assets successfully.