npm packages
Packages that put the player in an app you build yourself, in plain TypeScript or JavaScript, React or Vue.
| Package | What it gives you | Needs |
|---|---|---|
@spinemedia/player |
create(), the <spine-player> element, and the types |
any bundler, or none |
@spinemedia/player-react |
a <SpinePlayer> React component |
React 18 or later |
@spinemedia/player-vue |
a <SpinePlayer> Vue component |
Vue 3.5.2 or later |
They run the same player as the hosted script and the iframe, with the same controls, behavior and settings. The difference: the video engine is bundled inside, so a player update reaches your viewers only when you upgrade the package and release your app. The hosted script and the iframe always run Spine’s current release.
Site setup
The same as for the hosted script: Spine registers your site as a script site with the origins of your pages, and the player licence covers your domains. Your pages have to send their origin as the referrer, and the hosted script’s Content Security Policy applies.
Install
npm install @spinemedia/player
# or, for a React app
npm install @spinemedia/player-react
# or, for a Vue app
npm install @spinemedia/player-vue
pnpm add and yarn add work the same way. The React and Vue packages bring @spinemedia/player with them.
Add the player
Every player takes host, the Spine host it plays from: https://player.spinectrl.com in production. Keep it in your app’s configuration, such as an environment variable, rather than in each component. Leave out channel to play your site’s default channel.
import { create } from "@spinemedia/player";
const player = create("player", {
host: "https://player.spinectrl.com",
embedId: "01jdm8q3vz5k7r2x9c4n6b8t0w",
channel: "spor-1", // optional: without it, the site's default channel plays
onState: ({ status, problem }) => console.log(status, problem),
});
await player.ready; // the player's code has loaded (or failed to; check player.state())
// Later:
player.destroy();create(container, options) takes an element or an element’s id, and the options in the player reference. host and embedId are required. channel names the channel by its slug or ID; channelId, its older name, still works. channelSelector: true asks for the channel selector. It returns the player, with destroy, state, ready and the commands, as the hosted script’s does.
import { SpinePlayer } from "@spinemedia/player-react";
export function RaceStream() {
return (
<SpinePlayer
host="https://player.spinectrl.com"
embedId="01jdm8q3vz5k7r2x9c4n6b8t0w"
channel="spor-1"
channelSelector
/>
);
}Props: every option, as camel-case props (embedId, channelSelector, livePause, maxQuality), plus className and style for the block the player sits in. onState is called on every change of state. Leave out channel to play your site’s default channel.
- Changing a prop other than
onState,getGrant,classNameorstylestarts the player over with the new settings. Changingchannelis how your page switches channels. A viewer’s pick in the channel selector switches in place and doesn’t change your props. - Unmounting stops the player and releases everything it held.
- Strict mode, which mounts components twice in development, still ends up with one player.
Commands: a ref holds the player’s commands, for whichever player the component holds now.
import { SpinePlayer, type PlayerCommands } from "@spinemedia/player-react";
import { useRef } from "react";
export function RaceStream() {
const player = useRef<PlayerCommands>(null);
return (
<>
<button onClick={() => player.current?.setChannel("spor-2")}>Spor 2</button>
<button onClick={() => player.current?.requestPictureInPicture()}>Picture-in-picture</button>
<SpinePlayer
ref={player}
host="https://player.spinectrl.com"
embedId="01jdm8q3vz5k7r2x9c4n6b8t0w"
channel="spor-1"
/>
</>
);
}Reacting to the player’s state:
import { SpinePlayer, type PlayerStateInfo } from "@spinemedia/player-react";
import { useState } from "react";
export function LiveSection({ channel }: { channel?: string }) {
const [state, setState] = useState<PlayerStateInfo | null>(null);
return (
<section>
<h2>Live {state?.status === "offAir" && <small>(off air)</small>}</h2>
<SpinePlayer
host={import.meta.env.VITE_SPINE_PLAYER_HOST}
embedId={import.meta.env.VITE_SPINE_EMBED_ID}
channel={channel}
onState={setState}
/>
</section>
);
}The component uses React hooks, so in the App Router it belongs in a client component. Make a small wrapper and use it from any page, server components included:
// app/components/live-player.tsx
"use client";
import { SpinePlayer } from "@spinemedia/player-react";
export function LivePlayer({ channel }: { channel?: string }) {
return (
<SpinePlayer
host={process.env.NEXT_PUBLIC_SPINE_PLAYER_HOST!}
embedId={process.env.NEXT_PUBLIC_SPINE_EMBED_ID!}
channel={channel}
/>
);
}// app/live/[channel]/page.tsx
import { LivePlayer } from "../../components/live-player";
export default async function Page({ params }: { params: Promise<{ channel: string }> }) {
const { channel } = await params;
return <LivePlayer channel={channel} />;
}The server renders an empty block and the player starts in the browser, so no dynamic(…, { ssr: false }) is needed. In the Pages Router, use SpinePlayer directly.
<script setup lang="ts">
import { SpinePlayer, type PlayerStateInfo } from "@spinemedia/player-vue";
function onState(state: PlayerStateInfo) {
console.log(state.status, state.problem);
}
</script>
<template>
<SpinePlayer
host="https://player.spinectrl.com"
embed-id="01jdm8q3vz5k7r2x9c4n6b8t0w"
channel="spor-1"
channel-selector
latency="low"
@state="onState"
/>
</template>Props: every option, in kebab case in templates (embed-id, channel-selector, live-pause, max-quality) or camel case in render functions. Pass numbers and booleans with a binding: :max-quality="720", :fill="true", :data-saver="false". A boolean prop written on its own, such as channel-selector, is true. Leave out channel to play your site’s default channel.
Events: state, with { status, problem, muted, pictureInPicture }, on every change.
Commands: a template ref holds the player’s commands: player.value?.setChannel("spor-2"), with const player = ref<PlayerCommands | null>(null) and ref="player" on the component.
As in React, changing a prop other than get-grant starts the player over, and unmounting stops it. A viewer’s pick in the channel selector switches in place and doesn’t change your props.
The component renders an empty block on the server and starts in the browser, so it works in Nuxt pages as it is:
<!-- pages/live/[channel].vue -->
<script setup lang="ts">
import { SpinePlayer } from "@spinemedia/player-vue";
const route = useRoute();
const config = useRuntimeConfig();
</script>
<template>
<SpinePlayer
:host="config.public.spinePlayerHost"
:embed-id="config.public.spineEmbedId"
:channel="String(route.params.channel)"
/>
</template>Create the player once the view exists, and destroy it with the component:
import { AfterViewInit, Component, ElementRef, Input, OnDestroy, ViewChild } from "@angular/core";
import { create, type SpinePlayer } from "@spinemedia/player";
@Component({
selector: "app-live-player",
standalone: true,
template: `<div #container></div>`,
})
export class LivePlayerComponent implements AfterViewInit, OnDestroy {
/** The channel's slug or ID. Left out, the site's default channel plays. */
@Input() channel?: string;
@ViewChild("container") container!: ElementRef<HTMLDivElement>;
private player?: SpinePlayer;
ngAfterViewInit(): void {
this.player = create(this.container.nativeElement, {
host: "https://player.spinectrl.com",
embedId: "01jdm8q3vz5k7r2x9c4n6b8t0w",
channel: this.channel,
});
}
ngOnDestroy(): void {
this.player?.destroy();
}
}With Angular Universal or SSR, ngAfterViewInit also runs on the server. Guard the create call with isPlatformBrowser, or use afterNextRender.
<script lang="ts">
import { onMount } from "svelte";
import { create } from "@spinemedia/player";
/** The channel's slug or ID. Left out, the site's default channel plays. */
export let channel: string | undefined = undefined;
let container: HTMLDivElement;
onMount(() => {
const player = create(container, {
host: "https://player.spinectrl.com",
embedId: "01jdm8q3vz5k7r2x9c4n6b8t0w",
channel,
});
return () => player.destroy();
});
</script>
<div bind:this={container}></div>onMount doesn’t run during server rendering, so this is safe in SvelteKit. To switch channels from your page, wrap the component in {#key channel}.
Protected playback
Only for a site on customer grants. On any other site, you have nothing to add.
Hand the player each viewer's grant
On a site with customer grants (see Security and access), give the player a getGrant function that gets each viewer’s grant from your backend (see Your endpoint for the player):
import { create, type GrantRequest } from "@spinemedia/player";
async function getGrant({ channel }: GrantRequest): Promise<string | null> {
const response = await fetch("/api/spine/grant", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ channel }),
});
return response.ok ? ((await response.json()) as { grant: string }).grant : null;
}
create("player", {
host: "https://player.spinectrl.com",
embedId: "01jdm8q3vz5k7r2x9c4n6b8t0w",
channel: "spor-1",
getGrant,
});With the custom element, set its getGrant property at any time, before or after defineElement() runs, as with the hosted script.
import { SpinePlayer, type GrantRequest } from "@spinemedia/player-react";
async function getGrant({ channel }: GrantRequest): Promise<string | null> {
const response = await fetch("/api/spine/grant", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ channel }),
});
return response.ok ? ((await response.json()) as { grant: string }).grant : null;
}
export function RaceStream() {
return (
<SpinePlayer
host="https://player.spinectrl.com"
embedId="01jdm8q3vz5k7r2x9c4n6b8t0w"
channel="spor-1"
getGrant={getGrant}
/>
);
}The player calls the latest getGrant you passed, so a new function on each render doesn’t start it over.
<script setup lang="ts">
import { SpinePlayer, type GrantRequest } from "@spinemedia/player-vue";
async function getGrant({ channel }: GrantRequest): Promise<string | null> {
const response = await fetch("/api/spine/grant", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ channel }),
});
return response.ok ? ((await response.json()) as { grant: string }).grant : null;
}
</script>
<template>
<SpinePlayer
host="https://player.spinectrl.com"
embed-id="01jdm8q3vz5k7r2x9c4n6b8t0w"
channel="spor-1"
:get-grant="getGrant"
/>
</template>Changing get-grant doesn’t start the player over: the player reads it each time it needs a grant.
getGrantgets{ embedId, channel, reason }: your site’s embed ID in full, withemb_; the slug of the channel the player plays, even when the embed names it by ID or names none, which your backend needs only to limit a grant to one channel; andreason,"start"or"renew". It returns a promise of the grant, or ofnullwhen the viewer may not watch. A promise that rejects counts asnull.- It’s called when the player starts, about every four minutes while it plays, when a viewer switches channel, and when the player has to restart the stream. Answer within a few seconds.
- For a page that frames the embed in an
<iframe>instead,serveGrants(iframe, getGrant)answers the iframe’s grant requests and returns a function that stops answering (see Iframe embed).
Without a grant, the player plays nothing, reports the state denied with the problem protected, and shows “Your access to this stream couldn’t be confirmed”. It asks again about a minute later.
On iPhones and iPads before iOS 17.1, Safari plays the stream itself, and the player in your own page can’t renew a protected stream’s credentials mid-stream there. Playback pauses and resumes by itself every few minutes. The iframe embed renews them without a pause, so it’s the better choice for protected playback on those devices.
Good to know
Bundle size
Importing a package adds about 3 KB compressed to your bundle. The player itself, about 720 KB compressed and nearly all of it the video engine, is a separate chunk that your bundler splits off and loads only when the first player is created. So the import costs nothing on pages that don’t show a player.
Server-side rendering
Importing any of the packages is safe on the server: they touch no browser global until you create a player. Create players only in the browser. The React and Vue components already do this. They render an empty block on the server and start the player once mounted.
The custom element
import { defineElement } from "@spinemedia/player";
defineElement(); // defines <spine-player>; pass another tag name if that one is taken<spine-player
host="https://player.spinectrl.com"
embed-id="01jdm8q3vz5k7r2x9c4n6b8t0w"
channel="spor-1"
></spine-player>It takes the attributes and fires the events of the hosted script’s element. Here host is required.
What the package exports
| Export | What it is |
|---|---|
create |
Makes a player in a container and starts it. |
defineElement |
Defines the <spine-player> element, under another tag if you pass one. A second call does nothing. |
serveGrants |
Answers an embed iframe’s grant requests, on a site with customer grants. See Protected playback. |
version |
The package’s version, as the player reports it in its diagnostics. |
| Types | PlayerOptions, PlayerStateInfo, PlayerStatus, Problem, PlayerCommands, LatencyMode, LivePauseMode, Language, GrantRequest, GrantProvider, SpinePlayer, SpinePlayerElement, Create, DefineElement, ServeGrants. |
Serving the worker files yourself
The video engine loads a few worker files at run time. By default they come from the player host, at a path that matches the bundled engine’s version, so you don’t need to do anything.
If your app has to serve them itself, copy the package’s dist/theoplayer/ folder to your static files, and pass its URL, ending in /, as libraryLocation:
cp -r node_modules/@spinemedia/player/dist/theoplayer public/spine-theoplayerimport { create } from "@spinemedia/player";
create("player", {
host: "https://player.spinectrl.com",
embedId: "01jdm8q3vz5k7r2x9c4n6b8t0w",
channel: "spor-1",
libraryLocation: "/spine-theoplayer/",
});Versions and upgrades
The packages follow semantic versioning. A minor or patch release doesn’t break your code; a major release may, and its notes say what changes. Upgrade regularly: fixes for new browser versions reach your viewers only when you ship them.
version, exported by @spinemedia/player, is the version your app runs. Include it when you report a problem.