Skip to content

🎥 Make videos programmatically with React

move lambda functions over from next.js

Jonny Burger01391386197c
diff --git a/packages/template-react-router/app/components/AlignEnd.tsx b/packages/template-react-router/app/components/AlignEnd.tsx
new file mode 100644
index 0000000000..7ff7ad53bf
--- /dev/null
+++ b/packages/template-react-router/app/components/AlignEnd.tsx
@@ -0,0 +1,7 @@
+import React from "react";
+
+export const AlignEnd: React.FC<{
+ children: React.ReactNode;
+}> = ({ children }) => {
+ return <div className="self-end">{children}</div>;
+};
diff --git a/packages/template-react-router/app/components/Button.tsx b/packages/template-react-router/app/components/Button.tsx
new file mode 100644
index 0000000000..4f924f335d
--- /dev/null
+++ b/packages/template-react-router/app/components/Button.tsx
@@ -0,0 +1,39 @@
+import React, { forwardRef } from "react";
+import { Spacing } from "./Spacing";
+import { Spinner } from "./Spinner";
+import { cn } from "../lib/utils";
+
+const ButtonForward: React.ForwardRefRenderFunction<
+ HTMLButtonElement,
+ {
+ onClick?: () => void;
+ disabled?: boolean;
+ children: React.ReactNode;
+ loading?: boolean;
+ secondary?: boolean;
+ }
+> = ({ onClick, disabled, children, loading, secondary }, ref) => {
+ return (
+ <button
+ ref={ref}
+ className={cn(
+ "border-foreground border rounded-geist bg-foreground text-background px-geist-half font-geist h-10 font-medium transition-all duration-150 ease-in-out inline-flex items-center appearance-none text-sm hover:bg-background hover:text-foreground hover:border-focused-border-color disabled:bg-button-disabled-color disabled:text-disabled-text-color disabled:border-unfocused-border-color disabled:cursor-not-allowed",
+ secondary
+ ? "bg-background text-foreground border-unfocused-border-color"
+ : undefined,
+ )}
+ onClick={onClick}
+ disabled={disabled}
+ >
+ {loading && (
+ <>
+ <Spinner size={20}></Spinner>
+ <Spacing></Spacing>
+ </>
+ )}
+ {children}
+ </button>
+ );
+};
+
+export const Button = forwardRef(ButtonForward);
diff --git a/packages/template-react-router/app/components/DownloadButton.tsx b/packages/template-react-router/app/components/DownloadButton.tsx
new file mode 100644
index 0000000000..f08d4b5915
--- /dev/null
+++ b/packages/template-react-router/app/components/DownloadButton.tsx
@@ -0,0 +1,56 @@
+import React from "react";
+import { State } from "../lib/use-rendering";
+import { Button } from "./Button";
+import { Spacing } from "./Spacing";
+
+const Megabytes: React.FC<{
+ sizeInBytes: number;
+}> = ({ sizeInBytes }) => {
+ const megabytes = Intl.NumberFormat("en", {
+ notation: "compact",
+ style: "unit",
+ unit: "byte",
+ unitDisplay: "narrow",
+ }).format(sizeInBytes);
+ return <span className="opacity-60">{megabytes}</span>;
+};
+
+export const DownloadButton: React.FC<{
+ state: State;
+ undo: () => void;
+}> = ({ state, undo }) => {
+ if (state.status === "rendering") {
+ return <Button disabled>Download video</Button>;
+ }
+
+ if (state.status !== "done") {
+ throw new Error("Download button should not be rendered when not done");
+ }
+
+ return (
+ <div className="flex">
+ <Button secondary onClick={undo}>
+ <UndoIcon></UndoIcon>
+ </Button>
+ <Spacing></Spacing>
+ <a href={state.url}>
+ <Button>
+ Download video
+ <Spacing></Spacing>
+ <Megabytes sizeInBytes={state.size}></Megabytes>
+ </Button>
+ </a>
+ </div>
+ );
+};
+
+const UndoIcon: React.FC = () => {
+ return (
+ <svg height="1em" viewBox="0 0 512 512">
+ <path
+ fill="var(--foreground)"
+ d="M48.5 224H40c-13.3 0-24-10.7-24-24V72c0-9.7 5.8-18.5 14.8-22.2s19.3-1.7 26.2 5.2L98.6 96.6c87.6-86.5 228.7-86.2 315.8 1c87.5 87.5 87.5 229.3 0 316.8s-229.3 87.5-316.8 0c-12.5-12.5-12.5-32.8 0-45.3s32.8-12.5 45.3 0c62.5 62.5 163.8 62.5 226.3 0s62.5-163.8 0-226.3c-62.2-62.2-162.7-62.5-225.3-1L185 183c6.9 6.9 8.9 17.2 5.2 26.2s-12.5 14.8-22.2 14.8H48.5z"
+ />
+ </svg>
+ );
+};
diff --git a/packages/template-react-router/app/components/Error.tsx b/packages/template-react-router/app/components/Error.tsx
new file mode 100644
index 0000000000..28020e53c2
--- /dev/null
+++ b/packages/template-react-router/app/components/Error.tsx
@@ -0,0 +1,25 @@
+import React from "react";
+
+export const ErrorComp: React.FC<{
+ message: string;
+}> = ({ message }) => {
+ return (
+ <div className="text-geist-error font-geist py-geist-half">
+ <svg
+ fill="none"
+ shapeRendering="geometricPrecision"
+ stroke="currentColor"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ strokeWidth="2"
+ viewBox="0 0 24 24"
+ className="h-5 align-text-bottom mr-1.5 inline"
+ >
+ <circle cx="12" cy="12" r="10" fill="var(--geist-fill)"></circle>
+ <path d="M12 8v4" stroke="currentColor"></path>
+ <path d="M12 16h.01" stroke="currentColor"></path>
+ </svg>
+ <strong>Error:</strong> {message}
+ </div>
+ );
+};
diff --git a/packages/template-react-router/app/components/Input.tsx b/packages/template-react-router/app/components/Input.tsx
new file mode 100644
index 0000000000..d6dcc0434d
--- /dev/null
+++ b/packages/template-react-router/app/components/Input.tsx
@@ -0,0 +1,24 @@
+import React, { useCallback } from "react";
+
+export const Input: React.FC<{
+ text: string;
+ setText: React.Dispatch<React.SetStateAction<string>>;
+ disabled?: boolean;
+}> = ({ text, setText, disabled }) => {
+ const onChange: React.ChangeEventHandler<HTMLInputElement> = useCallback(
+ (e) => {
+ setText(e.currentTarget.value);
+ },
+ [setText],
+ );
+
+ return (
+ <input
+ className="leading-[1.7] block w-full rounded-geist bg-background p-geist-half text-foreground text-sm border border-unfocused-border-color transition-colors duration-150 ease-in-out focus:border-focused-border-color outline-none"
+ disabled={disabled}
+ name="title"
+ value={text}
+ onChange={onChange}
+ />
+ );
+};
diff --git a/packages/template-react-router/app/components/InputContainer.tsx b/packages/template-react-router/app/components/InputContainer.tsx
new file mode 100644
index 0000000000..19cbcb59e5
--- /dev/null
+++ b/packages/template-react-router/app/components/InputContainer.tsx
@@ -0,0 +1,11 @@
+import React from "react";
+
+export const InputContainer: React.FC<{
+ children: React.ReactNode;
+}> = ({ children }) => {
+ return (
+ <div className="border border-unfocused-border-color p-geist rounded-geist bg-background flex flex-col">
+ {children}
+ </div>
+ );
+};
diff --git a/packages/template-react-router/app/components/ProgressBar.tsx b/packages/template-react-router/app/components/ProgressBar.tsx
new file mode 100644
index 0000000000..a4c5886df7
--- /dev/null
+++ b/packages/template-react-router/app/components/ProgressBar.tsx
@@ -0,0 +1,22 @@
+import React, { useMemo } from "react";
+
+export const ProgressBar: React.FC<{
+ progress: number;
+}> = ({ progress }) => {
+ const fill: React.CSSProperties = useMemo(() => {
+ return {
+ width: `${progress * 100}%`,
+ };
+ }, [progress]);
+
+ return (
+ <div>
+ <div className="w-full h-2.5 rounded-md appearance-none bg-unfocused-border-color mt-2.5 mb-6">
+ <div
+ className="bg-foreground h-2.5 rounded-md transition-all ease-in-out duration-100"
+ style={fill}
+ ></div>
+ </div>
+ </div>
+ );
+};
diff --git a/packages/template-react-router/app/components/RenderControls.tsx b/packages/template-react-router/app/components/RenderControls.tsx
new file mode 100644
index 0000000000..0d657a0fef
--- /dev/null
+++ b/packages/template-react-router/app/components/RenderControls.tsx
@@ -0,0 +1,60 @@
+import { z } from "zod";
+import { AlignEnd } from "./AlignEnd";
+import { Button } from "./Button";
+import { InputContainer } from "./InputContainer";
+import { DownloadButton } from "./DownloadButton";
+import { ErrorComp } from "./Error";
+import { Input } from "./Input";
+import { ProgressBar } from "./ProgressBar";
+import { Spacing } from "./Spacing";
+import { useRendering } from "../lib/use-rendering";
+import { COMPOSITION_ID } from "~/remotion/constants.mjs";
+import { CompositionProps } from "~/remotion/schemata";
+
+export const RenderControls: React.FC<{
+ text: string;
+ setText: React.Dispatch<React.SetStateAction<string>>;
+ inputProps: z.infer<typeof CompositionProps>;
+}> = ({ text, setText, inputProps }) => {
+ const { renderMedia, state, undo } = useRendering(COMPOSITION_ID, inputProps);
+
+ return (
+ <InputContainer>
+ {state.status === "init" ||
+ state.status === "invoking" ||
+ state.status === "error" ? (
+ <>
+ <Input
+ disabled={state.status === "invoking"}
+ setText={setText}
+ text={text}
+ ></Input>
+ <Spacing></Spacing>
+ <AlignEnd>
+ <Button
+ disabled={state.status === "invoking"}
+ loading={state.status === "invoking"}
+ onClick={renderMedia}
+ >
+ Render video
+ </Button>
+ </AlignEnd>
+ {state.status === "error" ? (
+ <ErrorComp message={state.error.message}></ErrorComp>
+ ) : null}
+ </>
+ ) : null}
+ {state.status === "rendering" || state.status === "done" ? (
+ <>
+ <ProgressBar
+ progress={state.status === "rendering" ? state.progress : 1}
+ />
+ <Spacing></Spacing>
+ <AlignEnd>
+ <DownloadButton undo={undo} state={state}></DownloadButton>
+ </AlignEnd>
+ </>
+ ) : null}
+ </InputContainer>
+ );
+};
diff --git a/packages/template-react-router/app/components/Spacing.tsx b/packages/template-react-router/app/components/Spacing.tsx
new file mode 100644
index 0000000000..c901cfdadb
--- /dev/null
+++ b/packages/template-react-router/app/components/Spacing.tsx
@@ -0,0 +1,5 @@
+import React from "react";
+
+export const Spacing: React.FC = () => {
+ return <div className="w-geist-quarter h-geist-quarter" />;
+};
diff --git a/packages/template-react-router/app/components/Spinner.tsx b/packages/template-react-router/app/components/Spinner.tsx
new file mode 100644
index 0000000000..405f2260c1
--- /dev/null
+++ b/packages/template-react-router/app/components/Spinner.tsx
@@ -0,0 +1,46 @@
+import React, { useMemo } from "react";
+import { makeRect } from "@remotion/shapes";
+import { translatePath } from "@remotion/paths";
+
+const viewBox = 100;
+const lines = 12;
+const width = viewBox * 0.08;
+
+const { path } = makeRect({
+ height: viewBox * 0.24,
+ width,
+ cornerRadius: width / 2,
+});
+
+const translated = translatePath(path, viewBox / 2 - width / 2, viewBox * 0.03);
+
+export const Spinner: React.FC<{
+ size: number;
+}> = ({ size }) => {
+ const style = useMemo(() => {
+ return {
+ width: size,
+ height: size,
+ };
+ }, [size]);
+
+ return (
+ <svg style={style} viewBox={`0 0 ${viewBox} ${viewBox}`}>
+ {new Array(lines).fill(true).map((_, index) => {
+ return (
+ <path
+ className="animate-spinner"
+ style={{
+ rotate: `${(index * Math.PI * 2) / lines}rad`,
+ transformOrigin: "center center",
+ animationDelay: `${index * 0.1 - lines * 0.1}s`,
+ }}
+ key={index}
+ d={translated}
+ fill="var(--foreground)"
+ ></path>
+ );
+ })}
+ </svg>
+ );
+};
diff --git a/packages/template-react-router/app/components/Tips.tsx b/packages/template-react-router/app/components/Tips.tsx
new file mode 100644
index 0000000000..4e0d16cf4e
--- /dev/null
+++ b/packages/template-react-router/app/components/Tips.tsx
@@ -0,0 +1,53 @@
+import React from "react";
+
+const Tip: React.FC<{
+ title: React.ReactNode;
+ description: React.ReactNode;
+ href: string;
+}> = ({ title, description, href }) => {
+ return (
+ <a href={href} target="_blank" rel="noreferrer" className="flex-1">
+ <div className="transition-transform duration-200 ease-in-out p-2.5 group hover:-translate-y-0.5">
+ <div className="flex flex-row items-center justify-start">
+ <h4 className="my-3 font-bold text-foreground">{title}</h4>
+ <div className="flex-1"></div>
+ <svg
+ className="opacity-0 transition-opacity duration-200 ease-in-out group-hover:opacity-100"
+ height="1em"
+ viewBox="0 0 448 512"
+ >
+ <path
+ fill="var(--foreground)"
+ d="M438.6 278.6c12.5-12.5 12.5-32.8 0-45.3l-160-160c-12.5-12.5-32.8-12.5-45.3 0s-12.5 32.8 0 45.3L338.8 224 32 224c-17.7 0-32 14.3-32 32s14.3 32 32 32l306.7 0L233.4 393.4c-12.5 12.5-12.5 32.8 0 45.3s32.8 12.5 45.3 0l160-160z"
+ />
+ </svg>
+ </div>
+ <p className="text-sm leading-normal text-subtitle mb-6">
+ {description}
+ </p>
+ </div>
+ </a>
+ );
+};
+
+export const Tips: React.FC = () => {
+ return (
+ <div className="flex flex-col md:flex-row font-geist">
+ <Tip
+ href="https://www.remotion.dev/docs/the-fundamentals"
+ title="Learn Remotion"
+ description="Learn how to customize this video written in React."
+ ></Tip>
+ <Tip
+ href="https://github.com/remotion-dev/template-next-app-dir"
+ title="See source"
+ description="Visit the GitHub repository for this app."
+ ></Tip>
+ <Tip
+ href="https://remotion.dev/discord"
+ title="Join the community"
+ description="Chat with others builders on Discord."
+ ></Tip>
+ </div>
+ );
+};
diff --git a/packages/template-react-router/app/components/render-progress.tsx b/packages/template-react-router/app/components/render-progress.tsx
deleted file mode 100644
index 078caa5ba0..0000000000
--- a/packages/template-react-router/app/components/render-progress.tsx
+++ /dev/null
@@ -1,45 +0,0 @@
-import { usePollRenderStatus } from "../hooks/use-poll-render-status";
-
-interface Props {
- renderId: string;
- bucketName: string;
-}
-
-export const RenderProgress = ({ renderId, bucketName }: Props) => {
- const { progress } = usePollRenderStatus({
- renderId,
- bucketName,
- });
-
- if (!progress) {
- return <div> Invoking...</div>;
- }
-
- if (progress.errors.length > 0) {
- return (
- <div>
- <h3>Well this is unfortunate but there is an error...</h3>
- <span>{progress.errors[0].message}</span>
- </div>
- );
- }
-
- if (progress.outputFile) {
- return (
- <div>
- <a href={progress.outputFile} target="_blank" rel="noopener noreferrer">
- Download Video
- </a>
- </div>
- );
- }
-
- return (
- <div>
- <p>Rendering...</p>
- {progress ? (
- <div>{`${Math.round(progress.overallProgress * 100)}%`}</div>
- ) : null}
- </div>
- );
-};
diff --git a/packages/template-react-router/app/deploy.ts b/packages/template-react-router/app/deploy.ts
deleted file mode 100644
index 0463b949df..0000000000
--- a/packages/template-react-router/app/deploy.ts
+++ /dev/null
@@ -1,47 +0,0 @@
-import type { AwsRegion } from "@remotion/lambda";
-import {
- deploySite,
- getOrCreateBucket,
- deployFunction,
-} from "@remotion/lambda";
-import dotenv from "dotenv";
-import path from "path";
-import { RAM, TIMEOUT, SITE_NAME, DISK } from "./remotion/constants.ts";
-
-dotenv.config();
-
-const run = async () => {
- const region = process.env.REMOTION_AWS_REGION as AwsRegion;
- if (!region) {
- throw new Error("REMOTION_AWS_REGION is not set");
- }
- const { alreadyExisted, functionName } = await deployFunction({
- createCloudWatchLogGroup: true,
- memorySizeInMb: RAM,
- region,
- diskSizeInMb: DISK,
- timeoutInSeconds: TIMEOUT,
- });
- console.log(
- `${alreadyExisted ? "Ensured" : "Deployed"} function "${functionName}"`,
- );
-
- const { bucketName } = await getOrCreateBucket({ region });
- const { serveUrl } = await deploySite({
- siteName: SITE_NAME,
- bucketName,
- entryPoint: path.join(process.cwd(), "app/remotion/index.ts"),
- region,
- });
-
- console.log(serveUrl);
-};
-
-run()
- .then(() => {
- process.exit(0);
- })
- .catch((err) => {
- console.log(err);
- process.exit(1);
- });
diff --git a/packages/template-react-router/app/home.tsx b/packages/template-react-router/app/home.tsx
index faa763ac30..a24a3b8e2c 100644
--- a/packages/template-react-router/app/home.tsx
+++ b/packages/template-react-router/app/home.tsx
@@ -1,133 +1,59 @@
import { Player } from "@remotion/player";
-import React, { useCallback, useMemo, useState } from "react";
-import { RenderProgress } from "./components/render-progress";
-import { renderVideo } from "./lib/render-video.server";
+import { useMemo, useState } from "react";
import {
- SITE_NAME,
DURATION_IN_FRAMES,
COMPOSITION_FPS,
COMPOSITION_HEIGHT,
- COMPOSITION_ID,
COMPOSITION_WIDTH,
- CompositionProps,
-} from "./remotion/constants";
-import stylesHref from "./app.css";
-import type { RenderResponse } from "./lib/types";
-import { ActionFunction, LinksFunction, useFetcher } from "react-router";
+} from "./remotion/constants.mjs";
+import "./app.css";
import { z } from "zod";
import { Main } from "./remotion/components/Main";
+import { RenderControls } from "./components/RenderControls";
+import { Spacing } from "./components/Spacing";
+import { Tips } from "./components/Tips";
+import { CompositionProps } from "./remotion/schemata";
-export const links: LinksFunction = () => {
- return [{ rel: "stylesheet", href: stylesHref }];
-};
-
-const container: React.CSSProperties = {
- fontFamily: "sans-serif",
- lineHeight: "1.4",
- margin: "auto",
- maxWidth: 1200,
-};
-
-const content: React.CSSProperties = {
- width: 400,
- padding: 24,
-};
-
-const playerContainer: React.CSSProperties = {
- flex: 1,
- aspectRatio: "16 / 9",
-};
-
-const playerStyle: React.CSSProperties = {
- width: "100%",
- height: "auto",
- aspectRatio: 16 / 9,
-};
-
-export const action: ActionFunction = async ({ request }) => {
- const formData = await request.formData();
- const title = formData.get("title") as string;
-
- if (!title) {
- throw new Response(JSON.stringify({ error: "No name entered" }), {
- status: 400,
- });
- }
-
- const inputProps: z.infer<typeof CompositionProps> = {
- title: title,
- };
-
- const renderData = await renderVideo({
- serveUrl: SITE_NAME,
- composition: COMPOSITION_ID,
- inputProps,
- outName: `logo-animation.mp4`,
- metadata: null,
- });
-
- return renderData;
-};
export default function Index() {
- const [title, settitle] = useState("React Router + Remotion");
- const fetcher = useFetcher<RenderResponse>();
-
- const onNameChange = useCallback(
- (e: React.ChangeEvent<HTMLInputElement>) => settitle(e.target.value),
- [],
- );
-
- const onClick = useCallback(
- (e: React.MouseEvent<HTMLButtonElement, MouseEvent>) => {
- e.preventDefault();
- const data = new FormData();
- data.append("title", title);
- fetcher.submit(data, { method: "post" });
- },
- [fetcher, title],
- );
+ const [text, setText] = useState("React Router + Remotion");
const inputProps: z.infer<typeof CompositionProps> = useMemo(() => {
- return { title };
- }, [title]);
+ return {
+ title: text,
+ };
+ }, [text]);
return (
- <div style={container}>
- <div style={playerContainer}>
- <Player
- component={Main}
- inputProps={inputProps}
- durationInFrames={DURATION_IN_FRAMES}
- fps={COMPOSITION_FPS}
- compositionWidth={COMPOSITION_WIDTH}
- compositionHeight={COMPOSITION_HEIGHT}
- controls
- style={playerStyle}
- />
- </div>
- <div style={content}>
- <h1>Welcome to the Remotion React Router template!</h1>
- <div>
- {fetcher.data ? (
- <RenderProgress
- bucketName={fetcher.data.bucketName}
- renderId={fetcher.data.renderId}
- />
- ) : fetcher.state === "submitting" ? (
- <div>Invoking</div>
- ) : (
- <div>
- <p>Enter your name for a custom video:</p>
- <fetcher.Form method="post">
- <input type="text" onChange={onNameChange} value={title} />
- <br></br>
- <button type="submit" onClick={onClick}>
- Render a video
- </button>
- </fetcher.Form>
- </div>
- )}
+ <div>
+ <div className="max-w-screen-md m-auto mb-5">
+ <div className="overflow-hidden rounded-geist shadow-[0_0_200px_rgba(0,0,0,0.15)] mb-10 mt-16">
+ <Player
+ component={Main}
+ inputProps={inputProps}
+ durationInFrames={DURATION_IN_FRAMES}
+ fps={COMPOSITION_FPS}
+ compositionHeight={COMPOSITION_HEIGHT}
+ compositionWidth={COMPOSITION_WIDTH}
+ style={{
+ // Can't use tailwind class for width since player's default styles take presedence over tailwind's,
+ // but not over inline styles
+ width: "100%",
+ }}
+ controls
+ autoPlay
+ loop
+ />
</div>
+ <RenderControls
+ text={text}
+ setText={setText}
+ inputProps={inputProps}
+ ></RenderControls>
+ <Spacing></Spacing>
+ <Spacing></Spacing>
+ <Spacing></Spacing>
+ <Spacing></Spacing>
+ <Tips></Tips>
</div>
</div>
);
diff --git a/packages/template-react-router/app/hooks/use-poll-render-status.ts b/packages/template-react-router/app/hooks/use-poll-render-status.ts
deleted file mode 100644
index 6cc79838b4..0000000000
--- a/packages/template-react-router/app/hooks/use-poll-render-status.ts
+++ /dev/null
@@ -1,50 +0,0 @@
-import { useCallback, useEffect, useMemo } from "react";
-import type { StatusResponse } from "../lib/types";
-import { useFetcher } from "react-router";
-
-export function usePollRenderStatus({
- renderId,
- bucketName,
-}: {
- renderId: string;
- bucketName: string;
-}) {
- const { submit, data } = useFetcher<StatusResponse>();
-
- const checkRenderProgress = useCallback(() => {
- submit(
- { renderId, bucketName },
- {
- method: "post",
- action: "progress",
- },
- );
- }, [submit, renderId, bucketName]);
-
- useEffect(() => {
- checkRenderProgress();
- }, [checkRenderProgress]);
-
- const done = data?.done ?? false;
-
- useEffect(() => {
- if (done) {
- return;
- }
- const interval = setInterval(() => {
- checkRenderProgress();
- }, 2000);
-
- return () => {
- clearInterval(interval);
- };
- }, [checkRenderProgress, done, renderId]);
-
- const status = useMemo(() => {
- return {
- progress: data,
- };
- }, [data]);
-
- return status;
-}
diff --git a/packages/template-react-router/app/lib/api.ts b/packages/template-react-router/app/lib/api.ts
new file mode 100644
index 0000000000..fa274b493f
--- /dev/null
+++ b/packages/template-react-router/app/lib/api.ts
@@ -0,0 +1,64 @@
+import { z } from "zod";
+import type { RenderMediaOnLambdaOutput } from "@remotion/lambda/client";
+import {
+ CompositionProps,
+ ProgressRequest,
+ ProgressResponse,
+ RenderRequest,
+} from "~/remotion/schemata";
+
+export type ApiResponse<Res> =
+ | {
+ type: "error";
+ message: string;
+ }
+ | {
+ type: "success";
+ data: Res;
+ };
+
+const makeRequest = async <Res>(
+ endpoint: string,
+ body: unknown,
+): Promise<Res> => {
+ const result = await fetch(endpoint, {
+ method: "post",
+ body: JSON.stringify(body),
+ headers: {
+ "content-type": "application/json",
+ },
+ });
+ const json = (await result.json()) as ApiResponse<Res>;
+ if (json.type === "error") {
+ throw new Error(json.message);
+ }
+
+ return json.data;
+};
+
+export const renderVideo = async ({
+ inputProps,
+}: {
+ inputProps: z.infer<typeof CompositionProps>;
+}) => {
+ const body: z.infer<typeof RenderRequest> = {
+ inputProps,
+ };
+
+ return makeRequest<RenderMediaOnLambdaOutput>("/api/lambda/render", body);
+};
+
+export const getProgress = async ({
+ id,
+ bucketName,
+}: {
+ id: string;
+ bucketName: string;
+}) => {
+ const body: z.infer<typeof ProgressRequest> = {
+ id,
+ bucketName,
+ };
+
+ return makeRequest<ProgressResponse>("/api/lambda/progress", body);
+};
diff --git a/packages/template-react-router/app/lib/render-video.server.ts b/packages/template-react-router/app/lib/render-video.server.ts
index 50a0cc91cf..35088d22bc 100644
--- a/packages/template-react-router/app/lib/render-video.server.ts
+++ b/packages/template-react-router/app/lib/render-video.server.ts
@@ -4,8 +4,10 @@ import {
speculateFunctionName,
} from "@remotion/lambda/client";
import type { RenderResponse } from "./types";
-import { CompositionProps, DISK, RAM, TIMEOUT } from "app/remotion/constants";
import { z } from "zod";
+import { CompositionProps } from "~/remotion/schemata";
+import { TIMEOUT } from "dns";
+import { DISK, RAM } from "~/remotion/constants.mjs";
export const renderVideo = async ({
serveUrl,
diff --git a/packages/template-react-router/app/lib/return-error-as-json.ts b/packages/template-react-router/app/lib/return-error-as-json.ts
new file mode 100644
index 0000000000..d4bbd7b8a5
--- /dev/null
+++ b/packages/template-react-router/app/lib/return-error-as-json.ts
@@ -0,0 +1,14 @@
+import { ActionFunction } from "react-router";
+
+export const errorAsJson = (fn: ActionFunction): ActionFunction => {
+ return async (...args) => {
+ try {
+ return await fn(...args);
+ } catch (err) {
+ return new Response(
+ JSON.stringify({ type: "error", message: (err as Error).message }),
+ { status: 500 },
+ );
+ }
+ };
+};
diff --git a/packages/template-react-router/app/lib/use-rendering.ts b/packages/template-react-router/app/lib/use-rendering.ts
new file mode 100644
index 0000000000..dd60d099de
--- /dev/null
+++ b/packages/template-react-router/app/lib/use-rendering.ts
@@ -0,0 +1,116 @@
+import { z } from "zod";
+import { useCallback, useMemo, useState } from "react";
+import { getProgress, renderVideo } from "./api";
+import { CompositionProps } from "~/remotion/schemata";
+
+export type State =
+ | {
+ status: "init";
+ }
+ | {
+ status: "invoking";
+ }
+ | {
+ renderId: string;
+ bucketName: string;
+ progress: number;
+ status: "rendering";
+ }
+ | {
+ renderId: string | null;
+ status: "error";
+ error: Error;
+ }
+ | {
+ url: string;
+ size: number;
+ status: "done";
+ };
+
+const wait = async (milliSeconds: number) => {
+ await new Promise<void>((resolve) => {
+ setTimeout(() => {
+ resolve();
+ }, milliSeconds);
+ });
+};
+
+export const useRendering = (
+ id: string,
+ inputProps: z.infer<typeof CompositionProps>,
+) => {
+ const [state, setState] = useState<State>({
+ status: "init",
+ });
+
+ const renderMedia = useCallback(async () => {
+ setState({
+ status: "invoking",
+ });
+ try {
+ const { renderId, bucketName } = await renderVideo({ inputProps });
+ setState({
+ status: "rendering",
+ progress: 0,
+ renderId: renderId,
+ bucketName: bucketName,
+ });
+
+ let pending = true;
+
+ while (pending) {
+ const result = await getProgress({
+ id: renderId,
+ bucketName: bucketName,
+ });
+ switch (result.type) {
+ case "error": {
+ setState({
+ status: "error",
+ renderId: renderId,
+ error: new Error(result.message),
+ });
+ pending = false;
+ break;
+ }
+ case "done": {
+ setState({
+ size: result.size,
+ url: result.url,
+ status: "done",
+ });
+ pending = false;
+ break;
+ }
+ case "progress": {
+ setState({
+ status: "rendering",
+ bucketName: bucketName,
+ progress: result.progress,
+ renderId: renderId,
+ });
+ await wait(1000);
+ }
+ }
+ }
+ } catch (err) {
+ setState({
+ status: "error",
+ error: err as Error,
+ renderId: null,
+ });
+ }
+ }, [id, inputProps]);
+
+ const undo = useCallback(() => {
+ setState({ status: "init" });
+ }, []);
+
+ return useMemo(() => {
+ return {
+ renderMedia,
+ state,
+ undo,
+ };
+ }, [renderMedia, state, undo]);
+};
diff --git a/packages/template-react-router/app/lib/utils.ts b/packages/template-react-router/app/lib/utils.ts
new file mode 100644
index 0000000000..a5ef193506
--- /dev/null
+++ b/packages/template-react-router/app/lib/utils.ts
@@ -0,0 +1,6 @@
+import { clsx, type ClassValue } from "clsx";
+import { twMerge } from "tailwind-merge";
+
+export function cn(...inputs: ClassValue[]) {
+ return twMerge(clsx(inputs));
+}
diff --git a/packages/template-react-router/app/progress.tsx b/packages/template-react-router/app/progress.tsx
index 4ef02004ed..e308af7927 100644
--- a/packages/template-react-router/app/progress.tsx
+++ b/packages/template-react-router/app/progress.tsx
@@ -4,23 +4,14 @@ import {
speculateFunctionName,
} from "@remotion/lambda/client";
import type { StatusResponse } from "./lib/types";
-import { DISK, RAM, TIMEOUT } from "~/remotion/constants";
import { ActionFunction } from "react-router";
+import { errorAsJson } from "./lib/return-error-as-json";
+import { ProgressRequest } from "./remotion/schemata";
+import { DISK, RAM, TIMEOUT } from "./remotion/constants.mjs";
-export const action: ActionFunction = async ({ request }) => {
- const body = await request.formData();
- const renderId = body.get("renderId") as string;
- const bucketName = body.get("bucketName") as string;
- if (!renderId) {
- throw new Response(JSON.stringify({ error: "No renderId" }), {
- status: 400,
- });
- }
- if (!bucketName) {
- throw new Response(JSON.stringify({ error: "No bucketName" }), {
- status: 400,
- });
- }
+export const action: ActionFunction = errorAsJson(async ({ request }) => {
+ const body = await request.json();
+ const { bucketName, id } = ProgressRequest.parse(body);
const region = process.env.REMOTION_AWS_REGION as AwsRegion | undefined;
if (!region) {
@@ -29,7 +20,7 @@ export const action: ActionFunction = async ({ request }) => {
const { done, overallProgress, errors, outputFile } = await getRenderProgress(
{
- renderId,
+ renderId: id,
bucketName,
functionName: speculateFunctionName({
diskSizeInMb: DISK,
@@ -40,7 +31,7 @@ export const action: ActionFunction = async ({ request }) => {
},
);
const status: StatusResponse = {
- renderId,
+ renderId: id,
done,
overallProgress,
errors,
@@ -48,4 +39,4 @@ export const action: ActionFunction = async ({ request }) => {
};
return status;
-};
+});
diff --git a/packages/template-react-router/app/remotion/Root.tsx b/packages/template-react-router/app/remotion/Root.tsx
index 04baeeecb5..5c790d31bd 100644
--- a/packages/template-react-router/app/remotion/Root.tsx
+++ b/packages/template-react-router/app/remotion/Root.tsx
@@ -5,7 +5,7 @@ import {
COMPOSITION_HEIGHT,
COMPOSITION_ID,
COMPOSITION_WIDTH,
-} from "./constants";
+} from "./constants.mjs";
import { Main } from "./components/Main";
export const RemotionRoot = () => {
diff --git a/packages/template-react-router/app/remotion/components/Main.tsx b/packages/template-react-router/app/remotion/components/Main.tsx
index 807a323f60..97d6196d47 100644
--- a/packages/template-react-router/app/remotion/components/Main.tsx
+++ b/packages/template-react-router/app/remotion/components/Main.tsx
@@ -11,7 +11,7 @@ import { loadFont, fontFamily } from "@remotion/google-fonts/Inter";
import React, { useMemo } from "react";
import { Rings } from "./Rings";
import { TextFade } from "./TextFade";
-import { CompositionProps } from "../constants";
+import { CompositionProps } from "../schemata";
loadFont();
diff --git a/packages/template-react-router/app/remotion/constants.ts b/packages/template-react-router/app/remotion/constants.mjs
similarity index 62%
rename from packages/template-react-router/app/remotion/constants.ts
rename to packages/template-react-router/app/remotion/constants.mjs
index 103ade2620..48768d9ec8 100644
--- a/packages/template-react-router/app/remotion/constants.ts
+++ b/packages/template-react-router/app/remotion/constants.mjs
@@ -1,20 +1,11 @@
import { VERSION } from "remotion";
-import { z } from "zod";
export const COMPOSITION_FPS = 30;
export const DURATION_IN_FRAMES = 7 * COMPOSITION_FPS;
export const COMPOSITION_WIDTH = 1920;
export const COMPOSITION_HEIGHT = 1080;
export const COMPOSITION_ID = "LogoAnimation";
-export const RAM = 2048;
+export const RAM = 3009;
export const DISK = 10240;
export const TIMEOUT = 240;
export const SITE_NAME = "remotion-react-router-example-" + VERSION;
-
-export const CompositionProps = z.object({
- title: z.string(),
-});
-
-export const defaultMyCompProps: z.infer<typeof CompositionProps> = {
- title: "React Router and Remotion",
-};
diff --git a/packages/template-react-router/app/remotion/schemata.ts b/packages/template-react-router/app/remotion/schemata.ts
new file mode 100644
index 0000000000..4738f2ad91
--- /dev/null
+++ b/packages/template-react-router/app/remotion/schemata.ts
@@ -0,0 +1,33 @@
+import { z } from "zod";
+
+export const CompositionProps = z.object({
+ title: z.string(),
+});
+
+export const defaultMyCompProps: z.infer<typeof CompositionProps> = {
+ title: "React Router and Remotion",
+};
+
+export const RenderRequest = z.object({
+ inputProps: CompositionProps,
+});
+
+export const ProgressRequest = z.object({
+ bucketName: z.string(),
+ id: z.string(),
+});
+
+export type ProgressResponse =
+ | {
+ type: "error";
+ message: string;
+ }
+ | {
+ type: "progress";
+ progress: number;
+ }
+ | {
+ type: "done";
+ url: string;
+ size: number;
+ };
diff --git a/packages/template-react-router/app/render.tsx b/packages/template-react-router/app/render.tsx
new file mode 100644
index 0000000000..e62979fe7c
--- /dev/null
+++ b/packages/template-react-router/app/render.tsx
@@ -0,0 +1,20 @@
+import { ActionFunction } from "react-router";
+import { renderVideo } from "./lib/render-video.server";
+import { SITE_NAME, COMPOSITION_ID } from "./remotion/constants.mjs";
+import { errorAsJson } from "./lib/return-error-as-json";
+import { RenderRequest } from "./remotion/schemata";
+
+export const action: ActionFunction = errorAsJson(async ({ request }) => {
+ const formData = await request.json();
+ const { inputProps } = RenderRequest.parse(formData);
+
+ const renderData = await renderVideo({
+ serveUrl: SITE_NAME,
+ composition: COMPOSITION_ID,
+ inputProps,
+ outName: `logo-animation.mp4`,
+ metadata: null,
+ });
+
+ return renderData;
+});
diff --git a/packages/template-react-router/app/routes.ts b/packages/template-react-router/app/routes.ts
index fb2231bee0..5a0f699e85 100644
--- a/packages/template-react-router/app/routes.ts
+++ b/packages/template-react-router/app/routes.ts
@@ -1,10 +1,7 @@
-import {
- type RouteConfig,
- index,
- route,
-} from "@react-router/dev/routes";
+import { type RouteConfig, index, route } from "@react-router/dev/routes";
export default [
index("./home.tsx"),
- route("progress", "./progress.tsx")
-] satisfies RouteConfig
+ route("/api/lambda/progress", "./progress.tsx"),
+ route("/api/lambda/render", "./render.tsx"),
+] satisfies RouteConfig;
diff --git a/packages/template-react-router/deploy.mjs b/packages/template-react-router/deploy.mjs
new file mode 100644
index 0000000000..e099342340
--- /dev/null
+++ b/packages/template-react-router/deploy.mjs
@@ -0,0 +1,61 @@
+import {
+ deploySite,
+ getOrCreateBucket,
+ deployFunction,
+} from "@remotion/lambda";
+import dotenv from "dotenv";
+import path from "path";
+import { RAM, TIMEOUT, SITE_NAME, DISK } from "./app/remotion/constants.mjs";
+
+dotenv.config();
+
+const region = process.env.REMOTION_AWS_REGION;
+if (!region) {
+ throw new Error("REMOTION_AWS_REGION is not set");
+}
+
+if (!process.env.AWS_ACCESS_KEY_ID && !process.env.REMOTION_AWS_ACCESS_KEY_ID) {
+ console.log(
+ 'The environment variable "REMOTION_AWS_ACCESS_KEY_ID" is not set.',
+ );
+ console.log("Lambda renders were not set up.");
+ console.log(
+ "Complete the Lambda setup: at https://www.remotion.dev/docs/lambda/setup",
+ );
+ process.exit(0);
+}
+if (
+ !process.env.AWS_SECRET_ACCESS_KEY &&
+ !process.env.REMOTION_AWS_SECRET_ACCESS_KEY
+) {
+ console.log(
+ 'The environment variable "REMOTION_REMOTION_AWS_SECRET_ACCESS_KEY" is not set.',
+ );
+ console.log("Lambda renders were not set up.");
+ console.log(
+ "Complete the Lambda setup: at https://www.remotion.dev/docs/lambda/setup",
+ );
+ process.exit(0);
+}
+
+const { alreadyExisted, functionName } = await deployFunction({
+ createCloudWatchLogGroup: true,
+ memorySizeInMb: RAM,
+ region,
+ diskSizeInMb: DISK,
+ timeoutInSeconds: TIMEOUT,
+ logLevel: "verbose",
+});
+console.log(
+ `${alreadyExisted ? "Ensured" : "Deployed"} function "${functionName}"`,
+);
+
+const { bucketName } = await getOrCreateBucket({ region });
+const { serveUrl } = await deploySite({
+ siteName: SITE_NAME,
+ bucketName,
+ entryPoint: path.join(process.cwd(), "app/remotion/index.ts"),
+ region,
+});
+
+console.log(serveUrl);
diff --git a/packages/template-react-router/package.json b/packages/template-react-router/package.json
index 0cc5ec3a6d..47a28dbd3d 100644
--- a/packages/template-react-router/package.json
+++ b/packages/template-react-router/package.json
@@ -16,11 +16,14 @@
"*.css"
],
"dependencies": {
+ "clsx": "2.1.1",
"@react-router/node": "7.2.0",
"@react-router/serve": "7.2.0",
"@remotion/cli": "workspace:*",
"@remotion/lambda": "workspace:*",
"@remotion/player": "workspace:*",
+ "@remotion/shapes": "workspace:*",
+ "@remotion/paths": "workspace:*",
"@remotion/google-fonts": "workspace:*",
"isbot": "4.1.0",
"react": "19.0.0",
@@ -29,6 +32,7 @@
"react-router-dom": "7.2.0",
"remotion": "workspace:*",
"tailwindcss": "4.0.0",
+ "tailwind-merge": "3.0.1",
"@tailwindcss/cli": "4.0.0",
"@tailwindcss/vite": "4.0.0",
"vite": "^5.4.12",
diff --git a/packages/template-react-router/tsconfig.json b/packages/template-react-router/tsconfig.json
index 21dac797fa..7dd9e90748 100644
--- a/packages/template-react-router/tsconfig.json
+++ b/packages/template-react-router/tsconfig.json
@@ -1,5 +1,10 @@
{
- "include": ["**/*.ts", "**/*.tsx", ".react-router/types/**/*"],
+ "include": [
+ "**/*.ts",
+ "**/*.tsx",
+ ".react-router/types/**/*",
+ "app/remotion/constants.mjs"
+ ],
"compilerOptions": {
"lib": ["DOM", "DOM.Iterable", "ES2022"],
"isolatedModules": true,
@@ -24,5 +29,4 @@
"module": "ESNext"
},
"exclude": ["remotion.config.ts"]
-
}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index b02ecf18a4..a591361f8f 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -2761,15 +2761,24 @@ importers:
'@remotion/lambda':
specifier: workspace:*
version: link:../lambda
+ '@remotion/paths':
+ specifier: workspace:*
+ version: link:../paths
'@remotion/player':
specifier: workspace:*
version: link:../player
+ '@remotion/shapes':
+ specifier: workspace:*
+ version: link:../shapes
'@tailwindcss/cli':
specifier: 4.0.0
version: 4.0.0
'@tailwindcss/vite':
specifier: 4.0.0
version: 4.0.0([email protected])
+ clsx:
+ specifier: 2.1.1
+ version: 2.1.1
isbot:
specifier: 4.1.0
version: 4.1.0
@@ -2788,6 +2797,9 @@ importers:
remotion:
specifier: workspace:*
version: link:../core
+ tailwind-merge:
+ specifier: 3.0.1
+ version: 3.0.1
tailwindcss:
specifier: 4.0.0
version: 4.0.0