DEV Community

Cover image for How to display IP camera feed from an RTSP url onto react app page with node js
frank edekobi
frank edekobi

Posted on

How to display IP camera feed from an RTSP url onto react app page with node js

Refactor it however you please, but this should give you the essential building blocks to successfully render the rtsp stream in a react js app from a node js app.
Also make sure the rtsp feed is valid, you can test it using vlc media app.
and make sure you have ffmpeg installed on your computer


On the server

const express = require("express")
const Stream = require("node-rtsp-stream")
const cors = require("cors")

const app = express()
const port = 3002
let stream = null

app.use(
  cors({
    origin: "http://localhost:3000",
    credentials: true,
  })
)

app.get("/stream", (req, res) => {
  const newRtspStreamUrl = req.query.rtsp
  let currentRtspStreamUrl = ""

  // Create the WebSocket stream only if it doesn't exist or the RTSP URL has changed
  if (!stream || currentRtspStreamUrl !== newRtspStreamUrl) {
    if (stream || newRtspStreamUrl === "stop") {
      stream.stop()
    }
    stream = new Stream({
      name: "Camera Stream",
      streamUrl: newRtspStreamUrl,
      wsPort: 9999,
    })
    currentRtspStreamUrl = newRtspStreamUrl
  }

  res.send(200).json({ url: `ws://127.0.0.1:9999` })
})

app.listen(port, () => {
  console.log(`Server running on port ${port}`)
})
Enter fullscreen mode Exit fullscreen mode

On the client

import React from "react"
import JSMpeg from "@cycjimmy/jsmpeg-player"
import axios from "axios"

const StreamPlayer = () => {

useEffect(()=>{
    const url = 'ws://127.0.0.1:9999'
    let canvas = document.getElementById("video-canvas")
    new JSMpeg.Player(url, { canvas: canvas })
},[])

const rtspurl = ""//enter the rtsp url here

const httpRequest = (url) => {
   axios.get(`http://127.0.0.1:3002/stream?rtsp=${url}`)
}

const startRTSPFeed = () => {
   httpRequest(rtspurl)
}

const stopRTSPFeed = () => {
   httpRequest("stop")
}

return(
   <div>
      <div>
        <canvas id="video-canvas"></canvas>
      </div>
      <div>
        <button onClick={startRTSPFeed}>Start RTSP Feed</button>
        <button onClick={stopRTSPFeed}> Stop RTSP Feed</button>
      </div>
   </div>
)}
Enter fullscreen mode Exit fullscreen mode

Do have a lovely day!!

Top comments (0)