Sub topic 17
Cross-origin media and CORS
This chapter assumes you can write basic HTML and JavaScript and know what an HTTP header is. It also assumes you know what an origin is: the combination of scheme, host, and port. A page at https://app.example.com and a file at https://cdn.example.net/clip.mp4 are on different origins.
Playing is allowed, reading is not
Browsers let a page play media from another origin without any special setup. A video element with a cross-origin src makes a plain request, and the browser plays the result. This works without CORS (Cross-Origin Resource Sharing, the header-based system that lets a server permit other origins to read its responses).
The restriction applies to reading. If the response comes from another origin without permission, the browser treats it as opaque. The page can display it but cannot inspect its bytes. These features need that permission:
- Drawing video frames to a canvas and then reading pixels with
getImageData(),toDataURL(), ortoBlob(). - Routing audio into the Web Audio API with
createMediaElementSource(). - Loading a
trackfile (captions or subtitles) from another origin. - Fetching media segments with
fetch()orXMLHttpRequest, for example in adaptive streaming.
Without permission, canvas reads throw a SecurityError, Web Audio produces silence, and cross-origin tracks are not loaded.
The crossorigin attribute
The crossorigin attribute on audio and video changes how the browser requests the media. Without it, the request is in "no-cors" mode: it succeeds, but the response is opaque. With it, the request is in CORS mode, and the server must send permission headers.
| Value | Meaning |
|---|---|
| absent | No-cors request. Playback works, but the media is tainted for scripts. |
| `anonymous` (or empty) | CORS request. Cookies and credentials are sent only to the same origin. |
| `use-credentials` | CORS request. Cookies and credentials are also sent cross-origin. |
An unrecognized value is treated as anonymous.
<video controls crossorigin="anonymous" width="640">
<source src="https://cdn.example.net/clip.webm" type="video/webm">
<source src="https://cdn.example.net/clip.mp4" type="video/mp4">
<track kind="captions" src="https://cdn.example.net/clip.en.vtt"
srclang="en" label="English" default>
</video>Put the attribute on the video element, not on source. The source element has no crossorigin attribute, and all of its candidates inherit the setting from the parent. The track element uses the same setting. A cross-origin track is fetched in CORS mode, so the media element's crossorigin attribute must be set and the caption server must send CORS headers too. If it does not, the captions silently fail to appear.
Set crossorigin in the markup, before the browser starts loading. If you create elements in JavaScript, assign video.crossOrigin = 'anonymous' before you assign src.
What the server must send
For a CORS-mode media request, the response needs an Access-Control-Allow-Origin header. Its value is either the requesting origin or *. The * form is not allowed with use-credentials. In that case the server must echo the exact origin and also send Access-Control-Allow-Credentials: true.
If the server echoes different origins on different requests, it must add Vary: Origin. Otherwise a shared cache may store the response for one origin and serve it to another, which then fails.
Here is an nginx example, placed in a server block:
location /media/ {
add_header Access-Control-Allow-Origin "https://app.example.com" always;
add_header Access-Control-Expose-Headers "Content-Length, Content-Range, Accept-Ranges" always;
add_header Vary Origin always;
}The always flag makes nginx add the headers to error responses, such as 416 for a bad range. Without it, a failing range request looks like a CORS failure and hides the real cause.
Access-Control-Expose-Headers matters when your own script uses fetch() and needs to read Content-Range or Accept-Ranges. By default, scripts can read only a short list of safe response headers. The media element itself does not need this header.
Range requests and preflight
Media elements ask for byte ranges with a Range header, as described in the previous chapter on server delivery. A simple Range: bytes=0- header is safelisted by the Fetch standard, so it does not trigger a preflight (an extra OPTIONS request that asks permission first). A script using fetch() with unusual ranges or custom headers can trigger one. In that case the server must answer OPTIONS with Access-Control-Allow-Methods and Access-Control-Allow-Headers.
Deciding whether you need CORS
Reading pixels safely
This script copies a frame to a canvas and reads it. It works only if the media is same-origin or CORS-approved.
const video = document.querySelector('video');
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
video.addEventListener('loadeddata', () => {
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
ctx.drawImage(video, 0, 0);
try {
const pixels = ctx.getImageData(0, 0, canvas.width, canvas.height);
console.log('Read', pixels.data.length, 'bytes of pixel data');
} catch (err) {
console.error('Canvas is tainted:', err.name);
}
});drawImage() never throws for a cross-origin video. It draws the frame and marks the canvas as tainted. The error appears later, at the read. That delay makes the bug easy to misdiagnose.
Common failure modes
- Adding crossorigin breaks playback. Once the attribute is set, a response without valid CORS headers is rejected. The element fires an
errorevent, andvideo.error.codeis4(MEDIA_ERR_SRC_NOT_SUPPORTED). The same file played fine before. Fix the server, not the markup, unless you do not need script access. - Wrong origin string.
https://app.example.comandhttps://app.example.com:8443are different origins. The header must match exactly, including scheme. - Redirects. Every hop in a redirect chain must pass the CORS check. A CDN that redirects to a storage bucket with no CORS configuration fails at the last hop.
- Cache poisoning. If an earlier no-cors request cached the file without CORS headers, a later CORS-mode request may reuse that cached copy and fail. Using
Vary: Originand consistentcrossoriginsettings across your pages avoids this. - Credentials with a wildcard.
use-credentialswithAccess-Control-Allow-Origin: *is rejected. Useanonymousunless the media truly depends on cookies. - Mixed content. An
httpspage cannot loadhttpmedia. This is a separate rule from CORS, but it produces a similar-looking failure.
You can detect a CORS failure in code by listening for the error event:
const video = document.querySelector('video');
video.addEventListener('error', () => {
const err = video.error;
console.error('Media error code', err.code, err.message);
});The browser console usually names the missing header, which is more precise than the media error code.
Adaptive streaming with Media Source Extensions depends on this chapter. The player downloads segments with fetch() and hands the bytes to the browser, so the segment host must allow your origin and expose the headers your player reads.
Exercise
A page at https://app.example.com plays https://cdn.example.net/clip.mp4 with a plain video element. The team adds crossorigin="anonymous" so it can draw frames to a canvas. Playback now fails, and video.error.code is 4. What is the likely cause, and what are two ways to fix it?
Show answer
The CDN does not send an Access-Control-Allow-Origin header that permits https://app.example.com. With crossorigin set, the request is in CORS mode, so the browser rejects the response. Fix 1: configure the CDN to send Access-Control-Allow-Origin with the page's origin (plus Vary: Origin if it varies by origin). Fix 2: remove the crossorigin attribute if canvas reads are not needed, which restores plain playback.