> ## Documentation Index
> Fetch the complete documentation index at: https://bunnynet-cb9733c2-stream-player-framework-guides.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Use Bunny Player with React

> Embed the Bunny Stream player in a React app and control playback with player.js events and methods.

The Bunny Player is an iframe. React renders it like any other element, and [player.js](https://github.com/embedly/player.js) gives you a `Player` object for talking to it over `postMessage`. This guide builds a `BunnyPlayer` component that renders the iframe, forwards its events, and hands you that object.

The examples assume a client-rendered app, such as one built with Vite. For server rendering, including Remix and React Router framework mode, follow the [Next.js guide](/stream/player/nextjs).

## Quickstart

<Steps>
  <Step title="Install player.js">
    <CodeGroup>
      ```bash npm theme={null}
      npm install player.js
      ```

      ```bash pnpm theme={null}
      pnpm add player.js
      ```

      ```bash yarn theme={null}
      yarn add player.js
      ```

      ```bash bun theme={null}
      bun add player.js
      ```
    </CodeGroup>

    player.js ships without types. Add a declaration file anywhere your `tsconfig.json` includes, for example `player.js.d.ts`. It covers the methods and events the Bunny Player supports:

    ```ts player.js.d.ts theme={null}
    declare module "player.js" {
      export type PlayerEvent =
        | "ready"
        | "play"
        | "pause"
        | "ended"
        | "timeupdate"
        | "progress"
        | "seeked"
        | "error"
        | "playbackratechange";

      export type TimeUpdate = { seconds: number; duration: number };
      export type Progress = { percent: number; seconds: number; duration: number };
      /** Present when a command fails. Empty when the media itself errors. */
      export type PlayerError = { code: number; msg: string };

      export class Player {
        constructor(iframe: HTMLIFrameElement | string);

        on(event: "ready", callback: () => void): void;
        on(event: "timeupdate", callback: (data: TimeUpdate) => void): void;
        on(event: "progress", callback: (data: Progress) => void): void;
        on(event: "playbackratechange", callback: (rate: number) => void): void;
        on(event: "error", callback: (error?: PlayerError) => void): void;
        on(event: PlayerEvent, callback: (data?: unknown) => void): void;
        off(event: PlayerEvent, callback?: (...args: unknown[]) => void): void;
        supports(kind: "method" | "event", name: string | string[]): boolean;
        /** Send a raw command, for methods player.js does not expose such as setPlaybackRate. */
        send(message: { method: string; value?: unknown }): void;

        play(): void;
        pause(): void;
        mute(): void;
        unmute(): void;
        setVolume(percent: number): void;
        setCurrentTime(seconds: number): void;
        setLoop(loop: boolean): void;

        getPaused(callback: (paused: boolean) => void): void;
        getMuted(callback: (muted: boolean) => void): void;
        getVolume(callback: (percent: number) => void): void;
        getDuration(callback: (seconds: number) => void): void;
        getCurrentTime(callback: (seconds: number) => void): void;
        getLoop(callback: (loop: boolean) => void): void;
      }

      const playerjs: { Player: typeof Player };
      export default playerjs;
    }
    ```
  </Step>

  <Step title="Create the component">
    The component builds the embed URL, renders the iframe, and creates a `Player` once the iframe is in the DOM. Callbacks are read through a ref, so inline props don't re-create the player on every render.

    ```tsx components/bunny-player.tsx theme={null}
    import { useEffect, useRef } from "react";
    import playerjs, { type Player, type TimeUpdate } from "player.js";

    export type BunnyPlayerProps = {
      libraryId: string;
      videoId: string;
      /** Player parameters such as autoplay, muted, captions, or t. */
      params?: Record<string, string | number | boolean>;
      title?: string;
      onReady?: (player: Player) => void;
      onPlay?: () => void;
      onPause?: () => void;
      onEnded?: () => void;
      onTimeUpdate?: (time: TimeUpdate) => void;
    };

    export function BunnyPlayer({
      libraryId,
      videoId,
      params,
      title = "Video player",
      onReady,
      onPlay,
      onPause,
      onEnded,
      onTimeUpdate,
    }: BunnyPlayerProps) {
      const iframeRef = useRef<HTMLIFrameElement>(null);

      // Keep the latest callbacks without re-creating the player.
      const handlers = useRef({ onReady, onPlay, onPause, onEnded, onTimeUpdate });
      useEffect(() => {
        handlers.current = { onReady, onPlay, onPause, onEnded, onTimeUpdate };
      });

      const query = new URLSearchParams(
        Object.entries(params ?? {}).map(([key, value]) => [key, String(value)]),
      ).toString();
      const src = `https://player.mediadelivery.net/embed/${libraryId}/${videoId}${query ? `?${query}` : ""}`;

      useEffect(() => {
        const iframe = iframeRef.current;
        if (!iframe) return;

        // player.js has no teardown API. This flag stops stale listeners
        // from firing after the video changes or the component unmounts.
        let active = true;
        const player = new playerjs.Player(iframe);

        player.on("ready", () => active && handlers.current.onReady?.(player));
        player.on("play", () => active && handlers.current.onPlay?.());
        player.on("pause", () => active && handlers.current.onPause?.());
        player.on("ended", () => active && handlers.current.onEnded?.());
        player.on("timeupdate", (time) => active && handlers.current.onTimeUpdate?.(time));

        return () => {
          active = false;
        };
      }, [src]);

      return (
        <iframe
          ref={iframeRef}
          src={src}
          title={title}
          loading="lazy"
          style={{
            display: "block",
            width: "100%",
            height: "auto",
            aspectRatio: "16 / 9",
            border: 0,
          }}
          allow="autoplay; encrypted-media; picture-in-picture; fullscreen"
          allowFullScreen
        />
      );
    }
    ```
  </Step>

  <Step title="Render a video">
    Pass the library ID and video GUID from the video's page in the dashboard:

    ```tsx theme={null}
    import { BunnyPlayer } from "./components/bunny-player";

    export function Lesson() {
      return (
        <BunnyPlayer
          libraryId="12345"
          videoId="your-video-guid"
          params={{ autoplay: false, preload: true }}
          onEnded={() => console.log("Video finished")}
        />
      );
    }
    ```

    `params` accepts any [player parameter](/stream/embedding#supported-parameters), such as `captions`, `t`, or `muted`.
  </Step>
</Steps>

## Control playback

`onReady` hands you the `Player`. Keep it in state and call its methods from your own controls:

```tsx theme={null}
import { useState } from "react";
import type { Player } from "player.js";
import { BunnyPlayer } from "./components/bunny-player";

export function Lesson() {
  const [player, setPlayer] = useState<Player | null>(null);
  const [playing, setPlaying] = useState(false);

  return (
    <>
      <BunnyPlayer
        libraryId="12345"
        videoId="your-video-guid"
        onReady={setPlayer}
        onPlay={() => setPlaying(true)}
        onPause={() => setPlaying(false)}
      />

      <button onClick={() => (playing ? player?.pause() : player?.play())}>
        {playing ? "Pause" : "Play"}
      </button>
      <button onClick={() => player?.setCurrentTime(0)}>Restart</button>
      <button onClick={() => player?.mute()}>Mute</button>
    </>
  );
}
```

Getters take a callback, because the answer comes back from the iframe:

```tsx theme={null}
player.getCurrentTime((seconds) => console.log(seconds));
player.getDuration((seconds) => console.log(seconds));
```

The `player.js` package on npm has no playback speed method, so send the command directly. The build bunny.net hosts adds `setPlaybackRate()` and `getPlaybackRate()`; see [Methods](/stream/playback-api#methods).

```tsx theme={null}
player.send({ method: "setPlaybackRate", value: 1.5 });
player.on("playbackratechange", (rate) => console.log(rate));
```

Browsers block unmuted `play()` until the viewer has interacted with the page, so call `player.mute()` first if playback has to start without a click. [Playback control API](/stream/playback-api) lists every method and event.

## Track progress

`timeupdate` fires several times a second with `{ seconds, duration }`. Throttle it before writing to your backend:

```tsx theme={null}
import { useRef } from "react";
import { BunnyPlayer } from "./components/bunny-player";

export function Lesson({ videoId }: { videoId: string }) {
  const lastSaved = useRef(0);

  return (
    <BunnyPlayer
      libraryId="12345"
      videoId={videoId}
      onTimeUpdate={({ seconds, duration }) => {
        if (seconds - lastSaved.current < 5) return;
        lastSaved.current = seconds;
        saveProgress(videoId, seconds, duration);
      }}
      onEnded={() => markComplete(videoId)}
    />
  );
}
```

Pass the saved position back as `params={{ t: savedSeconds }}` to resume from there.

## Multiple players on one page

player.js matches the `ready` message to an iframe by its `src`, so two iframes with identical URLs confuse it. Give each one a parameter the player ignores:

```tsx theme={null}
import { useId } from "react";

const id = useId();

<BunnyPlayer libraryId="12345" videoId="your-video-guid" params={{ instance: id }} />
```

## Load player.js from the CDN instead

To skip the npm dependency, load the build bunny.net hosts:

```html index.html theme={null}
<script src="https://assets.mediadelivery.net/playerjs/playerjs-latest.min.js"></script>
```

Put it in `<head>` so it has loaded before your components mount. Replace `import playerjs from "player.js"` with `const playerjs = window.playerjs` and declare the global:

```ts theme={null}
declare global {
  interface Window {
    playerjs: (typeof import("player.js"))["default"];
  }
}
```

## Troubleshooting

<AccordionGroup>
  <Accordion title="onReady never fires">
    The `Player` has to exist before the iframe finishes loading. Creating it in `useEffect` in the render that mounts the iframe is early enough in a client-rendered app. Server-rendered iframe HTML can finish loading before your JavaScript runs; the [Next.js guide](/stream/player/nextjs) handles that case.
  </Accordion>

  <Accordion title="Events fire twice after changing the video">
    Every `Player` adds a `message` listener to `window` that is never removed. The `active` flag in the effect cleanup keeps stale instances quiet, so check that yours flips it.
  </Accordion>

  <Accordion title="The iframe shows a 403">
    The library's allowed domains, direct access block, or token authentication is rejecting the embed. See [Embedding restrictions](/stream/embedding#embedding-restrictions).
  </Accordion>
</AccordionGroup>
