When HLS.js need to load m3u8 URL redirecting to the different URL (302 Redirection)

CK CK 3788 
Created at  
663 0 0

HLS.js, a JavaScript library used for streaming HLS (HTTP Live Streaming) video, typically supports video playback by fetching segments from a specified URL. However, it might encounter issues when dealing with URLs that use HTTP 302 redirection.

 

Why HLS.js Might Struggle with 302 Redirects:

  1. Security Restrictions: Browsers impose strict cross-origin restrictions for media content to prevent unauthorized access. When a URL is redirected (via a 302 status), the final URL might point to a different domain, potentially triggering cross-origin resource sharing (CORS) issues.
  2. Incorrect Handling of Redirects: If the 302 redirection is not handled correctly by the server or the HLS.js implementation, the library may fail to retrieve the video segments. HLS.js expects a straightforward URL that it can repeatedly request for segments, but redirection can introduce complexity.
  3. Caching and Segment Fetching: Redirection might interfere with how segments are cached and fetched. HLS.js expects certain timing and consistency from segment URLs, and redirections can disrupt this flow.

 

Example Solution:

<video id="video1" controls preload="auto" width="320" height="180"></video><br>
<script type="text/javascript">
function load_video( streaming_url )
{
	var video1 = document.getElementById("video1");
	if (Hls.isSupported())
	{
		var _hlsOptions =
		{
			xhrSetup: function(xhr, url)
			{
			},
			fetchSetup: (url, headers) => {
				return fetch(url, { headers }).then(response => {
					// Ensure the response is followed correctly
					return response;
				});
			}
		};
		var hlsvideo1 = new Hls(_hlsOptions);
		hlsvideo1.loadSource( streaming_url );
		hlsvideo1.attachMedia(video1);
		hlsvideo1.on(
			Hls.Events.ERROR,
			function(event, data)
			{
				if (data.type === Hls.ErrorTypes.NETWORK_ERROR)
				{
					console.error('Network error:', data);
					if (data.details === Hls.ErrorDetails.MANIFEST_LOAD_ERROR || 
						data.details === Hls.ErrorDetails.FRAG_LOAD_ERROR)
					{
						console.error('CORS error: Unable to load the manifest due to cross-origin restrictions:', data);
						alert( 'CORS error: Unable to load the manifest due to cross-origin restrictions at ' + streaming_url);
					}
					else
					{
						console.error( 'Unknown error: ', data);
					}
				}
			}
		);
	}
}
load_video( "{$url}" );
</script>

 

Summary:

  • HTML Video Element: A video element (<video>) with the ID video1 is defined to display the video with controls and a specified size.
  • JavaScript Function (load_video):
    • Purpose: Loads a video stream from a given URL using HLS.
    • Process:
      • The function checks if HLS is supported by the browser.
      • If supported, it sets up options for HLS, including custom header handling through xhrSetup and fetchSetup.
      • An HLS object (hlsvideo1) is created with these options.
      • The video stream is loaded from the provided URL (streaming_url) and attached to the video element (video1).
      • Error handling is implemented to catch network-related errors, particularly focusing on CORS (Cross-Origin Resource Sharing) issues. If a CORS error is detected, an alert is displayed with details about the issue.

 

The code is designed to robustly handle potential errors, especially those related to network and CORS issues, ensuring a more reliable video streaming experience.

This should help mitigate the issues related to 302 redirects when using HLS.js.

 

If the client still face the CORS error, you should change the server settings like below:

Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, POST, OPTIONS
Access-Control-Allow-Headers: Content-Type, Authorization
Tags 302 Redirection CORS CORS Error HLS.js Facebook X
Comments 0
Similar posts
  1. HLS.js code to reload when user face bufferfull error
    705
  2. HLS.js code to reload video when levelLoadTimeOut occurs
    707
  3. HLS.js options to support subtitle
    516
  4. Change the manifest loading timeout in HLS.js
    1,038
  5. How do I display trickplay images with hls.js that elaborated at EXT-X-IMAGE-STREAM-INF in m3u8
    804
  6. Limit Maximum Resolution in HLS.js
    664
  7. A prefect Apache server settings to avoid CORS error for HLS
    604
  8. Disabling Audio Tracks in HLS.js
    376
  1. Secure HLS encoding using AES-128 encryption with FFmpeg
    1,131
  2. Machine Learning Models for Ad Detection from a Video Stream
    188
  3. Unlock Flawless HLS Audio Sync: The Power of #EXT-X-INDEPENDENT-SEGMENTS
    375
  4. NVIDIA CUDA library which can be integrated with C/C++
    376
  5. Approaches to Scene Detection in Video Processing
    645
  6. FFmpeg CLI to remove audio track from MP4
    542
  7. Building GPU as a Service aka Dockerized GPU
    1,575
  8. IAB Categories (a.k.a. OpenRTB Code)
    1,013
  9. FFmpeg library that can be directly integrated into C/C++/Rust/Python without CLI
    2,068
  10. HTTP Live Streaming (HLS) was developed by Apple as part of QuickTime X in iOS3.0, and became an official standard (RFC 8126) in 2017
    596
  11. Progressive MP4 is an application of streaming techniques using the standardized MP4 container invented by MPEG LA consortium
    1,076
  12. FFmpeg CLI to mix two different audios in a single audio file such as mp3
    603
  13. FFmpeg CLI to merge a video only mp4 and mp3 audio file
    334
  14. FFmpeg CLI to convert a video file to an MP3 audio file
    348
  15. HLS.js options to support subtitle
    516
  16. HLS.js code to reload when user face bufferfull error
    705
  17. HLS.js code to reload video when levelLoadTimeOut occurs
    707
  18. Change the manifest loading timeout in HLS.js
    1,038
  19. HLS.js Custom Error Handler to load Main Manifest from unstable HLS Live Stream
    1,431
  20. Mastering Audio Sync: Keyframes, GOP, FFmpeg, and HLS Explained
    538
  21. How do I display trickplay images with hls.js that elaborated at EXT-X-IMAGE-STREAM-INF in m3u8
    804
Recently updated
  1. Why 100% SEO Guarantees Better User Engagement and How to Achieve It in Your Service
    40
  2. Why SPF and DKIM Are Essential for Linux Email Servers?
    34
  3. How do I create animated background for Google Meet?
    20,613
  4. MaxMind GeoLite2 vs. DB-IP Lite vs. ip-api.com: Choosing the Right Free IP Geolocation Solution
    244
  5. Meet Valkey: Why Redis Changed Its License, Why Valkey is Better, and How to Use It as a Drop-in Replacement
    94
  6. How Rogue Web Scrapers Are Stealing My Content and Destroying My Server
    157
  7. Array of arguments passed to script in PHP
    90
  8. Invalid Auction Storms in Ad Tech
    98
  9. Building MRC-Compliant Instrumentation in Ad Tech: Implementation Steps and Key Challenges
    202
  10. The Two Clocks of Ad Server Architecture
    70
  11. Frequency Cap Architecture Overview
    514
  12. Collecting Proof-of-Play from 100,000 Screens
    146
  13. Vector Search in Relational Databases (RDBs): Trends & Usage Environments
    287
  14. What is RedisVL?
    109
  15. Designing a Skill Registry Architecture: Minimize Token Usage and Maximize AI Performance
    230
  16. TPU & GPU Cluster Management Tools
    244
  17. The Concept of Scaffolding in AI Agents
    233
  18. Beyond Static Pipelines: Architecting LLM Multi-Agent Systems for Autonomous Workflow Orchestration
    583
  19. AI-DLC vs. AI-SDLC: Model-Centric vs. System-Centric AI Development
    258
  20. Fine-Tuning Open-Weight LLMs: Training, Licensing, and Deploying Custom Models with Ollama
    339
  21. Inside the Next-Generation Streaming Architecture: Ultra-Low Latency, SGAI, and AI Codecs
    202
  22. Machine Learning: Training vs. Ranking
    221
  23. The Continuous Learning Machine: Designing a Loop That Actually Turns
    222
  24. The Next-Gen Low-Latency Standards: LL-HLS & MoQ
    195
  25. Designing a Data Curation System Around a Vector Database
    220
  26. Extracting Context from Live Video: The Architecture Got Simpler When We Stopped Building Features
    256
  27. The New Ad Stack Behind Live Sports Streaming: Inside SGAI, EABN, and the Standards Race to Fix Live Monetization
    656
  28. Designing MLOps Architectures to Handle Seasonal Data Drift in EV Fleet Models
    195
  29. From 15 to 40+ FPS: Accelerating PyTorch Object Detection on Automotive ECUs
    217
  30. Understanding Data Lineage
    260