n8nからRemotionを叩いて動画を自動生成した:Remotionサーバー構築編
業務自動化ツールの n8n と、Reactで動画を作る Remotion を組み合わせて、動画生成ワークフローを構築しました。
今回はその「サーバー構築編」として、VPS上にRemotionをレンダリングするためのHTTP APIサーバー(Express)を構築する方法と、実装時にハマったポイント(メモリ不足やバンドル時間など)を共有します。
全体像
n8nの「HTTP Request」ノードからPOSTリクエストを送り、パラメータ(テキストや色など)を受け取って、サーバー側で動画を生成(レンダリング)してパスを返す構成です。
- n8n: テキストやパラメータをPOST送信
- Expressサーバー (VPS): リクエストを受け取り、Remotionを実行
- Remotion: ReactコンポーネントをMP4にレンダリング
- Response: 生成された動画ファイルのパスを返す
実行環境
Remotionのレンダリングはヘッドレスブラウザを使用するため、リソース(特にメモリ)をかなり消費します。
- VPS OS: Ubuntu 22.04
- Node.js: 20.x
- Remotion: 4.0.x
- Framework: Express 4.x
- メモリ: 4GB以上推奨(2GBだと高確率で落ちます)
プロジェクト構造
シンプルな構成です。apiディレクトリにサーバー処理、srcに動画の元となるReactコンポーネントを配置します。
remotion-server/
├── src/
│ ├── Video.tsx # 動画の中身(Reactコンポーネント)
│ └── index.ts # Remotionのエントリーポイント
├── api/
│ └── server.ts # Expressサーバー本体
├── out/ # レンダリングされた動画の出力先
├── package.json
└── tsconfig.json
実装コード
1. package.json
ここでの重要なポイントは scripts の start コマンドです。
Remotionのレンダリングプロセスは重いため、Node.jsのヒープメモリ制限を緩和しています。
{
"name": "remotion-server",
"version": "1.0.0",
"type": "module",
"scripts": {
"start": "node --max-old-space-size=3072 api/server.js"
},
"dependencies": {
"@remotion/bundler": "^4.0.0",
"@remotion/renderer": "^4.0.0",
"express": "^4.18.2",
"react": "^18.2.0",
"remotion": "^4.0.0"
},
"devDependencies": {
"@types/express": "^4.17.17",
"@types/node": "^20.0.0",
"typescript": "^5.0.0"
}
}
2. 動画コンポーネント (src/Video.tsx)
受け取った props に応じてテキストと背景色が変わるシンプルな動画です。
import { AbsoluteFill, useCurrentFrame, interpolate } from 'remotion';
import React from 'react';
interface VideoProps {
text: string;
color: string;
}
export const MyVideo: React.FC<VideoProps> = ({ text, color }) => {
const frame = useCurrentFrame();
// 0~30フレームの間でフェードイン
const opacity = interpolate(frame, [0, 30], [0, 1], {
extrapolateRight: 'clamp',
});
return (
<AbsoluteFill
style={{
backgroundColor: color,
justifyContent: 'center',
alignItems: 'center',
}}
>
<h1 style={{ fontSize: 100, color: 'white', opacity }}>
{text}
</h1>
</AbsoluteFill>
);
};
3. APIサーバー (api/server.ts)
ここが今回の肝となる実装です。
パフォーマンス向上のため、サーバー起動時に一度だけWebpackのバンドルを実行し、その結果をキャッシュして使い回す設計にしています。
import express from 'express';
import { bundle } from '@remotion/bundler';
import { renderMedia, selectComposition } from '@remotion/renderer';
import path from 'path';
import { fileURLToPath } from 'url';
import fs from 'fs';
const app = express();
app.use(express.json());
// ES Modules環境でのパス解決
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
// バンドル結果をメモリに保持
let cachedBundleLocation: string | null = null;
// サーバー起動時にバンドルを作成
async function initializeBundle() {
console.log('Creating Webpack bundle...');
const entryPoint = path.resolve(__dirname, '../src/index.ts');
cachedBundleLocation = await bundle({
entryPoint,
webpackOverride: (config) => ({
...config,
cache: { type: 'filesystem' }, // ビルド高速化
}),
});
console.log('Bundle created:', cachedBundleLocation);
}
// 動画生成エンドポイント
app.post('/render', async (req, res) => {
try {
const { text = 'Hello', color = '#000000' } = req.body;
if (!cachedBundleLocation) {
return res.status(500).json({ error: 'Bundle not initialized' });
}
// コンポジション(動画設定)の選択
const composition = await selectComposition({
serveUrl: cachedBundleLocation,
id: 'MyVideo',
inputProps: { text, color },
});
// 出力ファイルパスの生成
const timestamp = Date.now();
const outputLocation = path.resolve(__dirname, `../out/video-${timestamp}.mp4`);
// ディレクトリ作成
const outputDir = path.dirname(outputLocation);
if (!fs.existsSync(outputDir)) {
fs.mkdirSync(outputDir, { recursive: true });
}
console.log(`Rendering started: ${outputLocation}`);
// レンダリング実行
await renderMedia({
composition,
serveUrl: cachedBundleLocation,
codec: 'h264',
outputLocation,
inputProps: { text, color },
});
console.log('Rendering completed.');
res.json({
success: true,
path: outputLocation,
filename: path.basename(outputLocation),
});
} catch (error) {
console.error('Render error:', error);
res.status(500).json({
error: 'Rendering failed',
message: error instanceof Error ? error.message : 'Unknown error',
});
}
});
// 起動処理
const PORT = process.env.PORT || 3000;
initializeBundle()
.then(() => {
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
})
.catch((e) => {
console.error('Failed to start server:', e);
process.exit(1);
});
使い方
起動
# 依存関係インストール
npm install
# TypeScriptコンパイル
npx tsc
# サーバー起動(ヒープメモリ拡張済み)
npm start
リクエスト例
n8nやCurlから以下のようにリクエストを送ります。
curl -X POST http://localhost:3000/render \
-H "Content-Type: application/json" \
-d '{"text":"Hello Zenn","color":"#3ea8ff"}'
レスポンス:
{
"success": true,
"path": "/path/to/remotion-server/out/video-1738465200000.mp4",
"filename": "video-1738465200000.mp4"
}
ハマったところ・技術的なポイント
実装中に直面した3つの大きな課題と解決策です。
1. バンドル処理が重すぎてタイムアウトする
最初はリクエストが来るたびに bundle() 関数を実行していましたが、これだと動画生成のたびにWebpackが走り、開始まで毎回5分以上待たされる状態でした。
解決策:
サーバー起動時(initializeBundle)に一度だけバンドルを実行し、生成された bundleLocation を変数にキャッシュして使い回すようにしました。これで2回目以降のリクエストは即座にレンダリングが始まります。
// NG: リクエスト内で毎回実行
// app.post('/render', async (req, res) => {
// const bundleLocation = await bundle({ ... }); // 激重
// });
// OK: 起動時に1回だけ実行してキャッシュ
let cachedBundleLocation: string | null = null;
await initializeBundle();
2. メモリ不足でプロセスが落ちる
VPS(メモリ2GBプラン)で動かしていた際、レンダリング中に Killed と表示されてプロセスが強制終了しました。RemotionはChromiumのヘッドレスモードを使用するため、メモリ消費が激しいです。
解決策:
Node.jsのヒープサイズ上限を上げるオプション --max-old-space-size を追加しました。また、VPSのスペックを4GB以上のものに変更することをお勧めします。
"scripts": {
"start": "node --max-old-space-size=3072 api/server.js"
}
3. パス解決の違い (__dirname vs process.cwd)
開発環境と本番環境(PM2などで起動する場合)で、ファイルの読み込みパスがずれる問題が発生しました。
-
process.cwd(): コマンドを実行したディレクトリ(起動場所に依存) -
__dirname: スクリプトファイルがあるディレクトリ(ファイル場所に依存)
解決策:
エントリーポイントの指定には、起動場所に依存しない __dirname (ESMなので import.meta.url から生成)を使用し、そこからの相対パスで解決するように統一しました。
// NG: どこから起動するかでパスが変わる
// const entryPoint = path.resolve(process.cwd(), 'src/index.ts');
// OK: server.ts の場所を基準にするので確実
const entryPoint = path.resolve(__dirname, '../src/index.ts');
まとめ
これで n8n からいつでも動画生成を呼び出せるAPIサーバーが完成しました。
今回はMP4をローカルに保存してパスを返すだけですが、実際にはこのあと AWS S3 にアップロードして署名付きURLを返す処理などを追加すると、より実用的になります。
自動生成動画は、SNSへの投稿自動化や、個別のパーソナライズド動画生成などに活用できそうです。
Discussion