惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

U
Unit 42
Vercel News
Vercel News
博客园 - 叶小钗
大猫的无限游戏
大猫的无限游戏
MyScale Blog
MyScale Blog
P
Proofpoint News Feed
量子位
Engineering at Meta
Engineering at Meta
B
Blog RSS Feed
博客园 - 【当耐特】
Recent Announcements
Recent Announcements
Google DeepMind News
Google DeepMind News
D
DataBreaches.Net
Stack Overflow Blog
Stack Overflow Blog
博客园 - 聂微东
小众软件
小众软件
Hugging Face - Blog
Hugging Face - Blog
人人都是产品经理
人人都是产品经理
IT之家
IT之家
T
The Blog of Author Tim Ferriss
Last Week in AI
Last Week in AI
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Jina AI
Jina AI
博客园 - 三生石上(FineUI控件)

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Build a video upload + HLS playback flow in Next.js 15 (w...
Mason K · 2026-05-26 · via DEV Community

Mason K

TL;DR

We're going to build a "user uploads a video, user watches the video" feature in a Next.js 15 app. The browser uploads directly to a managed video API so our server never holds bytes, a webhook flips the row from processing to ready, and the watch page plays an HLS manifest. ~120 lines across four files.

📦 Code: github.com/USER/nextjs-video-upload-demo (replace before publishing)

We'll use FastPix as the managed API in this tutorial because the encoding is free on the standard plan and the $25 signup credit covers the bytes you'll burn while iterating. The same shape works against Mux, api.video, or Cloudflare Stream. Only the endpoint names and webhook field names change.

What we're building

  1. POST /api/uploads returns a one-shot direct-upload URL.
  2. Browser PUTs the file to that URL. Our server never sees the bytes.
  3. POST /api/webhooks/fastpix receives an "asset ready" callback and stores the playbackId in our DB.
  4. /watch/[id] renders a player against https://stream.fastpix.io/<playbackId>.m3u8.

💡 Why direct upload? Next.js 15 Server Actions cap request bodies at 1 MB by default, and even Route Handlers with bumped limits will sit there holding a 300 MB file in a serverless function while encoding hasn't started. Direct upload pushes bytes straight to the storage layer.

1. Project setup

npx create-next-app@latest nextjs-video-upload-demo --typescript --app --tailwind
cd nextjs-video-upload-demo
npm install

Make a .env.local:

# .env.local
FASTPIX_TOKEN_ID=pk_...
FASTPIX_SECRET=sk_...
FASTPIX_WEBHOOK_SECRET=whsec_...
NEXT_PUBLIC_APP_URL=http://localhost:3000
DATABASE_URL=file:./dev.db

The token and secret come from dashboard.fastpix.io (Access Tokens). Webhooks live at https://docs.fastpix.io/docs/webhooks-collection; create a webhook pointing at your tunneled URL (more on that below).

Versions you want to be on: Node 22.x or newer, Next.js 15.x, hls.js 1.6.x for the player.

2. The "create upload" Route Handler

// app/api/uploads/route.ts
import { NextResponse } from "next/server";
import { db } from "@/lib/db";

export async function POST() {
  const auth = Buffer.from(
    `${process.env.FASTPIX_TOKEN_ID}:${process.env.FASTPIX_SECRET}`
  ).toString("base64");

  const res = await fetch("https://api.fastpix.io/v1/on-demand", {
    method: "POST",
    headers: {
      Authorization: `Basic ${auth}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      corsOrigin: process.env.NEXT_PUBLIC_APP_URL,
      playbackPolicy: ["public"],
    }),
  });

  if (!res.ok) {
    const txt = await res.text();
    return NextResponse.json({ error: txt }, { status: 502 });
  }

  const data = await res.json();

  const row = await db.video.create({
    data: {
      providerAssetId: data.id,
      status: "processing",
    },
  });

  return NextResponse.json({
    videoId: row.id,
    uploadUrl: data.uploadUrl,
  });
}

cors_origin matters. The browser is about to PUT bytes from your origin to FastPix's upload host, so the upload URL needs to allow your origin. Get this wrong and Chrome will throw a CORS error that looks scarier than it is.

⚠️ Note: don't return assetId to the browser. We stash it server-side and hand the client a stable videoId instead. Keeps the asset-id mapping under our control.

3. The upload component

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

import { useState } from "react";
import { useRouter } from "next/navigation";

export default function UploadPage() {
  const router = useRouter();
  const [progress, setProgress] = useState(0);
  const [error, setError] = useState<string | null>(null);

  async function handleUpload(file: File) {
    setError(null);
    setProgress(0);

    const r = await fetch("/api/uploads", { method: "POST" });
    if (!r.ok) { setError("Could not create upload"); return; }
    const { videoId, uploadUrl } = await r.json();

    await new Promise<void>((resolve, reject) => {
      const xhr = new XMLHttpRequest();
      xhr.open("PUT", uploadUrl);
      xhr.upload.onprogress = (e) => {
        if (e.lengthComputable) setProgress(Math.round((e.loaded / e.total) * 100));
      };
      xhr.onload = () => xhr.status < 300 ? resolve() : reject(new Error(`PUT ${xhr.status}`));
      xhr.onerror = () => reject(new Error("Network error"));
      xhr.send(file);
    }).catch((e) => setError(String(e)));

    router.push(`/watch/${videoId}`);
  }

  return (
    <main className="p-8">
      <input
        type="file"
        accept="video/*"
        onChange={(e) => e.target.files?.[0] && handleUpload(e.target.files[0])}
      />
      {progress > 0 && <p>Uploading: {progress}%</p>}
      {error && <p className="text-red-600">{error}</p>}
    </main>
  );
}

We use XMLHttpRequest instead of fetch because fetch still doesn't expose upload progress in a useful way in 2026, and "uploading: 47%" is the difference between the user closing the tab and waiting.

💡 Tip: for production, swap this for the official FastPix Web upload SDK. It does chunked uploads, retries, and resume on flaky networks. Worth it for mobile users.

4. The webhook handler

// app/api/webhooks/fastpix/route.ts
import { NextResponse } from "next/server";
import { createHmac, timingSafeEqual } from "node:crypto";
import { db } from "@/lib/db";

export async function POST(req: Request) {
  const raw = await req.text();
  const sig = req.headers.get("fastpix-signature") ?? "";

  const expected = createHmac("sha256", process.env.FASTPIX_WEBHOOK_SECRET!)
    .update(raw)
    .digest("hex");

  // timing-safe compare
  if (sig.length !== expected.length ||
      !timingSafeEqual(Buffer.from(sig), Buffer.from(expected))) {
    return NextResponse.json({ error: "bad signature" }, { status: 401 });
  }

  const evt = JSON.parse(raw);
  if (evt.type !== "video.asset.ready") {
    return NextResponse.json({ ok: true });
  }

  const asset = evt.data;
  await db.video.update({
    where: { providerAssetId: asset.id },
    data: { status: "ready", playbackId: asset.playbackIds?.[0]?.id },
  });

  return NextResponse.json({ ok: true });
}

Two things to notice:

  1. We read the raw body as text, then JSON-parse it ourselves. If you use req.json() first, the HMAC won't match because Node has already re-serialized the object.
  2. The signature check is timingSafeEqual. Don't compare with ===; it leaks bytes through timing.

⚠️ Note: webhook event names and field shapes vary by provider. If you're swapping in Mux, the event is video.asset.ready too, but the signature header is Mux-Signature and the payload uses playback_ids (snake case). Always read the provider's webhook reference.

Testing webhooks locally

# In one terminal:
npm run dev

# In another, expose 3000 to the internet:
ngrok http 3000

# Register the ngrok URL in dashboard.fastpix.io → Webhooks
# Format: https://abc123.ngrok-free.app/api/webhooks/fastpix

Tail the output. Upload a clip from the dev UI. You should see a POST to /api/webhooks/fastpix within 30 to 90 seconds for a short clip.

5. The watch page

// app/watch/[id]/page.tsx
import { db } from "@/lib/db";
import { Player } from "./Player";

export default async function WatchPage({ params }: { params: { id: string } }) {
  const v = await db.video.findUnique({ where: { id: params.id } });
  if (!v) return <p>Not found</p>;
  if (v.status !== "ready" || !v.playbackId) {
    return <p>Still processing. This page auto-refreshes.</p>;
  }
  const src = `https://stream.fastpix.io/${v.playbackId}.m3u8`;
  return <Player src={src} />;
}

And a client component for the player itself:

// app/watch/[id]/Player.tsx
"use client";

import { useEffect, useRef } from "react";
import Hls from "hls.js";

export function Player({ src }: { src: string }) {
  const ref = useRef<HTMLVideoElement>(null);

  useEffect(() => {
    const v = ref.current;
    if (!v) return;

    // Safari plays HLS natively.
    if (v.canPlayType("application/vnd.apple.mpegurl")) {
      v.src = src;
      return;
    }

    if (!Hls.isSupported()) return;
    const hls = new Hls();
    hls.loadSource(src);
    hls.attachMedia(v);
    return () => hls.destroy();
  }, [src]);

  return <video ref={ref} controls className="w-full max-w-4xl" />;
}

That's the whole player for a public asset. For private assets, mint a short-lived JWT on the server and append it as a query string. The JWT is signed with an asymmetric key pair you generate once and store in your secret manager.

6. Sanity-check the round trip

# Upload a small clip via the UI.
# Watch the dev server logs.
# You should see:
POST /api/uploads 200
PUT https://upload.fastpix.io/... 200   # browser → FastPix
POST /api/webhooks/fastpix 200          # ~30-90s later
GET  /watch/<videoId> 200

If the webhook never fires, three things go wrong in this order, every time: ngrok URL changed (re-register it), CORS misconfigured on the upload (check the cors_origin you passed), or the webhook secret in .env.local doesn't match the one in the dashboard.

What about the player UI?

We used <video controls> for this tutorial, which gives you the browser default controls. For a real product you'll want a custom player. Two paths:

Option When to pick it
FastPix Web Player (custom element) Default. You drop <fastpix-player playback-id="..."> and the player + analytics wiring come together.
Build on hls.js directly You want full UI control. More code, total ownership of the surface.

I have a longer piece on the second path that covers the events, the error recovery loop, and React StrictMode cleanup. For this tutorial, the default <video controls> is enough to ship.

What's next

  • QoE analytics. Wire the Video Data SDK (or your provider's equivalent). FastPix Video Data is free up to 100,000 views per month, which covers most side-project and SaaS workloads before you ever pay.
  • Resume on interruption. Replace the raw XMLHttpRequest upload with the official Web upload SDK to get chunked uploads and resume.
  • Signed playback. Switch the playback policy from public to signed and add JWT minting to the watch page.
  • Thumbnails. The default thumbnail is the middle frame. Pick a better one.

The pattern transfers cleanly. If you build this on Mux, swap the endpoint to https://api.mux.com/video/v1/uploads, the playback URL to https://stream.mux.com/<playbackId>.m3u8, and the webhook handler to verify Mux-Signature. Cloudflare Stream and api.video have the same three pieces with their own dialect.

The thing this tutorial is really about, more than any one provider, is the shape: broker upload tokens on the server, push bytes from the browser, receive webhooks, render manifests. Once you have that shape in your head, the next video feature you build will take an afternoon instead of a sprint.