Reputation: 861
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.
Upvotes: 5
Views: 8809
Reputation: 414
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
Upvotes: 1
Reputation: 3285
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
Upvotes: 7