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

推荐订阅源

Security Archives - TechRepublic
Security Archives - TechRepublic
Project Zero
Project Zero
K
Kaspersky official blog
G
Google Developers Blog
T
Threat Research - Cisco Blogs
T
The Blog of Author Tim Ferriss
Cyberwarzone
Cyberwarzone
Y
Y Combinator Blog
Recorded Future
Recorded Future
Blog — PlanetScale
Blog — PlanetScale
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Cisco Talos Blog
Cisco Talos Blog
Latest news
Latest news
Microsoft Security Blog
Microsoft Security Blog
H
Help Net Security
S
Schneier on Security
P
Palo Alto Networks Blog
H
Hacker News: Front Page
N
News and Events Feed by Topic
N
Netflix TechBlog - Medium
博客园 - Franky
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
SecWiki News
SecWiki News
Cloudbric
Cloudbric
TaoSecurity Blog
TaoSecurity Blog
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
The Hacker News
The Hacker News
C
Check Point Blog
L
LangChain Blog
腾讯CDC
小众软件
小众软件
T
Tenable Blog
Google DeepMind News
Google DeepMind News
GbyAI
GbyAI
L
LINUX DO - 最新话题
A
About on SuperTechFans
Google Online Security Blog
Google Online Security Blog
C
Cisco Blogs
Recent Announcements
Recent Announcements
Hacker News: Ask HN
Hacker News: Ask HN
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Vercel News
Vercel News
雷峰网
雷峰网
美团技术团队
D
DataBreaches.Net
Martin Fowler
Martin Fowler
Help Net Security
Help Net Security
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
F
Full Disclosure
博客园_首页

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 Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Build a video upload + HLS playback flow in Next.js 15 (with direct uploads)
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.