How to Configure CORS for html2canvas With S3 and CloudFront
Fix html2canvas images that fail across origins: configure S3 CORS, CloudFront forwarding and caching, then verify the response browsers actually see.

When html2canvas captures a page containing an image from another origin, set useCORS: true and make the image response allow the origin of the page running the capture. For an S3 bucket behind CloudFront, configure an S3 CORS rule for that page origin and the image read method, then configure CloudFront to forward Origin to S3. If CloudFront caches preflight OPTIONS responses, enable OPTIONS and forward the preflight headers too. Finally, inspect the response through the CloudFront hostname: that is the response the browser evaluates.
useCORS asks html2canvas to load an image in CORS mode. It cannot grant permission by itself. The browser still requires a valid Access-Control-Allow-Origin response, and the S3 object must separately be accessible.
1. Understand the three layers
- html2canvas: choose a CORS-capable image load with
useCORS: true. It defaults to false. - S3: allow the exact origin of the page using html2canvas. An origin consists of scheme, host, and port, such as
https://www.example.com. - CloudFront: preserve the request information S3 needs to choose the CORS response, and avoid serving a cached response with the wrong CORS headers.
CORS and authorization are separate. A CORS rule does not make a private S3 object public, bypass bucket policy, or grant access to an otherwise unauthorized request. The request must pass S3 access controls as well. See the S3 CORS documentation and html2canvas FAQ.

2. Configure an S3 CORS rule
For a public image read using GET without custom request headers, this is a narrow starting rule. Replace the origin with the origin of the page that renders the capture, not the bucket or CloudFront hostname.
[
{
"AllowedOrigins": ["https://www.example.com"],
"AllowedMethods": ["GET"],
"AllowedHeaders": [],
"MaxAgeSeconds": 3000
}
]
Enter valid JSON in the bucket’s CORS configuration. S3 rules can specify allowed origins, methods, request headers, exposed headers, and the browser’s preflight max age. Keep the origin list narrow for a production site. A wildcard origin is supported but permits any page origin covered by that rule; the all-origin examples in documentation demonstrate syntax, not a requirement to open access broadly. AWS explains the rule fields in its CORS configuration examples.
Choose methods and headers from the actual request
GETis needed for ordinary image reads. AddHEADonly if your application actually sends HEAD requests.- Keep
AllowedHeadersempty if there is no preflight and no non-simple request header. If the browser preflights, allow the request headers actually listed inAccess-Control-Request-Headers. MaxAgeSecondscontrols how long browsers may reuse preflight permission. It does not determine CloudFront’s cache lifetime.- Do not add an exposed response header unless browser JavaScript needs to read it. The image rendering use case generally centers on allowing the image response, not exposing arbitrary metadata.
3. Configure CloudFront to preserve CORS behavior
When S3 owns the CORS rule, CloudFront must forward the Origin request header to the origin so S3 can evaluate the page origin and return the appropriate response. Configure this on the cache behavior serving the image path. AWS describes the forwarding and cache variation requirements in CloudFront request and response behavior.

When there is no cached preflight
Forward Origin to S3. Also forward any other request headers that your image request actually needs. If S3’s response varies by origin, configure the cache policy so that responses for different origins do not incorrectly share a cached CORS response. Only add cache-key dimensions that affect the response; extra variation can lower the cache hit ratio.
When CloudFront caches OPTIONS
If the browser issues preflight requests and CloudFront is expected to cache those responses, enable OPTIONS for the behavior and forward all three headers that S3 uses to evaluate the preflight:
OriginAccess-Control-Request-HeadersAccess-Control-Request-Method
Include the relevant request headers in the cache policy as needed so a response for one origin or preflight shape is not reused for another. If you do not intend to cache OPTIONS at CloudFront, the behavior still needs to pass the required request through correctly to S3; verify the actual distribution behavior instead of assuming a console default.
Alternative: have CloudFront add response headers
You can attach a CloudFront response headers policy to the matching behavior and have CloudFront apply CORS response headers. CloudFront can modify responses served from cache as well as responses forwarded from the origin. Decide whether the policy overrides a same-named header returned by S3; its origin-override setting determines which value is used. Avoid returning conflicting or duplicate allow-origin values. Review CloudFront response headers policies.
This route makes CloudFront the owner of the browser-facing CORS response. The S3-owned route leaves S3 as the policy source and requires CloudFront to forward the request context and cache appropriately. Choose one clear owner and verify the final response. A same-origin asset path or a controlled proxy can also avoid direct browser access to a cross-origin image; the html2canvas documentation describes its proxy option. A proxy must be restricted so it cannot be abused to fetch arbitrary internal or external URLs.
4. Enable CORS in html2canvas
const target = document.querySelector("#capture");
if (!target) {
throw new Error("Capture target #capture was not found");
}
const canvas = await html2canvas(target, {
useCORS: true,
});
document.body.appendChild(canvas);
The snippet assumes html2canvas is loaded and runs in a context that supports await. Use it after the target and its images are present. If the image server does not allow the page origin, the browser security model still prevents the canvas from using that cross-origin image. The option is documented in the html2canvas configuration reference.
Check the right origin
Suppose the application page is https://app.example.com and the image is served at https://d123.cloudfront.net/photo.png. The S3 allowlist should contain https://app.example.com. The image host is the destination, not the requesting page origin. A page served at http://app.example.com, https://www.app.example.com, or a different port has a different origin and needs to be accounted for separately.
5. Verify through CloudFront
- Open browser developer tools on the page where capture runs.
- Find the image request and confirm its request URL uses the expected CloudFront hostname and path.
- Inspect the request’s
Originvalue, if present. Compare it exactly with the S3 allowlist, including scheme and host. - Inspect the final response headers. Confirm
Access-Control-Allow-Originaccepts the page origin. Check status and response body too: an error document or access-denied response is not a successful image response. - If there is an OPTIONS request, inspect its requested method and headers, then verify the response permits them.
- Repeat after invalidating or allowing stale CloudFront objects to expire if the response appears inconsistent with the latest configuration.
The browser judges the response it receives through CloudFront, not the S3 configuration screen. Testing only the S3 endpoint can miss header forwarding, response policy, and cache behavior problems.
6. Common errors and fixes
| Symptom | Likely cause | Fix |
|---|---|---|
| Images do not render in the canvas | useCORS is false, or the image response lacks an accepted allow-origin value. |
Set useCORS: true; inspect the CloudFront response and correct S3 or CloudFront CORS configuration. |
| “Access-Control-Allow-Origin” missing from CloudFront | CloudFront did not forward Origin, a policy is absent, or a cached response lacks the header. |
Forward Origin to S3 or attach the intended response headers policy; check cache variation and stale entries. |
| Works on one hostname but not another | The page origins differ by scheme, subdomain, or port. | Add each required, exact page origin to the allowlist and verify the browser’s Origin header. |
| GET works, but preflight fails | OPTIONS is disallowed, requested headers or method are not allowed, or CloudFront omits preflight headers. | Allow the required method and headers in S3; enable OPTIONS and forward Origin, Access-Control-Request-Headers, and Access-Control-Request-Method where OPTIONS is cached. |
| Response has an unexpected allow-origin value | A CloudFront response headers policy overrides the S3 value, or the cache serves a response for a different origin. | Review origin override and cache policy; have one layer produce the intended response and vary cache entries when required. |
| 403 or 404 instead of an image | The object is private, the key is wrong, or bucket/object authorization denies the request. | Fix object access and URL independently of CORS. CORS does not grant S3 permissions. |
| Direct S3 test succeeds but browser request fails | The CloudFront behavior, cache, or response policy changes the response. | Test the exact CloudFront URL used in the page and inspect its headers and status. |
| Some third-party images still fail | Their servers do not permit your page origin, or the assets use redirects with unsuitable CORS responses. | Serve a permitted copy from your own origin or use a carefully controlled proxy. Your S3 rule cannot grant permission on another server. |
7. Performance, reliability, and cost considerations
Cache deliberately. Forwarding more headers or varying the cache on more values can reduce CloudFront cache hits. Include origin and preflight dimensions when they affect the response, but avoid unrelated variation. A response headers policy can apply headers to cached content, so it may avoid relying on S3 to generate a browser-facing header for every cached object; the override choice still needs to match the intended policy.
Keep preflight overhead in view. A browser may issue OPTIONS when request details require a preflight. A suitable MaxAgeSeconds lets the browser reuse permission for its configured period. CloudFront OPTIONS caching is a separate decision: if enabled, forward and vary on the preflight inputs that determine the answer.
Test deployment changes end to end. CORS errors can be caused by stale cache entries or a different CloudFront behavior matching the URL. Verify status and headers at the public hostname after changing S3 or distribution configuration. A successful CORS response does not guarantee the object is authorized or that the image URL is valid.
Application cost is architecture-specific. This setup uses your existing S3 and CloudFront resources; the research does not establish a universal cost or performance benchmark. Review your AWS billing and cache behavior for your traffic pattern. Do not add broad cache variation or a proxy without considering its request volume and operational needs.
8. Or skip the browser setup
If the goal is to capture a page as an image rather than render a client-side canvas, ScreenshotNeo is a website screenshot API and MCP server from Yorker Media. Its API returns PNG, JPEG, WebP, or PDF from one GET request. See the API documentation.
curl -G "https://api.screenshotneo.com/v1/shot" \
-d access_key=YOUR_API_KEY \
--data-urlencode url=https://stripe.com \
-o shot.webp
import requests
r = requests.get(
"https://api.screenshotneo.com/v1/shot",
params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"},
timeout=90,
)
r.raise_for_status()
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({
access_key: 'YOUR_API_KEY',
url: 'https://stripe.com'
});
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
if (!res.ok) throw new Error(`Screenshot request failed: ${res.status}`);
await Bun.write('shot.webp', res);
Replace the example URL and save the response in the format you request. ScreenshotNeo removes cookie/consent banners, newsletter popups, and chat widgets before capture, with each step configurable. Bot checks, blank pages, failed loads, timeouts, and cache hits are not billed; response headers identify the page verdict and billing status. Its MCP server provides take_screenshot, get_page_info, and capture_pdf for Claude, Cursor, and other MCP clients. The Free plan includes 1,000 shots per month with no card; paid plans start at $5 for 3,000 shots, and every feature is on every plan.
Sign up free for 1,000 screenshots a month with no card.
9. Short FAQ
Does setting useCORS: true bypass CORS?
No. It makes html2canvas attempt CORS mode; the image response still has to permit the page origin.
Should the S3 allow-origin value be the CloudFront hostname?
Use the origin of the page running html2canvas. The CloudFront hostname is usually the image destination in this setup.
Does an S3 CORS rule make a private image public?
No. Object and bucket permissions still decide whether the request is authorized.
Can CloudFront supply the CORS headers instead of S3?
Yes. A response headers policy can apply headers on cached and forwarded responses. Set its origin override behavior intentionally and verify the final response.
When should I use a proxy?
Use a same-origin route or controlled proxy when the image server cannot be configured to allow the page origin. Restrict what the proxy can fetch.


