Search code examples
reactjsxmlhttprequestvideo.jsrequest-headers

Passing header parameters while loading Video in VideoJs


I am trying to load a video into VideoJS player in a react project. The Video is returned from a web service taking specific token that authenticate the user.

Let's say the video is returned from the below API call:

localhost:8080/video/1/

In order to play this video, the user should be authenticated. In other words, the API takes the below header to return a successful result:

auth: token

My VideoJs player is built in a React component as below:

import React from 'react'
import videojs from 'video.js'

export default class VideoComponent extends React.Component {

  componentDidMount () {
      this.videoJsOptions = {
        sources: [{
           src: 'http://localhost:8080/video/1/',
          type: 'video/mp4',
        }],
      }
      let player = videojs(this.videoNode, this.videoJsOptions, function onPlayerReady() {
        console.log('onPlayerReady', this)
      })

      this.player = player
  }
  render () {
      return (
            <div data-vjs-player>
              <video ref={node => this.videoNode = node} className="video-js"></video>
            </div>
      )       
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

How is it possible to let my video component take the token of the calling URL and pass it the request header?


Solution

  • I would put this component as a child of another component whose sole responsibility is to make the API call and render the VideoComponent if the user is authorized. Something along these lines.

    You'll probably want some type of redirect or error message feedback to the user if they are not authorized. I did not incorporate that in my code snippet.

    export default class VideoAuth extends React.Component {
        state = {
            isAuthorized: false
        }
    
        async componentDidMount() {
            const authRequest = await someAuthRequest()
            if (authRequest.ok) {// or however the data structure looks like
                this.setState({ isAuthenticated: true })
            }
        }
    
        render() {
            return this.state.isAuthenticated ? <VideoComponent /> : <div> Authorizing... </div>
        }
    }