CORS CDN and Image Loading — Cross-Origin Resource Sharing for Static Assets
In this tutorial, you will learn about CORS CDN and Image Loading. We cover key concepts, practical examples, and best practices to help you master this topic.
CORS also applies to static assets served from CDNs: fonts require CORS headers for cross-origin loading, images need CORS for canvas access, and media elements have specific CORS requirements.
What You'll Learn
- CORS requirements for @font-face fonts
- Cross-origin image loading for canvas
- Configuring crossorigin attributes on HTML elements
Why It Matters
CDN-hosted assets are essential for performance. Without proper CORS headers, your web fonts may not render, and canvas operations may fail. DodaTech's CDN serves all static assets with appropriate CORS headers.
flowchart LR
A["Static Asset"] --> B{"Resource type"}
B -->|"Font"| C["Requires ACAO header from CDN"]
B -->|"Image for canvas"| D["Requires crossorigin attribute"]
B -->|"Video/Audio"| E["May need CORS for JS access"]
B -->|"Script/Style"| F["No CORS needed (SOP exempt)"]
Code Examples
<!-- Font with CORS - CDN must serve with ACAO header -->
<style>
@font-face {
font-family: 'CustomFont';
src: url('https://cdn.example.com/fonts/custom.woff2');
}
</style>
<!-- Image with crossorigin for canvas manipulation -->
<img src="https://cdn.example.com/images/photo.jpg"
crossorigin="anonymous"
id="canvas-image">
<script>
const img = document.getElementById('canvas-image');
img.onload = () => {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
// Without crossorigin and CORS headers, this throws
ctx.drawImage(img, 0, 0);
// CORS required for toDataURL() and getImageData()
canvas.toDataURL();
};
</script>
# NGINX CORS for CDN assets
location /fonts/ {
add_header Access-Control-Allow-Origin "*";
# Fonts need CORS for cross-origin @font-face
}
location /images/ {
add_header Access-Control-Allow-Origin "*";
# Required for canvas access to images
}
location /media/ {
add_header Access-Control-Allow-Origin "*";
# For MSE and MediaSource cross-origin access
}
# Check CDN CORS headers for fonts
curl -I -H "Origin: https://app.example.com" \
https://cdn.example.com/fonts/custom.woff2 | grep -i "access-control"
# Check image CORS
curl -I -H "Origin: https://app.example.com" \
https://cdn.example.com/images/photo.jpg | grep -i "access-control"
Common Mistakes
1. Forgetting CORS for Web Fonts
Browsers require CORS for @font-face even from same-origin CDNs in some cases.
2. Omitting crossorigin Attribute on Images
JavaScript canvas operations fail silently if the image lacks the crossorigin attribute.
3. Using crossorigin="use-credentials" Without Server Support
The CDN must respond with ACAO specific origin and ACAC: true.