React quickstart
Play a hosted video in a React app built with Vite, listen to its events, and add the one small server endpoint you need for uploads and private videos. This uses @transcodely/sdk 0.3.28 or later. Using Next.js? Follow the Next.js quickstart instead.
The quick path: for a public or unlisted video, step 1 and step 2 are all you need. Steps 3 and 4 add uploads and private videos.
1. Install
npm install @transcodely/sdkreact and react-dom 18 or 19 are peer dependencies; your app already has them.
2. Play a video
// src/Lesson.tsx
import { TranscodelyPlayer } from "@transcodely/sdk/react";
export function Lesson({ videoId }: { videoId: string }) {
return (
<TranscodelyPlayer
videoId={videoId}
onReady={({ duration }) => console.log(`ready, ${Math.round(duration)} s long`)}
onProgress={({ seconds, percent }) =>
console.log(`at ${Math.round(seconds)} s, played ${Math.round(percent * 100)}%`)
}
onCompleted={({ percent, previously }) => {
if (!previously) console.log(`completed, ${Math.round(percent * 100)}% played`);
}}
onError={({ code }) => console.warn("player error", code)}
/>
);
}Render <Lesson videoId="vid_a1b2c3d4e5f6g7" /> with the id of a ready video from your dashboard. The component renders the hosted player in an iframe and needs no extra script.
Events. onProgress fires about once a second while playing, and on pause, seek and end. Its percent is the share of the video actually played, from 0 to 1: seeking ahead does not add to it. onCompleted fires once per page load when that share reaches the threshold (0.9 by default). The others are onPlay, onPause, onEnded, onSeeked and onTimeUpdate.
To control the player, pass a ref and call play(), pause() or seek(seconds) on it.
3. Keep the API key on a server
Never put your API key or a signing secret in the React app. Vite builds every variable whose name starts with VITE_ into the JavaScript it sends to the browser, where anyone can read it. Keep TRANSCODELY_API_KEY without that prefix and use it only in server code.
Uploads and private videos need a small server with two routes. This one uses only Node.js 20 or later, with no framework:
// server.ts: run with `npx tsx server.ts`
import { createServer } from "node:http";
import { Transcodely, signPlaybackToken } from "@transcodely/sdk";
import { createUploadHandler } from "@transcodely/sdk/upload/server";
const transcodely = new Transcodely({ apiKey: process.env.TRANSCODELY_API_KEY! });
/** Replace with your auth library's session lookup. Until then only local development is let in. */
async function currentUserId(request: Request): Promise<string | null> {
void request;
return process.env.NODE_ENV === "production" ? null : "dev-user";
}
const upload = createUploadHandler({
client: transcodely,
authorize: async (request) => {
const userId = await currentUserId(request);
if (!userId) return { allow: false, status: 401 };
return { allow: true, subject: userId, defaults: { visibility: "private" } };
},
});
async function playbackToken(request: Request): Promise<Response> {
const userId = await currentUserId(request);
if (!userId) return new Response(null, { status: 401 });
const videoId = new URL(request.url).searchParams.get("video") ?? "";
// Check here that this user may watch this video.
const token = signPlaybackToken({
keyId: process.env.TRANSCODELY_PLAYBACK_KEY_ID!,
secret: process.env.TRANSCODELY_PLAYBACK_SECRET!,
videoId,
viewerId: userId,
});
return Response.json({ token }, { headers: { "cache-control": "no-store" } });
}
createServer(async (req, res) => {
const chunks: Uint8Array[] = [];
for await (const chunk of req) chunks.push(chunk as Uint8Array);
const headers = new Headers();
for (const [name, value] of Object.entries(req.headers)) {
if (value !== undefined) headers.set(name, Array.isArray(value) ? value.join(", ") : value);
}
const request = new Request(new URL(req.url ?? "/", "http://localhost:3001"), {
method: req.method,
headers,
body: req.method === "GET" || req.method === "HEAD" ? undefined : Buffer.concat(chunks),
});
const path = new URL(request.url).pathname;
const response =
path === "/api/transcodely/upload" && req.method === "POST" ? await upload(request)
: path === "/api/playback-token" && req.method === "GET" ? await playbackToken(request)
: new Response("Not found", { status: 404 });
res.writeHead(response.status, Object.fromEntries(response.headers));
res.end(Buffer.from(await response.arrayBuffer()));
}).listen(3001);Set TRANSCODELY_API_KEY, TRANSCODELY_UPLOAD_SECRET (at least 32 characters, for example from openssl rand -hex 32), TRANSCODELY_PLAYBACK_KEY_ID (psk_…) and TRANSCODELY_PLAYBACK_SECRET (pss_…) in the server’s environment. Create the signing key on your app’s page in the dashboard; its secret is shown once.
Then let the Vite dev server pass /api to it, so the browser sees one origin and your session cookie reaches the routes:
// vite.config.js
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
export default defineConfig({
plugins: [react()],
server: { proxy: { "/api": "http://localhost:3001" } },
});In production, serve both from one domain the same way.
4. Upload, then play privately
// src/UploadAndPlay.tsx
import { useState } from "react";
import { TranscodelyPlayer, TranscodelyUploader } from "@transcodely/sdk/react";
import "@transcodely/sdk/react/styles.css";
export function UploadAndPlay() {
const [videoId, setVideoId] = useState("");
if (!videoId) {
return <TranscodelyUploader endpoint="/api/transcodely/upload" onSuccess={({ videoId }) => setVideoId(videoId)} />;
}
return <TranscodelyPlayer videoId={videoId} tokenUrl={`/api/playback-token?video=${videoId}`} />;
}The upload starts processing on its own. The player can play once the video is ready; until then, show a message, or have your server wait for the video.ready webhook or call transcodely.videos.waitUntilReady(videoId).
What can go wrong
onErrorreportsload_failed: the token route did not answer200. Check the server is running and the proxy is set.- Uploads answer 401:
currentUserIdreturned nothing. Wire in your real session lookup. - The server stops at startup naming
TRANSCODELY_UPLOAD_SECRET: it is missing or shorter than 32 characters. - The player stays blank on your domain: your app limits Allowed embed domains and this host is not on the list.
Next steps
- Browser Uploads: resuming, the headless hook, every option.
- Protected Playback: tokens, overlays and resolution caps.
- Course Progress: completion, resume and progress per viewer.
- Vue and SvelteKit quickstarts.