Storage & video with React
Audience: React developers who let their users upload files, browse them and watch video that is stored and delivered by plycdn. The package gives you hooks and ready-made components: a resumable upload area, a file browser, links that renew themselves before they expire, an accessible video player, and a small client for your backend's plycdn routes. It needs React 18 or later.
The browser never holds your API key and never chooses an organization. Every call goes to your
backend, which signs the user in, asks your IPlycdnStorageAuthorizer whether they may do this (the
default refuses everything) and adds the key. File bytes go from the browser straight to the bucket's region;
each part is authorised only by a short-lived ticket in its URL: no cookies, no headers. Your backend setup is
in Storage & video with ASP.NET Core; do that first, so the routes the hooks call
exist.
1Install
Install from the plycdn feed. Tell npm once where the @plycdn packages live: put this line in the .npmrc beside your package.json (commit it, so your colleagues and CI need no setup):
@plycdn:registry=https://npm.plycdn.com/
Then install:
npm install @plycdn/react
For use with a plycdn account under the plycdn Terms of Use: https://plycdn.com/terms. The feed has every version from Storage & video 1.22.0 onward; earlier versions stay available as downloads in your dashboard under Developers → SDKs. Step by step: Install the SDKs.
Or download the package from your dashboard: Developers → SDKs, where each language is its own download: pick React. Copy plycdn-react-1.39.0.tgz into your application's vendor directory and install it:
npm install ./vendor/plycdn-react-1.39.0.tgz
That is the whole install. The package installs what it needs automatically from your npm registry or mirror, so make sure yours can serve it. The player loads its streaming code only in browsers that need it; browsers that play the stream natively never download it. Commit the package file and your lockfile, or host the package in your private npm registry so your CI can install it.
2Choose what you import
Import by purpose, from the subpath you need (exports in the package; the root holds only shared types):
| Subpath | What it holds |
|---|---|
@plycdn/react/storage |
PlycdnProvider, PlycdnUpload, PlycdnFileBrowser, PlycdnFileViewer, useFileViewer, PlycdnUploader, useUpload, useObjects, useObject, useSignedUrl, useUnfinishedUploads, createPlycdnClient |
@plycdn/react/video |
PlycdnProvider, PlycdnPlayer, usePlayback, useVideo, PlycdnPlayerCore, createPlycdnClient, and for live streaming LiveBroadcaster and LivePlayer |
Both subpaths export the same PlycdnProvider: one provider serves a page that uses both. Wrap the part of
your application that uses the components:
import { PlycdnProvider } from '@plycdn/react/storage'; // or '@plycdn/react/video'
export function Root() {
return (
<PlycdnProvider config={{ baseUrl: '/api/plycdn/v1' }}>
<App />
</PlycdnProvider>
);
}
baseUrldefaults to/api/plycdn/v1, where the .NET package serves its routes.- Set
credentials: 'include'when your backend is on another origin and uses cookie sign-in. - Pass
fetchto add your own sign-in header, retries or telemetry. - The provider also takes
client(your own client, for tests or to wrap every call),uploader,links,rememberFileNamesandnonce.
If your site sends a Content-Security-Policy, allow the upload hosts with connect-src https://*.upload.plycdn.com. The components add one <style> element: pass nonce to the provider when your
style-src has no 'unsafe-inline', or pass unstyled to each component (it is a prop of the components, not of the provider) and include PLYCDN_CSS in your own stylesheet.
3Upload
import { PlycdnUpload } from '@plycdn/react/storage';
<PlycdnUpload bucketId={bucketId} prefix="week-1/" onStored={() => browser.current?.refresh()} onFailed={log} />
- Drag files onto the area or choose them. Each file's key is
prefix + file.name, or whateverkeyFor(file, prefix)returns. - Each file shows progress, time left, Pause / Resume, Cancel and Retry. Files beyond
parallelFiles(default 2) wait their turn;concurrency(default 3) is the number of parts of one file in flight at once. - Resumable. A dropped connection is retried, and sending waits while the browser is offline. After a reload or a closed tab, the component lists the bucket's unfinished uploads; choosing the same file again continues from the last part that arrived. Sessions stay open for 7 days; after that they are no longer offered, and the browser forgets them.
- Never uploaded twice. A lost or timed-out completion is asked again. A file whose upload already completed returns its stored object instead of being sent (and billed) a second time.
- Keyboard and screen readers. Pause and Resume are one button (
aria-pressed); after Retry, Cancel or Remove, focus moves to the row's next action; progress is a labelledprogressbar; errors arerole="alert"; a polite live region announces what happened. - Retry appears only where it can help. A refusal such as
object_existsorfile_type_not_allowedoffers Remove instead, which also ends the session. - Errors are sentences, not codes.
messages={{ file_type_not_allowed: 'Only videos and PDFs.' }}rewords (or translates) any of them.PLYCDN_MESSAGESlists the defaults by code;onFailedreceives aPlycdnError. - Every word is in
labels(defaults:PLYCDN_UPLOAD_LABELS). Other props:accept,multiple,disabledandwarnOnLeave(asks before the page closes mid-upload). Unmounting pauses uploads rather than ending them, so they stay resumable.
For each unfinished upload the browser keeps only its session id, its expiry and (to list it by name) its key.
On shared computers set rememberFileNames={false} on the component, or on the provider for the whole app. On
sign-out, clear the list:
const { forgetAll } = useUnfinishedUploads(bucketId);
forgetAll(); // every bucket; forgetAll(bucketId) for one. The sessions expire on their own.
To upload into a video library, give the library's id as bucketId and upload under sources/ (see the
Video guide); completing the upload creates the video.
4File browser
import { PlycdnFileBrowser, type PlycdnFileBrowserHandle } from '@plycdn/react/storage';
const browser = useRef<PlycdnFileBrowserHandle>(null);
<PlycdnFileBrowser ref={browser} bucketId={bucketId} onOpen={setOpened} />
- Folders come from
/in keys, with breadcrumbs. Show more pages through the listing (pageSize, default 100). prefixwithonPrefixChangecontrols the folder;defaultPrefixlets the component track it.- Unavailable and damaged files are marked, and a refusal is explained with Try again.
ref.current.refresh()reloads the folder, for example after an upload.onOpenreceives the stored object. Without it, names are shown as text.
A public bucket's object has a url. For a private one, ask your backend for a signed link. The link renews
itself before it expires:
import { useSignedUrl, type PlycdnObject } from '@plycdn/react/storage';
function Clip({ object }: { object: PlycdnObject }) {
const { url, error } = useSignedUrl(object.bucketId, object.key);
if (error) return <p role="alert">{error.message}</p>;
return url ? <video src={url} controls /> : null;
}
5Play video
import { PlycdnPlayer } from '@plycdn/react/video';
<PlycdnPlayer libraryId={libraryId} videoId={videoId} onStatus={status => console.log(status)} />
- Links come from your backend. The player asks your backend (
POST {baseUrl}/signwithbucketId= the library andvideoId) for a playback link; your authorizer decides who may watch (PlycdnOperation.WatchVideo, andGetVideofor the title and status). The video itself streams from*.plycdn.net. Links are renewed at 80 % of their lifetime, and at once if the delivery network refuses one; playback carries on without a reload.ttlSecondssets how long each link lives (your backend's default otherwise). - Resumes where this browser last stopped (
resume={false}turns it off; the position is kept inlocalStorageunderplycdn-position:<videoId>, and nothing breaks where storage is blocked). - While a video is still being prepared (
playable: the lowest quality is ready) the player checks every 15 seconds and, once every quality is ready, reloads at the same position. - Keyboard, while the player has focus: Space or K play/pause, Left/Right 5 seconds, J/L 10 seconds,
Up/Down volume, M mute, C next captions track, F full screen, Home/End, 0 to 9 jump to 0 to 90 %,
<and>slower and faster. Shortcuts are ignored with Ctrl, Cmd or Alt, and while a text field has focus. Every control is a labelled button reachable with Tab; the seek bar is a slider read in words; changes are announced to screen readers; motion is reduced when the system asks. - Quality (Auto first), speed and captions menus; captions are offered when the video has them. Download appears when the library offers downloads. Scrubbing previews show on hover and focus.
onStatusreceives{ status: 'loading' | 'ready' | 'error', error, message }. Error codes:video_not_found,video_not_ready,playback_unsupported(a browser that cannot stream),playback_link_failed(three renewals failed; the player offers Try again), and your backend's own refusals such asforbidden.messagesrewords them like the other components.onProgressreceives{ currentTime, duration, playing, ended, played }about once a second and at once on pause, seek and the end, for every library;playedis the seconds this session has been playing, which the player also saves to plycdn when your server names the viewer (Watch time per viewer). Positions come from the browser and are for convenience (a progress bar of your own, say); for anything you enforce, use thewatchedSecondsplycdn keeps for the viewer (Serial playback).- Serial playback. In a library with serial playback (no skipping ahead) the player handles it by itself: it needs no prop and no code. Your server names the viewer.
- Viewer watermark and logo. When the library shows them, the player draws the viewer's details and your logo over the
video, moves the watermark and puts it back if it is removed or hidden; three times in a minute pauses playback. In a
library that requires the watermark it renews its 10-minute links with the watermark's proof by itself. It needs no prop:
your server names the viewer (Viewer watermark and your logo). While the watermark is
drawn, picture-in-picture and casting are off, and on an iPhone full screen is not available. New
onStatuscodes:watermark_required(an older package somewhere: update the server and browser packages),watermark_proof_invalid,watermark_tamperedandplayback_session_expired; after the first three the player stops and Try again starts over.<LivePlayer>and<PlycdnWatch>draw the logo and a watermark of your fixed text and the date and time, not required. - Other props:
className,unstyledandhasMse(override the detection of Media Source Extensions).
If your site sends a Content-Security-Policy, allow the delivery hosts:
connect-src https://*.plycdn.net; media-src https://*.plycdn.net blob:; img-src https://*.plycdn.net https://watch.plycdn.com; worker-src blob:.
https://watch.plycdn.com is where your player logo comes from.
Your own player
import { usePlayback, useVideo } from '@plycdn/react/video';
function Lecture({ libraryId, videoId }: { libraryId: string; videoId: string }) {
const { data: video } = useVideo(videoId); // title, status; polls while it is being prepared
const { src, poster, error, refresh } = usePlayback(libraryId, videoId, { ttlSeconds: 14400 });
if (error) return <p role="alert">{error.message}</p>;
return <MyPlayer title={video?.title} src={src} poster={poster} onForbidden={refresh} />;
}
usePlayback shares one link per (library, video, ttl) with every component under the provider and renews it
like useSignedUrl: at about 80 % of its life, on wake-up, and when you call refresh() (do that when your
player gets a 403 from the delivery network). src is the stream (an adaptive-streaming playlist whose token your
player must carry on every request, as PlycdnPlayerCore does); nativeSrc is the same stream for native
playback, or undefined. PlycdnPlayerCore is the framework-free engine <PlycdnPlayer> uses (link renewal,
the token on every request, resume and the keyboard map), shared with the Angular package; give it a <video>
element and a getLink function. The Video guide shows a complete example.
For the watermark and logo in a player of your own, give PlycdnPlayerCore an onMark that draws with PlayerMark, and send
watermark: 'drawn' with each link it asks for; the core then checks in with the proof and renews before renewBy:
import { PlayerMark, PlycdnPlayerCore, usePlycdnClient } from '@plycdn/react/video';
let mark: PlayerMark | null = null;
const core = new PlycdnPlayerCore({
media: videoElement, videoId,
getLink: renewal => client.sign({ bucketId: libraryId, videoId, watermark: 'drawn',
...(renewal?.continues && renewal.watermarkProof ? { continues: renewal.continues, watermarkProof: renewal.watermarkProof } : {}) }),
onMark: next => {
if (!next) { mark?.destroy(); mark = null; return; }
mark ??= new PlayerMark({ container: screenElement, onTamper: () => core.noteTamper() });
mark.update(next.watermark, next.logo);
},
});
client is usePlycdnClient(); screenElement is a positioned element the video fills. PlayerMark draws the lines as text,
never as markup, and puts them back when they are removed, hidden or covered by the player's own parts.
Start at a moment
<PlycdnPlayer> takes startSeconds, so a search result can open a library video at the moment that matched; a moment set
while the video is still loading is applied once it is ready, and changing startKey (a click counter, say) goes to the
same moment again. Content Search
results carry source for files from your own buckets and libraries, and librarySource(result) gives the player what it
needs: <PlycdnPlayer {...librarySource(result)} /> (Your own plycdn storage). The player plays
through your storage authorizer (PlycdnOperation.WatchVideo), not through the reader's search permissions: for a
restricted file, check in your authorizer that the reader may see it (the Angular and .NET path applies the reader's
permissions for you).
6File viewer
Show a stored file in place: step by step.
import { PlycdnFileBrowser, PlycdnFileViewer } from '@plycdn/react/storage';
<PlycdnFileBrowser bucketId={bucketId} onOpen={setOpened} />
{opened && <PlycdnFileViewer key={opened.id} object={opened} onStateChange={setState} onError={offer} />}
<PlycdnFileViewer> is in @plycdn/react/storage, inside PlycdnProvider. Props: the file as object (the file browser's
onOpen), objectId, or bucketId with objectKey (and optionally contentType and size); a library video as libraryId
with videoId; or your own file as source (a name, what you know about it, delivery and a getLink function:
{ name: 'handbook.pdf', delivery: 'customer', getLink: () => link() }, with 'plycdn' for a plycdn link). Also ttlSeconds,
hostname, startSeconds, limits, labels, messages, className and style. Callbacks: onStateChange({ mode, renderer, card? })
and onError for a card that is not just "this type isn't shown". Give the viewer a key when you switch between files of your
own that share a name, type and size. A library video plays in <PlycdnPlayer> with its serial playback, watermark and logo.
To draw the file yourself, useFileViewer(source, options) gives { state, more(), openSheet(index), picture(ref), mediaFailed(kind), retry() }.
Everything a file contains is plain text in state; render it as text, never as markup.
For a file found by search, <PlycdnContentFileViewer> is in @plycdn/content-search-react, inside ContentSearchProvider:
<PlycdnContentFileViewer key={picked.assetId} result={picked} terms={results?.terms ?? []} onUnavailable={offerDownload} />
Props: assetId, result or source; location, terms and snippet to open at and mark the match; highlightPdf,
startSeconds, limits, labels, nonce (for the viewer's one <style> element), className and style. Callbacks:
onStateChange and onUnavailable(code). useContentFileViewer(options) is the same without the frame. A library video plays
there as a plain stream, without serial playback, watermark or logo: use <PlycdnPlayer> from @plycdn/react/video for those.
Limits. Defaults per file, loaded into the page: 10 MB of text (200,000 lines), 20 MB of CSV (200,000 rows, 200 columns) and
1,000,000 cells in one view; when the file's host cannot answer partial reads, whole-file limits apply (text 10 MB, CSV
20 MB, Excel 25 MB, Word 50 MB). Past a limit the view ends with The rest of this file isn't shown here. and Download
(label restNotShown), or, for a whole file over its limit, the card Too large to preview here. limits takes a partial
object to change them (textBytes, textLines, csvBytes, csvRows, csvColumns, xlsxBytes, xlsxCells, docxBytes,
chunkBytes, inFlight, cacheBytes and the archive caps). Content search never goes below the largest document the service
indexes.
CSS properties. The viewer reads the same --plycdn-* properties as the other components (--plycdn-accent, --plycdn-text,
--plycdn-muted, --plycdn-surface, --plycdn-border, --plycdn-radius, --plycdn-font-family, --plycdn-focus,
--plycdn-control-height) and adds --plycdn-viewer-height (default 42rem), --plycdn-viewer-background (behind pages and
pictures), --plycdn-card-icon, --plycdn-mark (matched words), --plycdn-highlight (the matched passage) and
--plycdn-mono-font. data-theme="dark" on an ancestor switches to the dark defaults.
Labels. Every word is in labels; the ones worth translating first are the card sentences tooLarge, unreachable,
unreadable, unsupportedHere and noLink, download and tryAgain, and the three that explain a partial view:
restNotShown ("The rest of this file isn't shown here."), loadedPart ("Showing the first {loaded} of {size}") and
pictureNotShown ("Picture not shown here"). The type words (typePdf, typeWord, typeSpreadsheet and the rest) name a file
on its card. ContentLabels carries the same words as optional entries, so a label set written before the viewer still compiles.
What it shows. Video and audio play, images show, PDFs, Word, Excel, CSV and text open in place reading only the part on the
screen, and anything else (PowerPoint, ZIP and other archives) gets a download card. HTML, XML, code and Markdown are shown as
text, never rendered. What each type shows, the
page policy it needs (img-src with blob: for Word pictures, frame-src for the PDF fallback) and
the errors are in the step-by-step guide.
7Go live and watch live
Two components cover live streaming, both in @plycdn/react/video, inside PlycdnProvider. Live inputs themselves are made on your server
(Storage & video with ASP.NET Core); how live streaming works, and the choice between its two delivery modes, is in the
Video guide.
Broadcast from the page
import { LiveBroadcaster } from '@plycdn/react/video';
<LiveBroadcaster liveInputId={stage.liveInputId} quality="hd" sources={['camera', 'microphone']}
onStateChange={state => console.log(state.status, state.message)} />
- No key in the browser. At every start and every reconnect the component asks your backend for a publish token
(
client.publishToken(liveInputId):POST {baseUrl}/live-inputs/{id}/publish-token; yourIPlycdnLiveAuthorizerdecides who may go live, and refuses everyone until you register one). PassgetPublishToken(a function from the live input's id to a promise of{ token, whipUrl, expiresAt }) to ask your own route. - What it shows: a preview, camera and microphone choices, a microphone level you can read as a meter, Share screen where the browser has it, Go live and End broadcast, and the state in words, announced politely to screen readers. Every control is a labelled native control.
- Props:
liveInputId,sources(any ofcamera,microphone,screen; all by default),quality(sd,hddefault,fhd: the picture size and bitrate sent),reconnectWindowSeconds(how long to keep reconnecting after a drop; use your input's setting, default 60),whipUrl(when your token route does not return an address),autoPrepare,labelsandmessages(reword or translate),classNameandunstyled. onStateChangereceives{ status, error, message, … }:statusisidle,preparing,connecting,live,reconnecting,endedorerror. Codes includecamera_denied,microphone_denied,screen_denied,no_camera,no_microphone,device_in_use,broadcast_unsupported,publish_token_invalid,connection_failed,connection_lost(the reconnect window was used up) and your backend's live codes such aslive_input_disabled,live_input_busy,live_cap_reachedandfeature_not_in_plan.- A page that broadcasts must be served over
https://(orlocalhostwhile you build); the visitor is asked for permission, and a refusal is shown as a sentence with Try again.
Watch live
import { LivePlayer } from '@plycdn/react/video';
<LivePlayer libraryId={stage.libraryId} liveInputId={stage.liveInputId} latencyTarget="lowest" showLatency
onStateChange={s => console.log(s.status, s.liveState)} />
- Links come from your backend (
client.signLive({ bucketId, liveInputId, mode, ttlSeconds }):POST {baseUrl}/sign); your authorizer decides who may watch (PlycdnOperation.WatchVideo, andGetVideoforGET {baseUrl}/live-inputs/{id}). Links are renewed before they expire (80 % ofttlSeconds, 15 minutes by default). modeisbroadcastorrealtime; leave it out to follow the input's own delivery mode. A real-time viewer beyond the input's audience cap is given broadcast automatically and the player says "Low-latency playback".latencyTargetislowest(default) orbalanced; a viewer can also choose Lowest delay or Smoother playback.- While the stream is not running the player says Waiting for the stream to start and checks every 5 seconds (
live_not_startedis not an error). It shows Reconnecting when the encoder drops, a LIVE button that returns to the live edge, a quality menu and, withshowLatency, the delay behind live. A stream that has just gone on air in its original quality shows More qualities coming until its other qualities are added (the player takes them up by itself). When the stream ends it plays the recording in the same place (playRecording={false}turns that off). onStateChangereceives{ status: 'loading' | 'ready' | 'error', liveState, error, message }, withliveStatewhat the stream is doing (waiting,live,reconnecting,ended).messagesandlabelsreword it; the other props areclassName,unstyledandhasMse.- For a player of your own:
client.signLive(...)returns the links (url,fallbackUrlorwhepUrl,mode,latency,streamId,expiresAt) and rejects withlive_not_started(retryable) while nothing is streaming;client.getLiveInput(liveInputId)returns the input as a browser may see it (id,state,delivery,stream). - Captions, rewind and ad breaks. A stream with captions gets a captions menu (the languages come from
client.getStreamCaptions(streamId), throughGET {baseUrl}/live-streams/{id}/captions). A stream with a rewind window (dvrWindowSecondsabove 0) gets a seek bar, and the keys of the video player: Space or K, ← and → (5 s), J and L (10 s), Home, End (back to live), ↑ and ↓, M and C. During an ad break the player shows how long is left and holds seeking;onAdEventreceivesadBreakStartandadBreakEnd(breakId,durationSeconds), and withadQuartilesalsoadBreakFirstQuartile,adBreakMidpointandadBreakThirdQuartile. - Protected streams play in browsers that support one of the stream's key systems; others show
playback_unsupported. The recording of a protected stream does not play inPlycdnPlayerin this release: setplayRecording={false}for it (Integration guide). - New refusals worded in the error messages:
live_setting_conflict,live_setting_not_in_planandprotection_not_configured.
If your site sends a Content-Security-Policy, add the live hosts to the delivery ones: connect-src https://*.plycdn.net https://*.live.plycdn.com.
Watch a shared stream
A share link can be watched on your own page with <PlycdnWatch>. It needs no account, no PlycdnProvider and nothing from your backend: it calls plycdn's public watch
routes directly.
import { PlycdnWatch } from '@plycdn/react/video';
<PlycdnWatch code="https://watch.plycdn.com/AbCdEfGhIjKlMnOpQrStUv" onStateChange={s => console.log(s.screen)} />
codeis the link's address or only the code at its end.apiBaseis the plycdn API address (https://api.plycdn.comwhen left out).- A password is asked for in a labelled box when the link has one. A wrong one shows Wrong password, try again; after too many wrong tries it shows Too many tries, try again in N minutes.
- While the stream has not started it shows Starting soon and looks again every 10 seconds. A live stream plays with a Live button and a captions menu when the stream has captions. When the stream ends it shows This stream has ended, then plays the recording if the link shows it. A link that is turned off, expired or deleted shows This link is not available.
- Links are renewed before they expire (after 12 minutes of their 15) without interrupting playback.
- The link's brand is drawn as the link answers it: the logo (at most 32, 48 or 72 pixels high, by the brand's
logoSize:small,mediumorlarge), colours and theme, one of three layouts (cinema,standard,side_panel), the title and description, the three sentences, the button to your site and up to three footer links. Text is shown as typed, never as markup, and onlyhttps://links are used. A link that is not available shows the plain built-in page. What you set inoptionsalways wins over the brand, key by key: setcolors.accentand the brand's accent is ignored, but its other colours stay. The page's logo is served by plycdn, so allow images fromhttps://watch.plycdn.com(and your own watch domain, if the page is served on one) in your Content-Security-Policy. optionsholds every sentence and colour in one object, and a page changes only what it names:{ text: { starting: 'Gleich geht es los' }, colors: { accent: '#7c3aed', background: '#101418' } }. The sentences areloading,starting,ended,notFound,passwordPrompt,passwordLabel,passwordButton,wrongPassword,tooManyTries(with{minutes}),tooManyTriesOne,error,unsupported,retry,live,goToLive,captions,captionsOffandrecording; the colours arebackground,text,muted,surface,accent,accentInk,onAccent,errorandborder.WATCH_OPTIONSholds the defaults. The look can also be set with the custom properties--plycdn-watch-background,--plycdn-watch-accentand so on.onStateChangereceives{ screen, error }, withscreenloading,password,starting,live,recording,ended,notFoundorerror. The other props areclassName,unstyledandnonce.- For a page of your own:
PlycdnWatchCore(from@plycdn/react/video) does everything above for a<video>element you give it.
If your site sends a Content-Security-Policy, add the API with the delivery and live hosts: connect-src https://api.plycdn.com https://*.plycdn.net.
8Hooks
| Hook | Returns |
|---|---|
useObjects(bucketId, { prefix, limit }) |
{ items, loading, error, hasMore, loadMore, reload } |
useObject(objectId) |
{ data, loading, error, reload } |
useUpload() |
{ start(file, { bucketId, key?, contentType?, sha256?, concurrency?, rememberFileNames? }), pause, resume, abort, retry, reset, progress: { sent, total, percent }, state, error, object } |
useSignedUrl(bucketId, key, { ttlSeconds?, hostname? }) |
{ url, expiresAt, loading, error, refresh } |
useUnfinishedUploads(bucketId) |
{ items, forget(item), forgetAll(bucketId?), reload } |
usePlayback(libraryId, videoId, { ttlSeconds? }) |
{ src, nativeSrc, poster, thumbnails, download, expiresAt, loading, error, refresh } |
useVideo(videoId, { pollWhileProcessing?, pollIntervalMs? }) |
{ data, loading, error }; polls every 15 s while the video is uploading, queued, encoding or playable |
useUpload.stateisidle, then one ofstarting,uploading,paused,retrying,offline,completing,stored,failedoraborted;retryingandofflinerecover by themselves.startresolves with the stored object, or withundefinedon failure (readerror) or when anotherstartfrom the same hook replaced it. Progress re-renders about ten times a second, however fast the bytes go.useSignedUrl. It asks your backend'ssignroute for a link. Every component under the same provider showing the same file (bucket, key, ttl, hostname) shares one link and one renewal, which stops when the last of them unmounts.hostnamesigns on one of the bucket's active custom domains; left out it is the bucket's default hostname, and a hostname that is not an active domain of the bucket fails withdomain_not_active. It renews at about 80 % of the link's life, spread by a few percent so links issued together do not all renew at once. The life is the one the server issued (itsDateheader againstexpiresAt), so a wrong clock in the browser changes nothing; if your backend is on another origin, addDateto itsAccess-Control-Expose-Headers, or the life is estimated and kept between 30 seconds and 15 minutes. A link in its last 10 % of life is never returned:urlis undefined andloadingtrue until the new one arrives. A failed renewal keeps the current link, without an error, while it still works;erroris set only when there is no working link to show. A public bucket's link (expiresAt: null) is not renewed.- All hooks ignore an answer that arrives after a newer request, so a slow response never overwrites a fast one, and never show data for a previous id, key or folder.
9Errors
Every failure is a PlycdnError: code is the server's code, or network_unreachable when nothing
answered; status is the HTTP status, or 0; retryable says whether trying again can help; message is a
sentence you can show. invalid_response means a 2xx answer that is not JSON, almost always a baseUrl that
reaches a web page (an HTML fallback) instead of your backend's plycdn routes; it is shown as an error, never
as an empty folder. describeError(error, messages) gives the sentence with your own wording first, and
canRetryUpload(error) says whether a retry can get an upload further.
10Client and uploader
createPlycdnClient({ baseUrl, fetch?, credentials? }) has these methods, all returning promises and each
taking a last { signal } argument to cancel it: listObjects, getObject, startUpload, getUpload,
renewUpload, completeUpload, abortUpload, sign and getVideo. sign(bucketId, key, ttlOrOptions?, { signal }?) takes either the lifetime in seconds or { ttlSeconds?, hostname? } as its third argument and
resolves with { url, expiresAt, lifetimeSeconds? }; sign({ bucketId: libraryId, videoId, ttlSeconds?, refused? })
returns a video's PlaybackLink (url, nativeUrl, expiresAt, posterUrl, thumbnailsUrl,
downloadUrl). Pass refused: true when you ask again because the last link was refused (the player does): your
backend's sign route then refreshes that library's signing settings, and the flag is never sent on to plycdn. The flag is sent
only once your sign route has answered with Plycdn-Sign-Refused: accepted, as the server packages' routes do; a sign route of
your own that passes the request on to plycdn never receives it. An organization can hold at most 1,000 open uploads at once; startUpload beyond that fails
with plan_limit_reached until one completes, is aborted or expires, so abort uploads you no longer need.
PlycdnUploader is the framework-free uploader, shared with the Angular package so both upload identically:
import { PlycdnUploader, createPlycdnClient } from '@plycdn/react/storage';
const client = createPlycdnClient({ baseUrl: '/api/plycdn/v1' });
const uploader = new PlycdnUploader(client); // (api, transport?, store?, { persistNames?: boolean })
const upload = uploader.upload(file, { bucketId, key: 'week-1/intro.mp4', onProgress: (sent, total) => {}, onStateChange: state => {} });
upload.pause(); upload.resume();
const object = await upload.done; // or: await upload.abort();
uploader.pendingUploads(bucketId); await uploader.forget(pending); uploader.forgetAll();
Pass your own uploader to PlycdnProvider to change how parts are sent or where sessions are remembered
(localStorage by default), or your own links (new PlycdnLinks(client, options)) to change the clocks the
signed-link renewal uses.
Tags on links: a sign request can carry an optional tags (names and values as in the ASP.NET Core guide). Your backend decides whether they are used: by default tags a browser sends are ignored, so set them on your server.
11Theme
Everything is a CSS custom property on the component (class plycdn) or any ancestor:
- colours:
--plycdn-accent,--plycdn-on-accent,--plycdn-text,--plycdn-muted,--plycdn-surface,--plycdn-border,--plycdn-error,--plycdn-success,--plycdn-focus,--plycdn-linkand--plycdn-background; - shape and type:
--plycdn-radius,--plycdn-font-family,--plycdn-font-size,--plycdn-line-height,--plycdn-spacing,--plycdn-control-heightand--plycdn-button-padding; - progress:
--plycdn-progress-heightand--plycdn-progress-track; - drop area:
--plycdn-drop-backgroundand--plycdn-drop-active-background; - file viewer:
--plycdn-viewer-height,--plycdn-viewer-background,--plycdn-card-icon,--plycdn-markand--plycdn-highlight(File viewer); - video player:
--plycdn-player-background,--plycdn-player-bar,--plycdn-player-textand--plycdn-player-max-height(default 80vh).
Fonts are inherited. data-theme="dark" on an ancestor, or theme="dark" on the component, switches to the
dark defaults. Every element has a plycdn-* class, and className is added to the root. unstyled leaves
the styling entirely to you. Sizes are shown in binary units: 1 GB is 2^30 bytes, the same GB your bill uses.
12Troubleshooting
- Every call fails with
forbidden. Your backend has noIPlycdnStorageAuthorizer, or it refused that operation. The default refuses everything. invalid_response.baseUrlreaches a web page instead of your backend's plycdn routes.- The player says it cannot play this video. The browser can neither play the stream natively nor load the player's streaming code: check that your Content-Security-Policy allows the delivery hosts and your own scripts.