Open source CapCut alternative.
TypeScript
import { NextResponse, type NextRequest } from "next/server";
import { allowedOrigin, corsHeaders, preflightHeaders } from "@/cut/server/cors";
import { DONKEYCUT_CANONICAL, isDonkeycutHost } from "@/cut/lib/hosts";
import { requestLocale } from "@/i18n/requestLocale";
import { isCurrency, marketCurrency } from "@/lib/billing/currencies";
import { countryFromHeaders } from "@/lib/config/country";
import { BEACON_PATH, META_COOKIE_MAX_AGE_S, metaCookies } from "@/lib/meta/identity";
// Cut (the video editor, publicly "Donkey Cut") lives under /cut in this single
// site app: the marketing landing at /cut and the app under /cut/app. The
// product host gets that mapping — "/" → landing, "/app/…" → editor app
// (generic "/…" → "/cut/…" rewrite) — with donkeycut.com as the one production
// host. The auth pages (/sign-in, /sign-up), "/install", and the legal pages
// are real root-level routes and pass through the rewrite.
//
// www. 308s to the apex; retired domains redirect to donkeycut.com at the
// edge (Cloudflare) and never reach this app.
//
// This file must live in src/ (next to app/) and use the Next 16 `proxy` name;
// a root-level middleware.ts is not loaded when the app is under src/.
// Cut's server APIs are local-only (see src/cut/server/local-only.ts): the
// hosted deploy serves only Cut's client bundle, and that page drives the
// engine running on the user's own Mac. Two rules follow:
// - hosted: these API paths 404 before any handler runs, so no Cut server
// code (disk, ffmpeg, the user's AI CLIs) can execute off-Mac and the
// unauthenticated routes are unreachable.
// - local: the page served from the hosted origin calls this engine
// cross-origin, so grant exactly that origin CORS.
const CUT_API_PREFIX = "/api/cut";
const HOSTED = Boolean(process.env.VERCEL);
const isCutApi = (pathname: string) =>
pathname === CUT_API_PREFIX || pathname.startsWith(`${CUT_API_PREFIX}/`);
function cutApi(req: NextRequest): NextResponse {
if (HOSTED) return new NextResponse(null, { status: 404 });
// Same CORS policy as the packaged engine (src/cut/server/cors.ts): grant the
// hosted Cut origin, pass everything else through as same-origin dev traffic.
const cors = allowedOrigin(req.headers.get("origin") ?? "");
if (!cors) return NextResponse.next();
if (req.method === "OPTIONS") {
return new NextResponse(null, {
status: 204,
headers: preflightHeaders(cors, req.headers.get("access-control-request-headers")),
});
}
const res = NextResponse.next();
for (const [k, v] of Object.entries(corsHeaders(cors))) res.headers.set(k, v);
return res;
}
// Root-level routes the generic "/…" → "/cut/…" rewrite must not capture:
// auth pages, the Mac download, and the legal pages. "/app/settings" is not
// among them: Cut ships its own billing and usage pages under
// /cut/app/settings, which the generic rewrite serves at /app/settings.
const PASSTHROUGH = [
"/install",
"/privacy",
"/terms",
"/sign-in",
"/sign-up",
// Email-footer unsubscribe page; the back office's emails link here.
"/unsubscribe",
];
// Whole-segment prefix match, so "/cut" covers "/cut/…" but not "/cut-app".
const underPath = (pathname: string, prefix: string) =>
pathname === prefix || pathname.startsWith(`${prefix}/`);
const passesThrough = (pathname: string) =>
PASSTHROUGH.some((p) => underPath(pathname, p));
// Every page response gives the browser Meta's ids as first-party cookies the
// server wrote (see lib/meta/identity.ts). Only the server reads them. Each
// page view's beacon renews them, so they last 90 days past the last visit.
function withMetaCookies(req: NextRequest, res: NextResponse): NextResponse {
const scope = req.nextUrl.pathname === BEACON_PATH ? "renew" : "new";
for (const { name, value } of metaCookies(req.nextUrl, req.cookies, Date.now(), scope)) {
res.cookies.set(name, value, {
httpOnly: true,
maxAge: META_COOKIE_MAX_AGE_S,
path: "/",
sameSite: "lax",
secure: req.nextUrl.protocol === "https:",
});
}
return res;
}
// Every page is served in its visitor's language at the same URL. The pages
// live under a hidden [locale] root segment (app/[locale]), and the last step
// of the mapping below prefixes the internal path with the visitor's locale:
// the language they picked (the cookie the pickers write), or else the
// closest match to their browser's Accept-Language, worked out per request.
function localized(req: NextRequest, internalPath: string): NextResponse {
const url = new URL(req.url);
url.pathname = `/${requestLocale(req)}${internalPath === "/" ? "" : internalPath}`;
return withMetaCookies(req, NextResponse.rewrite(url));
}
export function proxy(req: NextRequest) {
const { pathname } = req.nextUrl;
if (isCutApi(pathname)) return cutApi(req);
const host = req.headers.get("host");
// Aliases (www.) canonicalize to the apex.
if (isDonkeycutHost(host) && host?.split(":")[0] !== "donkeycut.com") {
const url = new URL(req.url);
return NextResponse.redirect(
`${DONKEYCUT_CANONICAL}${pathname}${url.search}`,
308,
);
}
// Legacy direct /cut/… links canonicalize to the rewritten address:
// /cut/app/… → /app/….
if (underPath(pathname, "/cut")) {
const url = new URL(req.url);
url.pathname = pathname.slice("/cut".length) || "/";
return NextResponse.redirect(url, 308);
}
if (underPath(pathname, "/api")) return NextResponse.next();
if (pathname === BEACON_PATH) {
return withMetaCookies(req, NextResponse.next());
}
if (passesThrough(pathname)) return localized(req, pathname);
// The landing is prerendered once per currency, and "/" serves the one for
// the visitor's country. The currency segment never shows in a URL, so a
// visit to one ("/eur") goes back to "/".
if (pathname === "/") {
return localized(req, `/cut/${marketCurrency(countryFromHeaders(req.headers))}`);
}
if (isCurrency(pathname.slice(1))) {
return NextResponse.redirect(new URL("/", req.url), 308);
}
return localized(req, `/cut${pathname}`);
}
export const config = {
// Page routes (skip Next internals and files with an extension) plus every
// Cut API path — including media/export files with extensions — so the
// hosted 404 and local CORS above cover all of them.
matcher: [
"/((?!_next/|.*\\..*).*)",
"/api/cut/:path*",
],
};