Next.js to production AI video generation: complete 2027 workflow
Add AI video generation to a Next.js app: keep the token server-side, submit async jobs from Route Handlers, store every MP4, and log cost per job.

A Next.js AI video generation workflow is a server-side route in your Next.js app that takes a prompt from the UI, starts a video job with a secret token, stores the MP4, and returns a URL the page can play. Start with Prodia when you want a documented video model such as LTX 2 Pro behind one endpoint, with an official AI SDK provider (@ai-sdk/prodia) or a plain fetch, plus per-job cost and an async API for long jobs. Compare fal, Replicate, Runway, Luma, and Stability AI for catalog breadth, custom models, or first-party APIs.
This guide is for developers shipping video generation inside a Next.js App Router app: a “generate” button, a product-clip feature, or a backend that creates short videos for content. It covers the parts that break in production: secrets, timeouts, storage, and cost. Video jobs commonly run longer than a single serverless request, so the production path uses Prodia’s async API.
Bottom line
- Start with Prodia if you want LTX 2 Pro and other documented video job types, callable from a Route Handler with
fetchto the async API, or through@ai-sdk/prodia. - Consider fal or Replicate if you want a wide hosted catalog or a community or custom model; both also have AI SDK providers.
- Consider Runway or Luma if you want that lab’s models through its first-party API.
- Consider Stability AI if your team is standardized on Stability’s official APIs and a current video endpoint is in their docs.
- Never call the video API from the browser. Keep the token server-side, start the job asynchronously, store every MP4, and return your own URL.
Key facts
- Prodia’s official AI SDK provider is
@ai-sdk/prodia. It readsPRODIA_TOKENby default and exposesprodia.video()for the AI SDK’sexperimental_generateVideo(AI SDK Prodia provider, generateVideo). - This guide uses LTX 2 Pro (
inference.ltx-2-pro.txt2vid.v1) on the direct async API for the production example. Its published price is about $0.019. - Prodia’s docs say to keep the token on the server, in an environment variable, and never in browser code (getting started).
- The async API returns a job ID immediately. Its docs recommend it for video and for serverless platforms with short request limits. Async outputs expire one hour after the job finishes (polling async jobs).
- Provider and Next.js details reflect public documentation checked in November 2026. No cross-provider quality or speed ranking is claimed.
What production AI video generation in Next.js means
A demo holds one HTTP request open until a clip arrives. A production feature has to answer five more questions:
- Where does the token live? On the server only. In Next.js, any variable prefixed with
NEXT_PUBLIC_is bundled for the browser, so the video API token must never use that prefix (Next.js environment variables). - Where does the call run? In a Route Handler (
app/api/.../route.ts) or a Server Action (Route Handlers). - What if it takes too long? Do not rely on raising
maxDurationalone. Submit an async job, store the job ID, and poll or resume from a later request (maxDuration, polling async jobs). - Where does the video go? Into storage you own, so the URL keeps working after a refresh and you never pay to generate the same clip twice. Copy the file before the one-hour async expiry.
- Who can trigger it? Signed-in users, with limits per user, because each job costs money and takes time.
It is not:
- Client-side generation. Calling the API from a Client Component exposes the token.
- A model. Next.js is the app framework. The model runs on the video API’s infrastructure.
- A finished editor. The API returns a short MP4. You still handle playback, review, and any later edits in the app.
Video APIs for Next.js at a glance
| Provider | Best for | How you call it from Next.js | Trade-offs |
|---|---|---|---|
| Prodia | LTX 2 Pro and other documented video job types, with cost per job | Direct fetch to /v2/job/async (recommended), or @ai-sdk/prodia with experimental_generateVideo |
You pick a job type and follow its schema; the async path is the production default |
| fal | A wide hosted catalog behind one key | @ai-sdk/fal, or fal’s client and queue API with webhooks |
Each endpoint has its own schema and price |
| Replicate | Community or custom models | @ai-sdk/replicate, or the predictions API |
Billing and schemas vary by model; pin the version |
| Runway | Runway’s own video models | Runway’s task API from a Route Handler; poll GET /v1/tasks/{id} |
Runway’s models and API only |
| Luma | Luma’s own video models | Luma’s first-party API from a Route Handler | Luma’s models only |
| Stability AI | Official Stability APIs, if a current video endpoint is documented | Stability’s REST API from a Route Handler | Confirm today’s video endpoints before you integrate |
Disclosure: Prodia publishes this guide and sells image and video inference API access, so Prodia is listed first. Provider details come from each provider’s public documentation and package registry. Test every option in your own app.
Best video APIs for Next.js, by use case
Prodia: best for a documented video job type you can poll from a Route Handler
Prodia is a managed inference API for image and video. For a Next.js app, the documented pieces that matter are:
- A single REST contract. Every model runs through
POST https://inference.prodia.com/v2/joborPOST /v2/job/asyncwith a jobtypeandconfig. This guide usesinference.ltx-2-pro.txt2vid.v1because it is documented and a live async submit returned HTTP 201 on 23 November 2026. - Async jobs. Create the job, persist the
id, polljob.state.currentuntilprocessedorfailed, then downloadoutput/video.mp4(polling async jobs). - Cost.
?price=truereturns the dollar amount for the job. Prodia’s published LTX price is about $0.019, and MiniMax H3 Turbo is about $0.073. This example uses LTX 2 Pro.
Best for: Next.js teams that want production video generation without managing GPUs, and an async flow that survives short function limits.
Trade-offs: you must pick a job type that the live API accepts and copy the MP4 to storage before it expires.
fal: best for a wide hosted catalog
fal hosts a large catalog of video endpoints behind one key, with a queue API that supports polling, cancellation, and webhooks. An AI SDK provider, @ai-sdk/fal, is also published.
Best for: apps that let users pick between many models.
Trade-offs: each endpoint has its own schema and price.
Replicate: best for community or custom models
Replicate runs official and community models through a predictions API and lets you deploy a custom model with Cog. @ai-sdk/replicate is the AI SDK provider.
Best for: apps built around a specific video model or a fine-tune.
Trade-offs: billing and request schemas vary by model. Pin the exact version you deploy.
Runway: best for Runway’s models
Runway’s developer API starts a task and has you poll GET /v1/tasks/{id}. Call it from a Route Handler with the required version header. Never put RUNWAYML_API_SECRET in a NEXT_PUBLIC_ variable.
Best for: teams that want Runway’s models through Runway’s API.
Trade-offs: Runway’s models and task API only.
Luma: best for Luma’s models
Luma publishes a first-party API for its video models. Call it from a Route Handler, not the browser.
Best for: apps that have chosen Luma’s models.
Trade-offs: Luma’s models only.
Stability AI: best when you already use Stability’s official APIs
The Stability AI Platform API is the official commercial API. Confirm the current video endpoint in the docs before you write the route.
Best for: teams already standardized on Stability.
Trade-offs: video endpoint names have changed across product lines.
How to add production AI video generation to a Next.js app
1. Store the token server-side (5 minutes)
Create a token in the Prodia API Dashboard (a Pro subscription is required for v2 tokens). Add it to .env.local for development and to your host’s environment settings for production, without a NEXT_PUBLIC_ prefix.
# .env.local
PRODIA_TOKEN=your-token-here
Done when process.env.PRODIA_TOKEN is defined in a Route Handler and undefined in the browser.
2. Submit an async LTX 2 Pro job from a Route Handler (30 to 60 minutes)
The pattern below follows Prodia’s polling async jobs guide. Split “create” and “poll” into two routes so no single serverless invocation has to last for the whole generation.
// app/api/video/route.ts
export const maxDuration = 30;
export async function POST(req: Request) {
// Check the user's session and per-user limit here before spending anything.
const { prompt } = await req.json();
if (typeof prompt !== "string" || prompt.length < 3 || prompt.length > 2000) {
return Response.json({ error: "Invalid prompt" }, { status: 400 });
}
const res = await fetch("https://inference.prodia.com/v2/job/async?price=true", {
method: "POST",
headers: {
Authorization: `Bearer ${process.env.PRODIA_TOKEN}`,
"Content-Type": "application/json",
Accept: "application/json",
},
body: JSON.stringify({
type: "inference.ltx-2-pro.txt2vid.v1",
config: { prompt },
}),
});
if (res.status !== 201) {
return Response.json(
{ error: `Prodia ${res.status}: ${await res.text()}` },
{ status: 502 },
);
}
const job = await res.json();
// Persist job.id, the user id, and the prompt in your database here.
return Response.json({ jobId: job.id, state: job.state?.current });
}
Done when a POST to /api/video returns a jobId and that id is stored in your database. A live submit of this job type returned HTTP 201 on 23 November 2026.
3. Poll the job and store the MP4 (30 to 60 minutes)
// app/api/video/[id]/route.ts
import { saveVideo } from "@/lib/storage"; // your object storage helper
export const maxDuration = 30;
export async function GET(
_req: Request,
{ params }: { params: Promise<{ id: string }> },
) {
const { id } = await params;
// Look up the job id in your database and confirm it belongs to the current user.
const stateRes = await fetch(
`https://inference.prodia.com/v2/job/async/${id}/job.state.current`,
{ headers: { Authorization: `Bearer ${process.env.PRODIA_TOKEN}` } },
);
if (!stateRes.ok) {
return Response.json({ error: `Status ${stateRes.status}` }, { status: 502 });
}
const state = (await stateRes.text()).trim();
if (state === "processing") {
return Response.json({ state });
}
if (state !== "processed") {
return Response.json({ state }, { status: 500 });
}
const fileRes = await fetch(
`https://inference.prodia.com/v2/job/async/${id}/output/video.mp4`,
{ headers: { Authorization: `Bearer ${process.env.PRODIA_TOKEN}` } },
);
if (!fileRes.ok) {
return Response.json({ error: `Download ${fileRes.status}` }, { status: 502 });
}
const bytes = new Uint8Array(await fileRes.arrayBuffer());
const url = await saveVideo(`generated/${id}.mp4`, bytes, "video/mp4");
// Save `url` on the job row. Optionally DELETE the async job resources after you have the file.
return Response.json({ state, url });
}
saveVideo is your own helper for the object storage you already use. It should upload the bytes and return a public or signed URL. Poll from the client every one to two seconds at first, then back off, as the async guide suggests. Done when a job that runs longer than your function limit still lands in storage and the playback URL works after a redeploy.
4. Call the routes from the UI (15 minutes)
// app/generate/page.tsx
"use client";
import { useState } from "react";
export default function Generate() {
const [url, setUrl] = useState<string | null>(null);
const [status, setStatus] = useState<string>("idle");
async function onSubmit(formData: FormData) {
setStatus("starting");
const started = await fetch("/api/video", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ prompt: formData.get("prompt") }),
});
const { jobId } = await started.json();
if (!jobId) {
setStatus("error");
return;
}
setStatus("processing");
for (let i = 0; i < 60; i++) {
await new Promise((r) => setTimeout(r, 2000));
const poll = await fetch(`/api/video/${jobId}`);
const data = await poll.json();
if (data.url) {
setUrl(data.url);
setStatus("done");
return;
}
if (data.state && data.state !== "processing") {
setStatus(data.state);
return;
}
}
setStatus("timeout");
}
return (
<form action={onSubmit}>
<input name="prompt" required minLength={3} maxLength={2000} />
<button disabled={status === "starting" || status === "processing"}>
{status === "processing" ? "Generating…" : "Generate"}
</button>
{url && <video src={url} controls width={640} />}
</form>
);
}
Done when the clip plays from your storage URL and the token never appears in the browser’s network tab.
5. Add limits and a cost log (30 minutes)
Limit requests per signed-in user in the create route. Store the job ID, prompt, and user with every clip, and use ?price=true on the create call to log cost (cost tracking). Done when you can answer “who generated this, with which prompt, and what did it cost” for any clip.
Common mistakes with AI video generation in Next.js
- Prefixing the token with
NEXT_PUBLIC_. Next.js bundles it into client JavaScript. Fix: no prefix, and read it only in Route Handlers or Server Actions. - Holding one request open until the video finishes. Serverless platforms time out. Fix: async create, persist the job ID, poll from a later request, and copy the MP4 to your storage.
- Returning a Prodia async URL and never storing the file. Outputs expire one hour after the job finishes. Fix: download and save as soon as the state is
processed. - Budgeting from a guess. Don’t assume one model’s price applies to another. Use the provider’s published price or the amount
?price=truereturns for that job.
Who this is not for
- Apps that only need still images. Use the image-generation Route Handler pattern instead; it can often stay on a single synchronous request.
- Teams that need a built-in timeline editor. This workflow returns an MP4. Editing stays in your product or in a separate tool.
- Projects that cannot store files. If you have no object storage, you will lose the clip when the async output expires.
FAQ
What is a Next.js AI video generation workflow?
It is a server-side route that accepts a prompt, starts a video job with a secret token, stores the MP4, and returns a URL for the page to play. The browser never sees the API token.
Can I use image-to-video from Next.js?
Yes. Use a documented img2vid job type such as inference.ltx-2-pro.img2vid.v1, send the still as a multipart input, and keep the same async poll-and-store flow.
How long will a job take?
It depends on the model, duration, and resolution. Measure wall time in your app. This guide does not publish a benchmark. Design for async either way.
How much does it cost?
Log ?price=true. Prodia’s published prices are about $0.019 for LTX and about $0.073 for H3 Turbo. Other models are not priced here.
Should I set a very high maxDuration instead of using async?
No. A higher limit might cover a short job and will still fail on a slow one, a retry, or a platform cap. Persist the job ID and poll.
Can I generate video from a Server Action instead of a Route Handler?
Yes, as long as the action stays on the server, the token is not prefixed with NEXT_PUBLIC_, and long work still goes through the async API.
Next step
Create a token in the Prodia API Dashboard, add PRODIA_TOKEN to .env.local without a public prefix, and ship the two-route async flow with inference.ltx-2-pro.txt2vid.v1. Store the first MP4 you generate, and only then open the button to users.