Install @cloudflare/stream-react
masterInstall the official Cloudflare Stream React component using yarn:
yarn add @cloudflare/stream-reactrepository·master·Indexed 41 days ago
https://github.com/cloudflare/stream-reactThe official React component library for integrating Cloudflare Stream videos. Version 1.9.3 provides the Stream and StreamEmbed components for declarative video playback management, the useStreamSDK hook for programmatic control via the StreamPlayerApi, and comprehensive props for configuring playback, styling, and event handling.
Install the official Cloudflare Stream React component using yarn:
yarn add @cloudflare/stream-reactImport the Stream component from @cloudflare/stream-react and provide a src prop containing either your video's UID or a signed token.
import { Stream } from "@cloudflare/stream-react";
export const App = () => {
const videoIdOrSignedToken = "YOUR_VIDEO_ID_OR_SIGNED_TOKEN";
return (
<div>
<Stream controls src={videoIdOrSignedToken} />
</div>
);
};To perform imperative actions on the player (like play(), pause(), or seeking), pass a MutableRefObject to the streamRef prop of the Stream component. This provides access to the StreamPlayerApi object.
play(): Returns a Promise<void> that resolves if playback begins successfully.pause(): Pauses the video.addEventListener(event, handler) / removeEventListener(event, handler): Subscribe to player events.currentTime: Returns or sets the current playback time in seconds.volume: Sets volume from 0.0 to 1.0.playbackRate: Indicates the rate at which media is played.src: The video UID or signed token.duration: The length of the media in seconds.buffered / played: TimeRanges objects representing buffered and played segments.videoWidth / videoHeight: Intrinsic dimensions of the video.import { useRef } from 'react';
import { Stream, StreamPlayerApi } from '@cloudflare/stream-react';
function Player() {
const playerRef = useRef<StreamPlayerApi | undefined>(null);
const handlePlay = async () => {
if (playerRef.current) {
await playerRef.current.play();
}
};
return (
<>
<Stream
src="YOUR_VIDEO_ID"
streamRef={playerRef}
/>
<button onClick={handlePlay}>Play via API</button>
</>
);
}The Stream component exposes a wide range of event listeners via props. These allow you to react to playback changes, loading states, and ad events.
onPlay / onPause: Triggered when playback state changes.onEnded: Triggered when playback completes.onTimeUpdate: Triggered when currentTime changes.onSeeking / onSeeked: Triggered during seek operations.onWaiting / onPlaying: Triggered when playback is delayed or resumes.onLoadStart / onLoadedData / onLoadedMetaData: Track the loading lifecycle.onError: Triggered when an error occurs (e.g., invalid token or encoding issues).onProgress: Periodic updates on download progress.If adUrl is provided, you can listen to:
onStreamAdStartonStreamAdEndonStreamAdTimeoutThe StreamProps interface defines the configuration options for the Stream component. Use these props to control playback behavior, appearance, and event handling.
src (required): The video UID or the signed token for the video.customerCode: Use a unique subdomain for the iframe source (e.g., customer-<CODE>.cloudflarestream.com).autoplay: Boolean to start downloading and playing immediately. Note that mobile browsers may require user interaction.controls: Boolean to show/hide default video controls.responsive: Boolean (defaults to true) to automatically manage the aspect ratio of the iframe.startTime: A timestamp to specify when playback begins. Supports plain numbers (seconds) or human-readable strings like 1h12m27s.primaryColor / letterboxColor: CSS color values for the player UI.preload: Hint to the browser via `The Stream component accepts several props to configure the player, styling, and event handling.
src (string): Required. The video UID or the signed token for the video.streamRef (MutableRefObject): A ref for accessing the underlying StreamPlayerApi for imperative control.customerCode (string): Use a unique subdomain for the iframe source (e.g., customer-<CODE>.cloudflarestream.com).responsive (boolean): Automatically manages the aspect ratio of the iframe. Defaults to true.autoplay (boolean): Starts downloading and playing immediately. Note: Mobile browsers often require muted to be set for autoplay to work.controls (boolean): Shows default video controls (play/pause, volume, etc.).currentTime (number): Seeks the video to a new time. Note: Seeking only occurs when a new value is set. For continuous seeking, use streamRef.loop (boolean): Automatically seeks back to the start upon reaching the end.playbackRate (number): The rate at which media is played back.startTime (string | number): Timestamp for when playback begins (e.g., 123 or 1h12m27s).volume (number): Sets volume from 0.0 to 1.0.muted (boolean): Indicates if audio is initially silenced.preload ("auto" | "metadata" | "none" | boolean): Hint to the browser about preloading.defaultTextTrack (string): BCP-47 language code to enable a specific text track during initialization.width (string): Width of the display area in CSS pixels.height (string): Height of the display area in CSS pixels.poster (string): URL for an image to show before playback or during download.primaryColor (string): CSS color applied to player UI elements.letterboxColor (string): CSS color for letterboxing/pillarboxing. Set to transparent to avoid this when not in fullscreen.adUrl (string): URL to a VAST advertising tag.All event listeners expect an EventListener type.
onPlay, onPause, onPlaying, onWaiting, onStalled, onSuspend (Playback state)onEnded, onAbort (Completion/Interruption)onLoadStart, onLoadedData, onLoadedMetaData, onCanPlay, onCanPlayThrough (Loading state)onProgress, onTimeUpdate, onSeeked, onSeeking (Progress/Seeking)onDurationChange, onRateChange, onVolumeChange (Property changes)onError (Error handling)onStreamAdStart, onStreamAdEnd, onStreamAdTimeout (Ad events)The Preload type defines the hint given to the browser regarding how much data to load before playback starts.
"auto": Suggests the browser should preload the video."metadata": Loads only the metadata needed to start playback."none": Suggests no preloading (though the player will still load minimal metadata to initialize).boolean: Can be used as a boolean flag.type Preload = "auto" | "metadata" | "none" | boolean;The useStreamSDK hook provides a safe way to access the Cloudflare Stream SDK within a React component. It handles the asynchronous loading of the SDK script from https://embed.cloudflarestream.com/embed/sdk.latest.js and ensures compatibility with Server-Side Rendering (SSR) by checking for the existence of the window object.
When the hook is called, it checks if the SDK is already present on the window. If not, it dynamically injects the script tag into the document head and updates the state once the script has finished loading.
import { useStreamSDK } from '@cloudflare/stream-react';
function MyVideoComponent() {
const streamSdk = useStreamSDK();
if (!streamSdk) {
return <div>Loading SDK...</div>;
}
// You can now use the streamSdk object
return <div>SDK is ready!</div>;
}The StreamEmbed component accepts several props to customize the player experience.
src: The video UID, signed token, or a valid iframe source URL.autoplay: Boolean. If true, the video starts playing immediately.controls: Boolean. Enables/disables player controls (default: false).muted: Boolean. If true, the video starts muted.loop: Boolean. If true, the video loops.preload: String. Controls how the video is loaded (e.g., "metadata").poster: URL. The image to show while the video is loading.volume: Number. The playback volume (default: 1).playbackRate: Number. The playback speed.startTime: Number. The time in seconds to start playback.currentTime: Number. The current playback time.primaryColor: String. The primary theme color for the player.letterboxColor: String. The color used for letterboxing.defaultTextTrack: Any. Configuration for default text tracks.responsive: Boolean. If true, the player uses a responsive container with a padding-top hack to maintain aspect ratio (default: true).height / width: Dimensions for the iframe.className: CSS class for the container.title: Accessibility title for the iframe.adUrl: URL. The URL for advertisements.customerCode: String. Used for specific customer configurations.The StreamEmbed component exposes a wide range of event callbacks to react to player state changes:
onPlay: Triggered when playback starts.onPause: Triggered when playback is paused.onPlaying: Triggered when the player starts playing after being paused or buffering.onWaiting: Triggered when playback stops due to buffering.onStalled: Triggered when playback is stalled.onSuspend: Triggered when playback is suspended.onEnded: Triggered when the video reaches the end.onLoadStart: Triggered when the load process begins.onLoadedMetaData: Triggered when metadata is loaded.onLoadedData: Triggered when the first frame is loaded.onCanPlay: Triggered when the player can play.onCanPlayThrough: Triggered when the player can play through without buffering.onTimeUpdate: Triggered as the playback position advances.onProgress: Triggered during playback progress.onSeeked: Triggered when seeking is complete.onSeeking: Triggered when seeking starts.onDurationChange: Triggered when the video duration changes.onResize: Triggered when the player size changes.onError: Triggered on playback errors.onAbort: Triggered when playback is aborted.onStreamAdStart: Triggered when an ad starts.onStreamAdEnd: Triggered when an ad ends.onStreamAdTimeout: Triggered when an ad times out.onRateChange: Triggered when the playback rate changes.onVolumeChange: Triggered when the volume changes.The safelyAccessStreamSDK function is a utility that returns the Stream object from the global window scope. It includes a safety check for typeof window === 'undefined' to prevent errors during Server-Side Rendering (SSR) environments where the window object is not available.
import { safelyAccessStreamSDK } from '@cloudflare/stream-react';
// Use this to check for the SDK outside of the hook or in non-React contexts
const sdk = safelyAccessStreamSDK();
if (sdk) {
// sdk is available on the window
}The useStreamSDK hook provides access to the StreamPlayerApi, allowing you to programmatically control the video player (e.g., play, pause, seek) from within your React application.
import { useStreamSDK } from '@cloudflare/stream-react';
const MyPlayerController = () => {
const api = useStreamSDK();
return (
<button onClick={() => api.play()}>Play</button>
);
};