How to record webcam video in React

You do not need a library to record a webcam in React. Two browser APIs do the work: getUserMedia opens the camera and microphone, and MediaRecorder turns the stream into a video file. Below is a complete, typed component, the format support you can expect in each browser, and the errors you will hit in practice.

Try It Now - Free Webcam Recorder

Ready to record

Click the button below to start

🔒 Your camera feed and recordings never leave your device. All processing happens locally in your browser.

A complete recorder component

'use client'; // needed in the Next.js App Router
import { useEffect, useRef, useState } from 'react';

const TYPES = ['video/mp4', 'video/webm;codecs=vp9,opus', 'video/webm'];

export function WebcamRecorder() {
  const videoRef = useRef<HTMLVideoElement>(null);
  const streamRef = useRef<MediaStream | null>(null);
  const recorderRef = useRef<MediaRecorder | null>(null);
  const chunks = useRef<Blob[]>([]);
  const [recording, setRecording] = useState(false);
  const [url, setUrl] = useState<string | null>(null);

  async function startCamera() {
    const stream = await navigator.mediaDevices.getUserMedia({
      video: { width: { ideal: 1280 }, height: { ideal: 720 } },
      audio: true,
    });
    streamRef.current = stream;
    if (videoRef.current) videoRef.current.srcObject = stream;
  }

  function start() {
    if (!streamRef.current) return;
    const mimeType = TYPES.find((t) => MediaRecorder.isTypeSupported(t));
    const recorder = new MediaRecorder(streamRef.current, mimeType ? { mimeType } : {});
    chunks.current = [];
    recorder.ondataavailable = (e) => {
      if (e.data.size > 0) chunks.current.push(e.data);
    };
    recorder.onstop = () => {
      const blob = new Blob(chunks.current, { type: recorder.mimeType });
      setUrl((old) => {
        if (old) URL.revokeObjectURL(old);
        return URL.createObjectURL(blob);
      });
    };
    recorder.start(1000); // emit a chunk every second
    recorderRef.current = recorder;
    setRecording(true);
  }

  function stop() {
    recorderRef.current?.stop();
    setRecording(false);
  }

  // release the camera when the component unmounts
  useEffect(() => () => streamRef.current?.getTracks().forEach((t) => t.stop()), []);

  return (
    <div>
      <video ref={videoRef} autoPlay muted playsInline />
      <button onClick={startCamera}>Start camera</button>
      <button onClick={recording ? stop : start}>{recording ? 'Stop' : 'Record'}</button>
      {url && <a href={url} download="recording">Download</a>}
    </div>
  );
}

How it works

  • getUserMedia asks for permission and returns a MediaStream. It only works on https:// pages or localhost.
  • The preview <video> is muted to avoid feedback and so autoplay is allowed; playsInline stops iOS Safari from going full screen.
  • MediaRecorder.isTypeSupported picks a format the browser can actually record. The resulting Blob's type tells you whether you got MP4 or WebM.
  • start(1000) delivers data every second, so a crash or tab close loses at most one second.
  • Stopping every track on unmount turns the camera light off – forgetting this is the most common bug.

Format support by browser

BrowserRecords asNotes
Safari (macOS, iOS)MP4 (H.264/AAC)MediaRecorder supported since Safari 14.1
Chrome / EdgeWebM (VP8/VP9 + Opus); MP4 in recent versionsCheck isTypeSupported('video/mp4') at runtime
FirefoxWebM (VP8 + Opus)No MP4 recording

Using the react-webcam package

If you prefer a ready-made preview component, react-webcam renders the <video> element and gives you getScreenshot() for still images. It does not record by itself: pass audio to the component, take webcamRef.current.stream once onUserMedia fires, and feed it to a MediaRecorder exactly as in the component above.

Common errors

  • NotAllowedError: the user (or an OS privacy setting) blocked the camera. Show a message explaining how to allow it in the address bar.
  • NotFoundError: no camera matched the constraints. Use ideal instead of exact values, or enumerate devices with navigator.mediaDevices.enumerateDevices().
  • NotReadableError: another app holds the camera (common on Windows). Ask the user to close Teams or Zoom.
  • navigator.mediaDevices is undefined: the page is served over plain http on a non-localhost address.
  • WebM file has no duration / can't seek: Chrome writes WebM without a duration header. Fix it after recording with a library such as fix-webm-duration, or record MP4 where supported.

Frequently Asked Questions

Do I need a library to record webcam video in React?

No. getUserMedia and MediaRecorder are built into every modern browser. Libraries mainly save you the preview markup and permission handling.

How do I record only video without audio?

Call getUserMedia with audio: false. MediaRecorder will produce a video-only file and the browser will only ask for camera permission.

How do I upload the recording to my server?

Send the Blob with fetch and FormData (formData.append('file', blob, 'recording.webm')). For long recordings, upload the chunks from ondataavailable as they arrive.

Related Topics