Browser Uploads
@transcodely/sdk includes a browser uploader that sends a video straight from your user’s browser to Transcodely’s storage, in parts, with progress, pause, resume, cancel and retry. It comes as a React component (@transcodely/sdk/react), a framework-free uploader for any other app (@transcodely/sdk/upload), and a server route helper (@transcodely/sdk/upload/server).
These imports need @transcodely/sdk 0.3.25 or later, the release that added the /upload, /upload/server and /react subpaths.
How it works
The browser never holds an API key. Your backend does, and the browser talks only to a route of your own:
- You add one
POSTroute to your app built withcreateUploadHandler. It holds a server-side Transcodely client and a requiredauthorizefunction that decides, with your app’s own session, who may upload. - When a user picks a file, the uploader calls your route.
authorizeruns, and the route opens a multipart upload on a new hosted video and returns presigned part URLs plus a signed upload ticket. - The browser
PUTs the parts directly to storage. Every later call to your route (more part URLs, complete, abort) carries the ticket, and your route acts only on the upload that ticket names. A browser cannot choose a video id or upload id, and cannot sign parts for an upload it did not open. - When all parts are in, the route completes the upload and the video starts processing, like any other upload. If the answer to
completeis lost on the way back (a timeout, a dropped connection) and the browser asks again, the route reads the video withvideos.get, sees that it is already pastuploading, and answers with success, so the user is not told that a finished upload failed.
authorize runs on every call, before anything is created or signed. If it refuses, nothing is created. It is required: createUploadHandler throws at startup without it, so an open upload endpoint cannot be deployed by accident.
The route accepts only Content-Type: application/json and answers anything else with 415, so a page on another site cannot post to it without a CORS preflight. Cookies set with SameSite=None still reach it after a preflight, so if your app answers cross-origin requests, check the request’s Origin header in authorize too. Request bodies over 1 MiB are refused with 413 before they are read in full (the largest real body, a complete for 10,000 parts, is about 700 KB).
Tickets are signed with HMAC-SHA256 using a secret that only your server knows. Set it once in your server environment:
# at least 32 characters
export TRANSCODELY_UPLOAD_SECRET=$(openssl rand -hex 32)
export TRANSCODELY_API_KEY={{API_KEY}}createUploadHandler throws at startup if the secret is missing or shorter than 32 characters. You can also pass it as the secret option.
Next.js (App Router)
The route
// app/api/transcodely/upload/route.ts
import { Transcodely } from "@transcodely/sdk";
import { createUploadHandler } from "@transcodely/sdk/upload/server";
import { auth } from "@/auth"; // your app's own session helper
const client = new Transcodely({ apiKey: process.env.TRANSCODELY_API_KEY! });
export const POST = createUploadHandler({
client,
// Runs on every call from the browser, before anything is created or signed.
authorize: async () => {
const session = await auth();
if (!session?.user) return { allow: false, status: 401 };
return {
allow: true,
subject: session.user.id,
defaults: { visibility: "private", tags: [`user:${session.user.id}`] },
};
},
});What authorize returns:
| Return | Effect |
|---|---|
{ allow: false } | The call is refused with 403 and error code forbidden. Add message to choose the text the user sees. |
{ allow: false, status: 401 } | Refused with 401 and code unauthenticated (default text “Sign in to upload.”). |
{ allow: true } | The call goes ahead. |
subject | Who is uploading, usually your user id. Strongly recommended. It is written into the ticket, and every later call must return the same subject, so one signed-in user cannot finish another user’s upload. |
defaults | Fields applied to the new video on create, such as visibility, tags, preset or autoCaptions. They are applied after the browser’s title and description, so they always win. The browser can set only title and description; nothing else it sends reaches the API. |
Set
subject. Without it, a ticket belongs to no one. On a shared browser profile, if user A starts uploading a file and signs out, and user B signs in and picks the same file, B’s browser resumes A’s upload and completes A’s video, created with A’sdefaults. Withsubjectset, B’s calls are refused for A’s ticket and B starts a fresh upload of their own.
authorize receives the Request and a context with the action (create, sign_parts, complete or abort) and, on create, the file the browser wants to upload (name, size, type). When the browser reports no type for a file, type is filled in from its extension (see Limits and behavior).
Other options:
| Option | Default | Notes |
|---|---|---|
client | required | A server-side Transcodely client. The route uses its four multipart upload calls and, optionally, videos.get. A Transcodely client has all of them. If you pass your own object without videos.get, the route still works, but a complete retried after a lost answer fails with the API’s error instead of answering success. |
authorize | required | See above. |
secret | process.env.TRANSCODELY_UPLOAD_SECRET | At least 32 characters. |
maxFileSize | 5 GiB | Largest file accepted, in bytes. It can only lower the 5 GiB ceiling. |
accept | "video/*" | Same syntax as the accept attribute of <input type="file">. A file with no type is judged by its extension. |
ticketTtlSeconds | 86400 (24 hours) | How long one upload can be resumed. Values are held between 60 and 518400 (6 days). |
The handler takes a Web Request and returns a Response, and signs tickets with Web Crypto rather than node:crypto. It needs Node.js 20 or later.
The component
// app/upload/video-upload.tsx
"use client";
import { TranscodelyUploader } from "@transcodely/sdk/react";
import "@transcodely/sdk/react/styles.css"; // optional
export function VideoUpload() {
return (
<TranscodelyUploader
endpoint="/api/transcodely/upload"
accept="video/*"
metadata={{ title: (file) => file.name.replace(/.[^.]+$/, "") }}
onSuccess={({ videoId }) => {
console.log("uploaded", videoId);
}}
onError={(err) => {
console.warn(err.code, err.message);
}}
/>
);
}<TranscodelyUploader> renders a drop zone and file picker, a progress bar with bytes and percent, Pause, Resume, Cancel and Retry buttons for the current state, and a plain-language message when something fails. react and react-dom (18 or 19) are optional peer dependencies of the SDK: they are needed only for @transcodely/sdk/react, and are never bundled into it.
onSuccess receives { videoId, status, resumed }. status is the video’s status after the upload completed, usually processing. Use the video id to show the video, or wait for the video.ready webhook.
Headless: useTranscodelyUpload
The hook gives you the same uploader without any markup:
"use client";
import { useTranscodelyUpload } from "@transcodely/sdk/react";
export function HeadlessUpload() {
const { start, pause, resume, cancel, retry, state, progress, error } = useTranscodelyUpload({
endpoint: "/api/transcodely/upload",
accept: "video/*",
onSuccess: ({ videoId }) => console.log("uploaded", videoId),
});
return (
<div>
<input
type="file"
accept="video/*"
onChange={(e) => {
const file = e.target.files?.[0];
if (file) void start(file);
}}
/>
{state !== "idle" && <progress max={100} value={progress.percent} />}
<p role="status">{state}</p>
{state === "uploading" && <button onClick={pause}>Pause</button>}
{state === "paused" && <button onClick={resume}>Resume</button>}
{(state === "uploading" || state === "paused") && <button onClick={() => void cancel()}>Cancel</button>}
{state === "error" && error?.retryable && <button onClick={() => void retry()}>Retry</button>}
{error && <p role="alert">{error.message}</p>}
</div>
);
}state is one of idle, preparing, uploading, paused, offline, completing, success, error or canceled. progress is { loaded, total, percent }, with percent from 0 to 100, rounded down. It counts bytes still in flight, so it can show 100 just before the last part is confirmed. retry() starts the last file again and keeps the parts that were already uploaded. reset() forgets the current file. An upload still running when the component unmounts is paused, never canceled, so it can be resumed.
Both the component and the hook take every option of createUpload below, except that metadata.title and metadata.description can also be functions of the chosen file.
Other frameworks: @transcodely/sdk/upload
Vue, Svelte, Angular and plain JavaScript apps use the framework-free uploader. It has no dependencies, and importing it during server rendering is safe: it touches window, navigator and IndexedDB only once an upload starts.
import { createUpload, TranscodelyUploadError } from "@transcodely/sdk/upload";
const input = document.querySelector<HTMLInputElement>("#video")!;
const bar = document.querySelector<HTMLProgressElement>("#progress")!;
const status = document.querySelector<HTMLElement>("#status")!;
const pauseButton = document.querySelector<HTMLButtonElement>("#pause")!;
const resumeButton = document.querySelector<HTMLButtonElement>("#resume")!;
const cancelButton = document.querySelector<HTMLButtonElement>("#cancel")!;
input.addEventListener("change", async () => {
const file = input.files?.[0];
if (!file) return;
const upload = createUpload(file, {
endpoint: "/api/transcodely/upload",
accept: "video/*",
metadata: { title: file.name },
onProgress: ({ percent }) => {
bar.value = percent;
},
onStateChange: (state) => {
status.textContent = state; // "uploading", "paused", "offline", ...
},
});
pauseButton.onclick = () => upload.pause();
resumeButton.onclick = () => upload.resume();
cancelButton.onclick = () => void upload.cancel();
try {
const { videoId, resumed } = await upload.start();
status.textContent = resumed ? `Resumed and finished: ${videoId}` : `Uploaded: ${videoId}`;
} catch (err) {
if (err instanceof TranscodelyUploadError && err.code !== "aborted") {
status.textContent = err.message;
}
}
});upload.start() resolves with { videoId, status, resumed } and rejects with a TranscodelyUploadError. upload.state, upload.progress, upload.error and upload.videoId are readable at any time, and upload.subscribe(listener) calls listener on every change (it returns an unsubscribe function), which is what a store in Vue or Svelte needs.
The server side is the same createUploadHandler in any framework with Web-standard handlers. In SvelteKit, for example:
// src/routes/api/transcodely/upload/+server.ts
import { Transcodely } from "@transcodely/sdk";
import { createUploadHandler } from "@transcodely/sdk/upload/server";
declare function getUserId(request: Request): Promise<string | undefined>; // your session lookup
const handler = createUploadHandler({
client: new Transcodely({ apiKey: process.env.TRANSCODELY_API_KEY! }),
authorize: async (request) => {
const userId = await getUserId(request);
return userId ? { allow: true, subject: userId } : { allow: false, status: 401 };
},
});
export const POST = ({ request }: { request: Request }) => handler(request);Uploader options
| Option | Default | Notes |
|---|---|---|
endpoint | required | Your route’s URL, for example /api/transcodely/upload. |
metadata | none | { title, description } for the new video. Your route’s defaults win over these. |
accept | none | Checked in the browser before anything is sent. Your route checks again. |
maxFileSize | 5 GiB | Checked in the browser before anything is sent. Cannot be raised above 5 GiB. |
headers | none | Extra headers for calls to your route (never sent to storage), or a function that returns them, for example a CSRF token. |
credentials | "same-origin" | Passed to fetch for calls to your route. |
concurrency | 3 | Parts uploaded at once, between 1 and 6. |
retries | 5 | Retries per part and per call to your route, after a network error, 5xx, 408 or 429. The first call, create, is never retried, except that one which failed while the browser was offline is sent again once it is back online: it opens a new video, and retrying it after a lost answer could open a second one. Time spent paused or offline does not use up retries. |
retryDelayMs | 1000 | First backoff step. It doubles on each retry, with jitter, up to 30 seconds. |
store | indexedDBStore() | Where unfinished uploads are remembered. false turns resuming off. memoryStore() remembers for the life of the page only. |
fetch | global fetch | Used for calls to your route. Parts are sent with XMLHttpRequest, which reports byte progress, and with this fetch where XMLHttpRequest does not exist. |
onProgress | none | Called with { loaded, total, percent }. |
onStateChange | none | Called with the new state. |
Resuming an upload
Every part that reaches storage is recorded in the browser straight away. If the upload stops (the tab is closed, the page reloads, the connection drops, the user pauses), it continues from the parts already uploaded instead of starting again. What that means in practice:
- The record lives in this browser only, in IndexedDB. Transcodely does not keep a list of the parts it has received for an unfinished upload, so the browser’s record is what a resume is built on.
- After a reload, the user picks the same file again (in the component, the hook or
createUpload) and the upload continues with only the missing parts. A file is recognized by its name, size and last-modified time, plus a SHA-256 of its first and last 64 KiB where the browser has Web Crypto, and by the endpoint. A file that has changed is uploaded again from the start. - Another device, another browser profile, or cleared site data starts again from zero. So does private browsing where IndexedDB is not available: the upload still works, but it can be resumed only while the page stays open.
- A record expires with its ticket: after 24 hours by default, configurable on your route with
ticketTtlSecondsup to 6 days. The uploader treats a record as gone 10 minutes before its ticket expires and starts a fresh upload. The 6-day ceiling exists because the storage bucket is configured to discard unfinished uploads after 7 days, so a resume record lasts at most 6 days. If your route rejects the ticket of a resumed upload (it expired, or the secret changed), the uploader starts again from zero, once, without any action from you. - A restart leaves the earlier attempt behind. When the uploader starts fresh because a record expired or its ticket was refused, it cannot abort the earlier multipart upload (it no longer has a valid ticket for it). That earlier video is left in
uploading. - A paused upload keeps its record; a canceled upload is aborted on the server and its record is deleted; a finished upload deletes its record.
This is not the tus protocol and is not compatible with tus clients or servers. It is a small JSON protocol between @transcodely/sdk/upload and createUploadHandler.
Limits and behavior
- 5 GiB per file. This is the API’s ceiling for an upload. Your app’s own maximum upload size (
max_upload_size_bytesin its hosting settings) also applies: a larger file is refused when the upload is created, with the API’s error codemax_upload_size_exceeded. - Part size is chosen for you, by your route, and sent to the browser: 16 MiB parts, with only the last part shorter. It is not an option.
- Three parts at a time by default (
concurrency, 1 to 6). - Retries. A failed part, or a failed call to your route caused by the network, a
5xx,408or429, is retried up to 5 times with exponential backoff. The exception iscreate, which opens a new video: it is not retried, not even after a429, so that a lost answer does not open a second video. The only time it is sent again is when it failed while the browser was offline, once the browser is back online. If it fails, the upload ends inerrorand the user can retry. A part URL that has expired is signed again before the retry. Other4xxanswers from your route are not retried. - Stalled connections. A part whose upload reports no progress for 60 seconds is abandoned and retried, so a connection that hangs without erroring does not freeze the upload. Where parts go through
fetchinstead ofXMLHttpRequest, the deadline is 60 seconds plus the time the part would take at 8 KB/s. - Offline. When the browser reports that it went offline, uploading stops and the state becomes
offline; it continues by itself when the browser is back online. This covers calls to your route (create, part URLs,complete) as well as the parts: a call that fails while the browser is offline waits for the connection instead of using up its retries. - Pause stops the parts in flight and holds back calls to your route until you resume. The bytes of a part that was in flight are sent again on resume, so progress can step back a little; parts already in storage are kept.
- Cancel stops the upload and aborts it on the server. Once the final
completecall has been sent, cancel cannot undo it. - File types. Some browsers report no type for some video files (Chrome on Windows, for some
.mkvand.m2tsfiles). Such a file is judged by its extension, in the browser and on your route, and your route tells the API the type that extension implies:.mp4,.m4v,.mov,.mkv,.webm,.avi,.wmv,.flv,.mpg,.mpeg,.ts,.m2ts,.mts,.3gpand.ogvare recognized.videoTypeFor(name)from@transcodely/sdk/uploadreturns that type. - Storage. Transcodely’s storage already accepts browser uploads and exposes each part’s
ETag, so there is nothing to configure on your side.
Errors
Every failure is a TranscodelyUploadError with a code, a message written to be shown to the person uploading, an HTTP status when there was a response, and retryable, which says whether trying again can succeed without changing anything.
err.code | When | What to show |
|---|---|---|
file_empty | The file has no bytes. | Ask for another file. |
file_too_large | Above your maxFileSize, your route’s maxFileSize, or 5 GiB. | The limit, and ask for a smaller file. When your route refused it, err.message states the route’s own limit; the component shows that message. |
file_type_not_accepted | The file does not match accept, in the browser or on your route. | Which kinds of file are accepted. |
unauthenticated | Your authorize returned status: 401, or something in front of your route answered 401 without a JSON error. A 401 from the Transcodely API is never passed on as this code (see internal_error). | Ask the user to sign in, then retry. |
forbidden | Your authorize refused the call. | The message your authorize returned. |
network | Your route or storage could not be reached after every retry. | Ask the user to check their connection and retry. |
storage_error | Storage refused a part, or did not return its ETag. | Ask the user to retry. |
upload_expired | The ticket expired. A resumed upload restarts by itself; this reaches you only for a fresh upload. | Ask the user to start the upload again. |
ticket_invalid | The ticket was not signed by your route, or belongs to another subject. | Ask the user to start the upload again. |
bad_response | Your endpoint did not answer the way createUploadHandler does. | A generic failure; check that endpoint points at your route. |
aborted | The upload was canceled. start() rejects with it; the hook and component do not call onError for it. | Nothing. |
unexpected | Anything else that was thrown. | A generic failure. |
invalid_request | Sent by your route: a malformed body (400), or a Content-Type other than application/json (415). | A generic failure. |
payload_too_large | Sent by your route: the request body was over 1 MiB (413). | A generic failure. |
method_not_allowed | Sent by your route: a method other than POST (405). | A generic failure. |
internal_error | Sent by your route: an error inside the route, or the Transcodely API refusing your server’s own API key or app (an API 401 or 403). Its details are never sent to the browser. | A generic failure, and check your server’s logs and API key. |
| Any other code | A Transcodely API error passed through by your route, for example max_upload_size_exceeded. | err.message, the API’s own explanation. |
Accessibility and styling
<TranscodelyUploader> is built on native elements, so it works with a keyboard and a screen reader without extra setup:
- The drop zone is a
<label>around a visually hidden<input type="file">, so it can be focused with Tab and opened with the keyboard. - Progress is a
<progress>element whosearia-valuetextreads like “12.3 MB of 100 MB (12%)“. - A
role="status"live region announces each state change and every 10% of progress, not every byte. Errors are shown in arole="alert"element. - Keyboard focus is kept when the focused control changes: when Pause becomes Resume, when Retry or Cancel disappears, or when the file input is disabled during an upload, focus moves to the control that took its place, or to the drop zone.
- The
messagesprop replaces any piece of text the component shows, for translation or your own wording;defaultMessagesis exported as a starting point.
It is unstyled by default and carries stable attributes to style against:
| Attribute | On |
|---|---|
data-transcodely-uploader, data-state="<state>" | The root element. |
data-part="dropzone", plus data-dragging and data-disabled when they apply | The drop zone. |
data-part="input", "progress", "status", "error" | The file input, progress bar, status line and error text. |
data-part="pause", "resume", "cancel", "retry" | The buttons. |
import "@transcodely/sdk/react/styles.css" adds a small optional stylesheet keyed only on those attributes, with a dark-mode variant. Theme it by overriding its custom properties on [data-transcodely-uploader]: --tu-accent, --tu-border, --tu-muted, --tu-danger and --tu-radius. It uses no CSS framework. Pass className to add your own class to the root.
Where to go next
- TypeScript SDK: the server-side client the route uses.
- Videos: what happens to an uploaded video, and its statuses.
- Webhook Integration: know when the uploaded video is ready.