4

I am developing an application where server streams some video files and ReactJS-based client can play that stream using react-player.

Everything works great when I'm playing the stream using ordinary url variable from ReactPlayer component. But now I need to pass some data (authorization token) in header along with request to get access to the stream.

Ideally would be to somehow make request to the stream using Fetch API and then bypass only video data to ReactPlayer component, but I'm not sure if it is possible.

Does react-player supports such situation? If not, how can I achieve this or is there any other universal video player I can use that supports custom request crafting?

If that matters backend server is a Flask based REST api application.

SP5RFD
  • 841
  • 3
  • 17
  • 31

2 Answers2

4

The solution I used is to modify the XHR request send by HLS when loading the stream. This is made by giving to ReactPlayer component some options for hls :

          <ReactPlayer
              config={{
                file: {
                  hlsOptions: {
                    forceHLS: true,
                    debug: false,
                    xhrSetup: function(xhr, url) {
                      if (needsAuth(url)) {
                        xhr.setRequestHeader('Authorization', getToken())
                      }
                    },
                  },
                },
              }}
            />

The list of options for hls is available here.

You may use this since react-player version 1.1.2 according to this github issue

Stephane L
  • 2,879
  • 1
  • 34
  • 44
1

I spent several hours on this until finally found this amazing answer. It worked for me since I needed to pass down the token on the authorization prop.

If your file server supported CORS, you could use fetch and URL.createObjectURL

const token = getUserToken();
const CustomVideo = ({ videoUrl }) => {
    const options = {
        headers: {
            Authorization: `Bearer ${token}`
        }
    }
    const [url, setUrl] = useState()
    useEffect(() => {
        fetch(videoUrl, options)
        .then(response => response.blob())
            .then(blob => {
            setUrl(URL.createObjectURL(blob))
            
        });
    }, [videoUrl])
   
    
    return (
        <ReactPlayer url={url} width="100%"  controls />
    )
}

Check the details here : https://github.com/CookPete/react-player/issues/282

Blarz
  • 294
  • 3
  • 6
  • your answer works once you receive the full blob response. have you find anything to stream the part of the blob data? – Sai kumar Feb 22 '23 at 18:52
  • this doesn't work if you want to stream the video, this is bound to fail or work slow if its a large video file – Ram Jun 05 '23 at 14:23