Skip to content
Next.js

Next.js quickstart

Upload a video from your Next.js app, play it privately with TranscodelyPlayer, and hear about it on your server when it is ready. This uses the App Router and @transcodely/sdk 0.3.28 or later.

The quick path: install the SDK, set five environment variables, and add three route handlers and two pages. Your API key and signing secrets stay on the server; the browser talks only to routes of your own.

1. Install and configure

npm install @transcodely/sdk

Put these in .env.local (never in a variable whose name starts with NEXT_PUBLIC_, which Next.js sends to the browser):

TRANSCODELY_API_KEY=ak_your_api_key
# Signs upload tickets: at least 32 characters, for example from `openssl rand -hex 32`
TRANSCODELY_UPLOAD_SECRET=
# A playback signing key: dashboard > your app > Playback signing keys
TRANSCODELY_PLAYBACK_KEY_ID=psk_...
TRANSCODELY_PLAYBACK_SECRET=pss_...
# The webhook endpoint's secret, from step 6
TRANSCODELY_WEBHOOK_SECRET=whsec_...

The signing key’s secret (pss_…) is shown once, when you create the key. Create the API key under API keys in the dashboard.

2. The upload route

createUploadHandler opens the upload on your server, hands the browser presigned URLs, and refuses anyone authorize turns away. The file goes from the browser straight to storage; it never passes through your server. The Browser Uploads guide has every option.

The routes below read the signed-in user with auth() from @/auth, as Auth.js sets it up. Use your own auth library’s session call in its place.

// 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 session helper

const transcodely = new Transcodely({ apiKey: process.env.TRANSCODELY_API_KEY! });

export const POST = createUploadHandler({
  client: transcodely,
  authorize: async () => {
    const userId = (await auth())?.user?.id;
    if (!userId) return { allow: false, status: 401 };
    return { allow: true, subject: userId, defaults: { visibility: "private" } };
  },
});

3. The upload page

// app/upload/page.tsx
"use client";

import { TranscodelyUploader } from "@transcodely/sdk/react";
import "@transcodely/sdk/react/styles.css";

export default function UploadPage() {
  return (
    <TranscodelyUploader
      endpoint="/api/transcodely/upload"
      onSuccess={({ videoId }) => window.location.assign(`/videos/${videoId}`)}
      onError={(err) => console.warn(err.code, err.message)}
    />
  );
}

4. The playback token route

The video is private, so the player needs a playback token, signed on your server for one viewer.

// app/api/playback-token/route.ts
import { signPlaybackToken } from "@transcodely/sdk";

import { auth } from "@/auth";

export async function GET(request: Request): Promise<Response> {
  const userId = (await auth())?.user?.id;
  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" } });
}

5. The video page

TranscodelyPlayer is a client component, so a server component can render it. Its tokenUrl points at the route above: the player fetches a token before loading, and a fresh one when the token expires.

// app/videos/[id]/page.tsx
import { Transcodely } from "@transcodely/sdk";
import { TranscodelyPlayer } from "@transcodely/sdk/react";

const transcodely = new Transcodely({ apiKey: process.env.TRANSCODELY_API_KEY! });

export default async function VideoPage({ params }: { params: Promise<{ id: string }> }) {
  const { id } = await params;
  const video = await transcodely.videos.get(id);
  if (video.status !== "ready") {
    return <p>Still processing. Refresh in a minute.</p>;
  }
  return <TranscodelyPlayer videoId={video.id} tokenUrl={`/api/playback-token?video=${video.id}`} />;
}

The token carries the viewer id, so the player resumes where this viewer stopped, on any device, and records how much they played. Course Progress covers reading that back. To react to player events such as onProgress or onCompleted, render the player from a component of your own marked "use client"; the React quickstart shows the props.

6. Hear when it is ready

Create an endpoint under Webhooks in the dashboard, pointing at https://your-site.example/api/webhooks/transcodely with the video.ready event, and copy its whsec_… secret into TRANSCODELY_WEBHOOK_SECRET. The URL must be public HTTPS, so test it on a deployment (or through a tunnel to your machine).

// app/api/webhooks/transcodely/route.ts
import { Transcodely, WebhookSignatureError, WebhookTimestampError } from "@transcodely/sdk";

const transcodely = new Transcodely({ apiKey: process.env.TRANSCODELY_API_KEY! });

export async function POST(request: Request): Promise<Response> {
  const body = await request.text(); // the raw body: the signature covers these exact bytes
  try {
    const event = transcodely.webhooks.constructEvent(
      body,
      request.headers.get("transcodely-signature") ?? "",
      process.env.TRANSCODELY_WEBHOOK_SECRET!,
    );
    if (transcodely.webhooks.isEventType(event, "video.ready")) {
      console.log("ready:", event.data.id, event.data.title);
    }
    return new Response(null, { status: 200 });
  } catch (err) {
    if (err instanceof WebhookSignatureError || err instanceof WebhookTimestampError) {
      return new Response("bad signature", { status: 400 });
    }
    throw err;
  }
}

Answer within 10 seconds. A 5xx, 408, 429, a timeout or a network error is retried, up to 15 attempts over about three days; any other 4xx is final and the event is not sent again. A delivery can arrive twice, so de-duplicate on event.id (also in the Webhook-Id header).

What you get back

  • After the upload, onSuccess gets { videoId, status, resumed }. The video is usually processing.
  • When it reaches ready, the page shows the player and the video.ready event’s data is the video object.

What can go wrong

  • The routes answer 401: no one is signed in, or auth() is not your session call.
  • Startup error naming TRANSCODELY_UPLOAD_SECRET: the secret is missing or shorter than 32 characters.
  • onError reports load_failed: the token route did not answer 200 (cause holds the reason). expired means the token ran out; with a tokenUrl the player fetches a fresh one once and resumes where the viewer was.
  • The player stays blank on your domain: your app limits Allowed embed domains and this host is not on the list.
  • Webhook answers 400: the body was parsed before verifying, or the secret is wrong.
  • An API call fails: SDK errors carry err.code and err.requestId (req_…). Quote the request id when you contact support.

Next steps

Run this against your own file

A free account runs standard-quality encodes up to 2 minutes, one at a time (a longer upload is shortened to its first 2 minutes), so the Quickstart runs with nothing set up but an API key.