npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

react-webcam-kit

v0.8.0

Published

React webcam, screen recorder, and audio recorder hooks for camera preview, screenshots, recording, device switching, and media cleanup.

Readme

react-webcam-kit

npm version npm downloads CI Bundle size TypeScript License: MIT

react-webcam-kit logo

A modern React webcam toolkit for camera preview, screenshot capture, video recording, device switching, front/back mobile camera flows, and safe getUserMedia cleanup.

react-webcam-kit gives React apps a small, typed API over browser camera behavior. Use the component when you want a ready webcam preview, or the hooks and utilities when you need custom React camera capture, MediaRecorder, avatar upload, or mobile camera switching flows.

Why react-webcam-kit?

Camera packages run in the browser, so every dependency matters. A webcam component should not pull in extra media libraries, hidden utilities, or large client-side code just to call browser APIs that already exist.

react-webcam-kit is built for teams that care about bundle size, predictable installs, and client-side performance:

  • Zero runtime dependencies beyond React - no transitive dependency tree, fewer vulnerability surprises, and no unexpected bundle-size changes from nested packages.
  • Small published browser entry - the current npm release is about 6.2 KB gzip on Bundlephobia, and this repo now enforces size budgets in CI.
  • Hooks-first React API - functional components and hooks only, with no class component layer or polyfill-heavy architecture.
  • Native browser media APIs - wraps getUserMedia, getDisplayMedia, canvas capture, and MediaRecorder directly instead of shipping a recording engine.
  • Typed package exports - ESM, CommonJS, and TypeScript declarations are checked with publint, Are The Types Wrong, and consumer TypeScript tests.

| Package | Runtime dependencies | Browser entry size | Type checks | | ------------------------ | -------------------- | ---------------------------- | ----------- | | react-webcam-kit | React peer only | ~6.2 KB gzip on Bundlephobia | Built in | | Typical webcam wrappers | Varies by package | Recheck per release | Varies | | Recording/helper bundles | Often larger | Recheck per release | Varies |

Bundle benchmarks change over time, so check the live Bundlephobia report before making a final production choice.

Highlights

  • <Webcam /> preview component with imperative capture methods
  • useWebcam() hook for stream lifecycle, permission state, and device switching
  • useCameraPermissions() hook for preflight permission UI
  • useDevices() hook for camera and microphone enumeration, maps, and counts
  • useAudioRecorder() hook for microphone-only recording
  • useDisplayMedia() hook for screen, window, and tab capture
  • useMediaRecorder() hook for typed video recording, duration, max-duration, and Blob output
  • useCameraCapabilities() hook for torch (flashlight), optical zoom, and focus mode
  • useBarcodeScanner() hook for QR and barcode scanning on the native BarcodeDetector
  • useImageCapture() hook for full-resolution stills instead of downscaled preview frames
  • useAudioLevel() hook for volume meters, waveforms, and spectrum displays
  • useFrameProcessor() hook for per-frame work on requestVideoFrameCallback
  • useCompositeStream() hook for screen-plus-webcam picture-in-picture recording
  • useMicrophonePermissions() hook for audio-only permission preflight
  • useObjectUrl() hook for safe Blob previews
  • downloadBlob() helper for recording and screenshot downloads
  • formatDuration() helper for recorder timers
  • blobToFile() and createUploadFormData() helpers for upload-ready camera files
  • createChunkUploader() helper for streaming long recordings to a server as they record
  • Recorder quality presets for low, medium, high, HD, and full-HD capture
  • Recorder cancel(), fileName, fileType, and File output for retry/save flows
  • Recorder and playback MIME support helpers
  • Data URL, Blob, canvas, and ImageData capture utilities
  • Exact deviceId, front/back facingMode switching, and advanced track constraints
  • Predictable stream cleanup on stop, restart, switch, disable, and unmount
  • Typed media errors for permission, device, security, and browser support states
  • ESM, CommonJS, and TypeScript declaration output
  • No required runtime dependency beyond React

Install

npm install react-webcam-kit
pnpm add react-webcam-kit
yarn add react-webcam-kit

Quick Start

import { Webcam } from 'react-webcam-kit';

export function CameraPreview() {
  return (
    <Webcam
      audio={false}
      mirrored
      videoConstraints={{
        width: { ideal: 1280 },
        height: { ideal: 720 },
        facingMode: { ideal: 'user' },
      }}
    />
  );
}

Capture A Screenshot

import { useRef } from 'react';
import { Webcam, type WebcamHandle } from 'react-webcam-kit';

export function AvatarCapture() {
  const webcamRef = useRef<WebcamHandle>(null);

  return (
    <>
      <Webcam ref={webcamRef} audio={false} screenshotFormat="image/jpeg" />
      <button
        type="button"
        onClick={() => {
          const image = webcamRef.current?.getScreenshot({
            width: 512,
            height: 512,
            quality: 0.9,
          });
          console.log(image);
        }}
      >
        Capture
      </button>
    </>
  );
}

Capture A Blob

const blob = await webcamRef.current?.getScreenshotBlob({
  format: 'image/png',
});

if (blob) {
  const file = new File([blob], 'avatar.png', { type: blob.type });
  console.log(file);
}

Record Video

import {
  createUploadFormData,
  downloadBlob,
  formatDuration,
  getRecordingPresetConstraints,
  useAudioRecorder,
  useDisplayMedia,
  useMediaRecorder,
  useObjectUrl,
  useWebcam,
} from 'react-webcam-kit';

export function CameraRecorder() {
  const camera = useWebcam({
    audio: true,
    videoConstraints: getRecordingPresetConstraints('hd'),
  });
  const recorder = useMediaRecorder({
    fileName: 'camera-recording',
    fileType: 'webm',
    maxDuration: 30_000,
    quality: 'hd',
    stream: camera.stream,
  });
  const playbackUrl = useObjectUrl(recorder.blob);

  return (
    <>
      <video ref={camera.videoRef} autoPlay playsInline muted />
      <button type="button" onClick={() => recorder.start()}>
        Record
      </button>
      <button type="button" onClick={recorder.stop}>
        Stop
      </button>
      <button
        type="button"
        disabled={!recorder.file}
        onClick={() => {
          if (recorder.file) {
            downloadBlob(recorder.file);
          }
        }}
      >
        Download
      </button>
      {playbackUrl ? <video src={playbackUrl} controls /> : null}
      <p>{formatDuration(recorder.duration)}</p>
    </>
  );
}

Use videoBitsPerSecond, audioBitsPerSecond, bitsPerSecond, mimeType, and timeslice to tune output size and browser behavior.

Use quality: 'low' | 'medium' | 'high' | 'hd' | 'full-hd' for a preset bitrate target, and pair it with getRecordingPresetConstraints() when you want matching camera constraints.

Use maxDuration, duration, recordingTimeLimitReached, and onMaxDuration for recording time limits and timer UI.

Use cancel() when the user wants to discard a recording and retry without creating a final Blob.

Use muteAudio() and unmuteAudio() to toggle microphone tracks during recording without changing the preview element.

Record The Screen

import { useDisplayMedia, useMediaRecorder, useObjectUrl } from 'react-webcam-kit';

export function ScreenRecorder() {
  const screen = useDisplayMedia({
    audio: true,
    video: true,
  });
  const recorder = useMediaRecorder({
    fileName: 'screen-recording',
    fileType: 'webm',
    quality: 'hd',
    stream: screen.stream,
  });
  const playbackUrl = useObjectUrl(recorder.blob);

  return (
    <>
      <button type="button" onClick={() => void screen.start()}>
        Share screen
      </button>
      <button type="button" disabled={!screen.stream} onClick={() => recorder.start()}>
        Record
      </button>
      <button type="button" onClick={recorder.stop}>
        Stop recording
      </button>
      {playbackUrl ? <video src={playbackUrl} controls /> : null}
    </>
  );
}

useDisplayMedia() returns status, stream, error, isSupported, start(), and stop(). It also reacts when the user stops sharing from the browser UI.

Upload A Screenshot Or Recording

import { createUploadFormData } from 'react-webcam-kit';

const form = createUploadFormData(recorder.file ?? recorder.blob!, {
  fieldName: 'video',
  fileName: 'intro.webm',
  fields: {
    userId,
  },
});

await fetch('/api/upload', {
  method: 'POST',
  body: form,
});

Use the same helper with screenshot Blobs from getScreenshotBlob().

Audio-Only Recording

Use useAudioRecorder() when you want the hook to request the microphone and start recording.

import { useAudioRecorder, useObjectUrl } from 'react-webcam-kit';

export function VoiceNoteRecorder() {
  const recorder = useAudioRecorder({
    fileName: 'voice-note',
    fileType: 'webm',
    quality: 'medium',
  });
  const playbackUrl = useObjectUrl(recorder.blob);

  return (
    <>
      <button type="button" onClick={() => void recorder.start()}>
        Record voice note
      </button>
      <button type="button" onClick={recorder.stop}>
        Stop
      </button>
      {playbackUrl ? <audio src={playbackUrl} controls /> : null}
    </>
  );
}

useAudioRecorder() returns the recorder state plus mediaStatus, mediaError, stream, and stopStream() for microphone lifecycle control.

Build A Custom UI With useWebcam

import { useWebcam } from 'react-webcam-kit';

export function CameraControls() {
  const camera = useWebcam({
    audio: false,
    onError(error) {
      console.error(error.type, error.message);
    },
  });

  return (
    <>
      {/* getVideoProps() supplies the ref plus autoPlay/playsInline/muted, and attaches the
          stream as soon as the element mounts — so it also works when the <video> is rendered
          conditionally, e.g. only once status === 'ready'. */}
      <video {...camera.getVideoProps()} />

      <button type="button" onClick={() => void camera.start()}>
        Start
      </button>
      <button type="button" onClick={camera.stop}>
        Stop
      </button>
      <button
        type="button"
        onClick={() => {
          const image = camera.getScreenshot();
          console.log(image);
        }}
      >
        Capture
      </button>

      <p>Status: {camera.status}</p>
    </>
  );
}

Check Camera Permission

import { useCameraPermissions } from 'react-webcam-kit';

export function PermissionPrompt() {
  const cameraPermission = useCameraPermissions();

  return (
    <button
      type="button"
      disabled={!cameraPermission.canRequest}
      onClick={() => void cameraPermission.requestPermission()}
    >
      {cameraPermission.permission === 'granted' ? 'Camera ready' : 'Enable camera'}
    </button>
  );
}

Switch Cameras

Use useDevices() to list devices, then pass a video input device ID to switchDevice().

import { useDevices, useWebcam } from 'react-webcam-kit';

export function DevicePicker() {
  const devices = useDevices();
  const camera = useWebcam({ audio: false });

  return (
    <select
      value={camera.selectedDeviceId ?? ''}
      onChange={(event) => {
        void camera.switchDevice(event.target.value);
      }}
    >
      <option value="" disabled>
        Select a camera
      </option>
      {devices.videoInputs.map((device) => (
        <option key={device.deviceId} value={device.deviceId}>
          {device.label || 'Camera'}
        </option>
      ))}
    </select>
  );
}

switchDevice() uses an exact deviceId constraint:

{
  video: {
    deviceId: { exact: deviceId },
  },
}

For front/back mobile camera flows, use switchFacingMode():

await camera.switchFacingMode('environment');
await camera.switchFacingMode('user');

Advanced Camera Controls

Browsers expose hardware-specific controls through MediaStreamTrack.applyConstraints(). Use applyVideoConstraints() for capabilities such as torch, zoom, focus distance, or exposure when the device supports them.

const [track] = camera.stream?.getVideoTracks() ?? [];
const capabilities = track?.getCapabilities?.();

if (capabilities && 'torch' in capabilities) {
  await camera.applyVideoConstraints({
    advanced: [{ torch: true } as MediaTrackConstraintSet],
  });
}

Browser Requirements

Camera access requires navigator.mediaDevices.getUserMedia. Browsers only expose it in secure contexts such as HTTPS and localhost.

Mobile devices are sensitive to strict constraints. Prefer ideal values for width, height, and facingMode unless your app can gracefully handle overconstrained errors.

<Webcam
  audio={false}
  videoConstraints={{
    width: { ideal: 1280 },
    height: { ideal: 720 },
    facingMode: { ideal: 'environment' },
  }}
/>

Privacy-focused browsers and extensions may block canvas reads after drawing video frames. In that case screenshot methods return null; show a fallback instead of assuming capture always succeeds.

API Summary

<Webcam />

| Prop | Type | Purpose | | -------------------------------------------- | --------------------------------- | ----------------------------------------------------------- | | audio | boolean | Request microphone tracks when true. Defaults to false. | | audioConstraints | MediaStreamConstraints['audio'] | Custom audio constraints. | | videoConstraints | MediaStreamConstraints['video'] | Custom video constraints. | | enabled | boolean | Start or stop the stream declaratively. | | startOnMount | boolean | Start automatically on mount. Defaults to true. | | mirrored | boolean | Mirror the preview and captured frames. | | muted | native video prop | Mute the preview element without changing stream audio. | | screenshotFormat | ScreenshotFormat | Default screenshot output format. | | screenshotQuality | number | Default screenshot quality for JPEG/WebP. | | forceScreenshotSourceSize | boolean | Capture from the video source dimensions. | | imageSmoothing | boolean | Enable or disable canvas image smoothing. | | minScreenshotWidth / minScreenshotHeight | number | Minimum captured frame size. | | fallback | ReactNode or render function | Rendered for unsupported, denied, or error states. | | onStart / onStop | callbacks | Stream lifecycle events. | | onUserMedia / onUserMediaError | callbacks | Media request events. | | onError | callback | Normalized media error event. | | onPermissionChange | callback | Permission state updates. | | onDevicesChanged | callback | Device list updates. |

The component also accepts ordinary <video> props such as className, style, poster, muted, and disablePictureInPicture.

WebcamHandle

| Method | Purpose | | -------------------------------------- | --------------------------------------------- | | start() | Request a stream. | | stop() | Stop tracks and clear the video element. | | switchDevice(deviceId, constraints?) | Restart with an exact camera device ID. | | switchFacingMode(mode, constraints?) | Restart with an ideal front/back camera mode. | | applyVideoConstraints(constraints) | Apply constraints to the active video track. | | getScreenshot(options?) | Return a Data URL or null. | | getScreenshotBlob(options?) | Return a Blob or null. | | getCanvas(options?) | Return a canvas or null. | | stream | Current MediaStream, if active. | | video | Current HTMLVideoElement, if mounted. |

useWebcam()

useWebcam(options) owns the stream lifecycle and returns status, error, permission, devices, the capture helpers, and start/stop/restart/switchDevice/switchFacingMode.

Attach the preview with getVideoProps() rather than videoRef where you can — it wires the ref, autoPlay, playsInline and muted, and attaches the stream the moment the element mounts:

<video {...camera.getVideoProps({ className: 'preview' })} />

start, stop, restart, switchDevice and switchFacingMode are referentially stable, so they are safe to use in dependency arrays even when you pass inline onError/onUserMedia handlers.

stop() is a durable intent: the stream stays stopped until you call start() again. Toggling the enabled option off and back on resumes whatever state the camera was in.

useMediaRecorder()

useMediaRecorder(options) records an active MediaStream and returns recording state, chunks, the final Blob, duration, max-duration state, and controls for start, stop, pause, resume, and reset.

const recorder = useMediaRecorder({
  stream: camera.stream,
  mimeType: 'video/webm',
  maxDuration: 30_000,
  quality: 'hd',
  videoBitsPerSecond: 1_500_000,
  timeslice: 1000,
});

Recording quality helpers

RECORDING_QUALITY_PRESETS exposes the built-in bitrate and camera-size targets. getRecordingPresetConstraints('hd') returns matching ideal video constraints for useWebcam() or <Webcam />.

getSupportedMimeType()

getSupportedMimeType(candidates?) returns the first MIME type supported by the current browser, or null when MediaRecorder is unavailable.

useWebcam(options) returns stream state, a videoRef, capture methods, device controls, permission state, and normalized errors.

useDevices()

useDevices() returns videoInputs, audioInputs, devicesById, devicesByType, counts, permission, error, and refresh().

useCameraPermissions()

useCameraPermissions(options) returns permission, isSupported, canRequest, error, refresh(), and requestPermission(). requestPermission() probes the camera permission, stops the temporary stream, and resolves to true when permission was granted.

useAudioRecorder()

useAudioRecorder(options) requests a microphone stream, starts useMediaRecorder() with that stream, and stops microphone tracks when recording stops.

useDisplayMedia()

useDisplayMedia(options) requests browser screen, window, or tab capture with navigator.mediaDevices.getDisplayMedia(). Pass the returned stream to useMediaRecorder() to build a React screen recorder.

formatDuration()

formatDuration(duration) formats milliseconds as m:ss for recorder timer UI.

blobToFile() and createUploadFormData()

Use blobToFile(blob, fileName) to turn a screenshot or recording Blob into a named File. Use createUploadFormData(blobOrFile, options) to build a FormData payload for upload endpoints.

captureFrame()

captureFrame(video, options) captures from a ready HTMLVideoElement and can return a Data URL, Blob, canvas, or ImageData.

minWidth and minHeight are floors: they scale a capture up when the source is smaller, and never force a downscale. Pass width/height to pin an exact size.

useCameraCapabilities()

useCameraCapabilities(stream) reads what the active camera can do and controls it.

const camera = useWebcam({ videoConstraints: { facingMode: { ideal: 'environment' } } });
const controls = useCameraCapabilities(camera.stream);

{
  controls.supportsTorch && (
    <button onClick={() => controls.setTorch(!controls.torch)}>
      {controls.torch ? 'Light off' : 'Light on'}
    </button>
  );
}
{
  controls.supportsZoom && (
    <input
      type="range"
      min={controls.capabilities.zoom?.min}
      max={controls.capabilities.zoom?.max}
      step={controls.capabilities.zoom?.step}
      value={controls.zoom ?? 1}
      onChange={(event) => controls.setZoom(Number(event.target.value))}
    />
  );
}

Torch and zoom are hardware dependent. Always branch on supportsTorch/supportsZoom — desktop webcams almost never have either.

useBarcodeScanner()

useBarcodeScanner(videoRef, options) scans the preview for QR codes and barcodes using the browser's built-in BarcodeDetector. No extra dependency and no bundle cost.

const camera = useWebcam({ videoConstraints: { facingMode: { ideal: 'environment' } } });
const scanner = useBarcodeScanner(camera.videoRef, {
  formats: ['qr_code', 'ean_13'],
  onDetected: (code) => setValue(code.rawValue),
});

if (!scanner.isSupported) {
  return <FallbackScanner />; // Safari and Firefox have no BarcodeDetector yet
}

A code that stays in frame reports once rather than on every scan; pass continuous: true for per-frame callbacks, or tune dedupeIntervalMs.

useImageCapture()

useImageCapture(stream, options) takes a still from the camera hardware rather than sampling the preview. On a phone this is often an order of magnitude more pixels than getScreenshot().

const camera = useWebcam();
const photo = useImageCapture(camera.stream, { videoRef: camera.videoRef });

const blob = await photo.takePhoto(); // falls back to a preview frame where unsupported

useAudioLevel()

useAudioLevel(stream, options) reports level (RMS, 0..1) and peak for meters, plus getWaveform() and getFrequencyData() for visualisers. Measurement runs every animation frame, but state updates are throttled to updateInterval (default 100ms); use getLevel() inside your own render loop for the live value.

useFrameProcessor()

useFrameProcessor(videoRef, { onFrame }) runs a callback per decoded frame using requestVideoFrameCallback, falling back to requestAnimationFrame. Frames are dropped rather than queued while an async handler is pending, so slow per-frame work cannot back up.

useCompositeStream()

useCompositeStream({ layers }) draws several streams onto a canvas and mixes their audio into a single recordable stream — a screen share with a webcam bubble, for example.

const screen = useDisplayMedia({ audio: true });
const camera = useWebcam({ audio: true });
const composite = useCompositeStream({
  height: 720,
  width: 1280,
  layers: [
    { audio: true, stream: screen.stream },
    {
      audio: true,
      fit: 'cover',
      height: 180,
      mirrored: true,
      stream: camera.stream,
      width: 320,
      x: 940,
      y: 520,
    },
  ],
});
const recorder = useMediaRecorder({ stream: composite.stream });

useMediaPermissions() and useMicrophonePermissions()

useMediaPermissions({ kind }) preflights 'camera' or 'microphone' access and releases the probe stream immediately, so the indicator light does not stay on during an onboarding screen. useCameraPermissions() and useMicrophonePermissions() are thin wrappers over it.

createChunkUploader()

createChunkUploader(options) uploads recording chunks as they arrive instead of buffering a whole recording in memory.

const uploader = useMemo(() => createChunkUploader({ url: '/api/uploads', uploadId }), [uploadId]);
const recorder = useMediaRecorder({
  timeslice: 5000,
  onDataAvailable: (event) => uploader.enqueue(event.data),
  onStop: () => uploader.complete(),
});

Chunks are sent strictly in order with retry and backoff — a media container cannot be reassembled from out-of-order parts.

More Documentation

Examples

Development

npm install
npm run verify

Available scripts:

  • npm run build - build ESM, CommonJS, and type declarations
  • npm run typecheck - run TypeScript without emitting files
  • npm run lint - run ESLint with zero warnings
  • npm run format:check - verify Prettier formatting
  • npm run test - run Vitest
  • npm run audit - check production and development dependencies for high severity advisories
  • npm run size - enforce the published bundle-size budget
  • npm run verify - run the full release gate

Publishing

Release from a version tag:

git tag v0.7.2
git push origin master --tags

The publish workflow verifies the package, publishes to npm with provenance, and creates the GitHub release. Configure npm trusted publishing for .github/workflows/publish.yml before using the tag flow:

  • Publisher: GitHub Actions
  • Repository owner: modeitsch
  • Repository name: react-webcam-kit
  • Workflow file: publish.yml
  • Environment: leave empty unless you add one to the workflow

See the Release Guide for the full checklist.

Before local dry-runs:

npm run verify
npm pack --dry-run
npm publish --dry-run

License

MIT