在 Next.js 中渲染
關於在 Next.js 應用中使用 Remotion 的常見問題,包含整合方式、伺服器元件限制與常見錯誤排除。
在 Next.js 中渲染
可以在 Next.js 中使用 Remotion 嗎?
可以,但需要注意一些重要的整合細節。Remotion 的渲染功能(@remotion/renderer)是 Node.js 環境的程式庫,因此需要在 Next.js 的伺服器端(API Route 或 Server Action)中使用,而不是在瀏覽器端。
在 Next.js 中使用 Remotion 的推薦架構是什麼?
建議的架構如下:
- 前端:使用
@remotion/player在瀏覽器中預覽影片 - 後端:在 API Route 或 Server Action 中呼叫
renderMedia()觸發渲染 - 儲存:將渲染結果儲存到 S3 或本地檔案系統
用戶瀏覽器 → Next.js API Route → @remotion/renderer → 影片檔案
Next.js 的 App Router 和 Pages Router 都支援嗎?
兩者都支援,但使用方式略有不同:
App Router(推薦):
- 使用 Route Handler(
app/api/render/route.ts)呼叫渲染函式 - 可以使用 Server Actions 觸發渲染任務
Pages Router:
- 使用 API Route(
pages/api/render.ts)呼叫渲染函式
可以在 React Server Component 中使用 Remotion 嗎?
不行。Remotion 的元件(<Composition>、<Sequence> 等)依賴 React Context 和瀏覽器 API,無法在 React Server Component(RSC)中直接使用。
如果你在 RSC 中 import Remotion 元件,可能會遇到以下錯誤:
Error: createContext is not a function
解決方法是在元件頂部加入 "use client" 指令,或將 Remotion 相關元件封裝到獨立的客戶端元件中。
使用 Next.js 時出現 Webpack 錯誤怎麼辦?
Remotion 使用了一些 Node.js 原生模組,在 Next.js 的客戶端打包時可能造成問題。在 next.config.js 中加入以下設定可解決大多數問題:
/** @type {import('next').NextConfig} */
const nextConfig = {
webpack: (config, { isServer }) => {
if (!isServer) {
config.resolve.fallback = {
...config.resolve.fallback,
fs: false,
path: false,
os: false,
};
}
return config;
},
};
module.exports = nextConfig;如何在 Next.js API Route 中觸發渲染?
// app/api/render/route.ts
import { renderMedia, selectComposition } from "@remotion/renderer";
import { bundle } from "@remotion/bundler";
import { NextResponse } from "next/server";
export async function POST(request: Request) {
const { compositionId, inputProps } = await request.json();
const bundleLocation = await bundle({
entryPoint: "./remotion/index.ts",
});
const composition = await selectComposition({
serveUrl: bundleLocation,
id: compositionId,
inputProps,
});
await renderMedia({
composition,
serveUrl: bundleLocation,
codec: "h264",
outputLocation: `out/${compositionId}.mp4`,
inputProps,
});
return NextResponse.json({ success: true });
}在 Vercel 上部署 Next.js + Remotion 有限制嗎?
有重大限制。Vercel 的 Serverless Function 有執行時間(最長 60 秒)和記憶體限制,無法支援長時間的影片渲染任務。
建議改用:
- Remotion Lambda:使用 AWS Lambda 進行渲染,不受 Vercel 限制
- 獨立伺服器:在 Railway、Render 或自架伺服器上執行渲染任務
詳情請參考 在 Vercel 上渲染 文件。
@remotion/player 可以在 Next.js 中使用嗎?
可以,但必須在客戶端元件中使用。在使用 @remotion/player 的元件頂部加入 "use client" 指令:
"use client";
import { Player } from "@remotion/player";
import { MyVideo } from "./MyVideo";
export const VideoPlayer = () => {
return (
<Player
component={MyVideo}
durationInFrames={150}
fps={30}
compositionWidth={1280}
compositionHeight={720}
/>
);
};開發時 HMR(熱模組替換)正常運作嗎?
@remotion/player 支援 Next.js 的 HMR,修改 Remotion 元件後播放器會自動更新。但 Remotion Studio 是獨立的開發伺服器,需要另外啟動,不整合在 Next.js 的開發環境中。