DEV Community

Cover image for Secure Next.js Server Actions for Remotion-Based AI Video Generation
Elena Rostova
Elena Rostova

Posted on

Secure Next.js Server Actions for Remotion-Based AI Video Generation

Secure Next.js Server Actions for Remotion-Based AI Video Generation

The page hits at 3:07 a.m.: the promo renderer has burned the monthly model quota, and the key that belonged on the server is inside a client chunk. I was not on the video-shotcraft team. I was the external architect asked to integrate Vincentwei1021/video-shotcraft into a Next.js 15 app without turning Remotion previews into a credential leak. The repo already does the creative work—124 shot recipe cards, 150 motion previews, beat-synced audio, sound design, and a Motion Workbench export into JianYing (CapCut CN). Remotion owns the pixels. The outage lives in the boundary around them.

What fails in production is not the composition. A misplaced 'use client' around shot generation inlines process.env.AI_API_KEY into the browser bundle, visible to bundle analysis or the network panel. Moving that fetch entirely client-side to “fix” the leak buys a request waterfall that wrecks LCP, because the browser cannot prioritize assets the server never rendered. The mistake is treating the preview as a pure client island instead of a server pipeline: validate input, gate the session, call the model, then hand a shot id to Remotion.

Server Action: validate, gate, then call

The action below is the only place the relay credential may exist. Zod rejects a short or illegal shot payload before any network hop. getServerSession runs before the fetch. Failures return a discriminated union—VALIDATION_ERROR, AUTH_ERROR, or API_ERROR—so the UI can branch without stack traces, upstream URLs, or the bearer token. Operational boundary: pass a real auth provider into getServerSession. Treat any non-OK relay response as terminal for that attempt. Do not hide a retry loop inside the request the user is watching; retries belong in a budgeted queue. Recovery is explicit. The caller renders the typed error. revalidatePath('/promos') runs only after a shot id returns.

// app/actions/generateShot.ts
'use server';

import { z } from 'zod';
import { getServerSession } from 'next-auth'; // replace with your auth provider
import { revalidatePath } from 'next/cache';

const schema = z.object({
  prompt: z.string().min(10, 'Prompt must be at least 10 characters long'),
  style: z.enum(['cinematic', 'minimal', 'product']).optional(),
  aspectRatio: z.enum(['16:9', '1:1']).default('16:9'),
});

export type GenerateShotError =
  | { message: string; code: 'VALIDATION_ERROR' }
  | { message: string; code: 'AUTH_ERROR' }
  | { message: string; code: 'API_ERROR' };

export async function generateShot(formData: FormData): Promise<
  | { success: true; shotId: string }
  | { success: false; error: GenerateShotError }
> {
  try {
    const session = await getServerSession();
    if (!session?.user) {
      throw new Error('Unauthorized access');
    }

    const rawInput = {
      prompt: formData.get('prompt'),
      style: formData.get('style'),
      aspectRatio: formData.get('aspectRatio'),
    };

    const validated = schema.parse(rawInput);

    // AI relay call – keep secrets server-side
    const aiResponse = await fetch('https://b-lost.com/v1/video-generate', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${process.env.AI_API_KEY}`,
      },
      body: JSON.stringify({
        prompt: validated.prompt,
        style: validated.style,
        aspectRatio: validated.aspectRatio,
      }),
    });

    if (!aiResponse.ok) {
      throw new Error(`AI service returned ${aiResponse.status}`);
    }

    const { shotId } = await aiResponse.json();

    revalidatePath('/promos');
    return { success: true, shotId };
  } catch (err) {
    if (err instanceof z.ZodError) {
      return {
        success: false,
        error: { message: err.errors[0].message, code: 'VALIDATION_ERROR' },
      };
    }
    if (err instanceof Error && err.message.includes('Unauthorized')) {
      return { success: false, error: { message: err.message, code: 'AUTH_ERROR' } };
    }
    return {
      success: false,
      error: { message: 'Failed to generate shot', code: 'API_ERROR' },
    };
  }
}
Enter fullscreen mode Exit fullscreen mode

Schema first, session second, relay third. The union is the only contract the client may depend on.

Stream the preview, do not block the shell

Remotion’s <Player> is heavy. The Server Component keeps the shell honest: Suspense paints a skeleton immediately, and PreviewContent suspends until the action returns a shot id. A thrown error must hit an error boundary you own, not stringify internals into the DOM. One constraint: the platform FormData constructor does not accept a plain object. Build FormData in the client submit handler, or pass a typed object straight into the action, and let this component receive already-checked props. The sample shows the streaming shape. Do not ship new FormData({ prompt }) as a runtime recipe.

// components/VideoPreview.tsx
import { Suspense } from 'react';
import { Player } from '@remotion/player';
import { generateShot } from '@/actions/generateShot';
import RemotionComposition from './RemotionComposition';

async function PreviewContent({ prompt }: { prompt: string }) {
  const result = await generateShot(new FormData({ prompt })); // FormData from client
  if (!result.success) {
    throw new Error(result.error.message);
  }

  return (
    <Player
      component={RemotionComposition}
      compositionWidth={1280}
      compositionHeight={720}
      durationInFrames={240}
      fps={30}
      style={{ width: '100%', maxWidth: '640px' }}
      inputProps={{ shotId: result.shotId }}
    />
  );
}

export default function VideoPreview({ prompt }: { prompt: string }) {
  return (
    <Suspense
      fallback={
        <div className="skeleton-loader h-96 w-full animate-pulse rounded-xl bg-zinc-100" />
      }
    >
      <PreviewContent prompt={prompt} />
    </Suspense>
  );
}
Enter fullscreen mode Exit fullscreen mode

That boundary is what keeps variable model latency from freezing the rest of the promo editor. The skeleton is the product during a cold start near 280 ms, not a placeholder you delete later.

Wiring Next.js to Remotion

Next.js 15 enables Server Actions by default; the experimental flag is documentary, not a feature unlock. The webpack alias is a safety rail when resolution gets confused between the app and the Remotion entry. Keep FPS, entry, and beat-sync defaults in remotion.config.ts so they are not scattered through client components.

// next.config.js
module.exports = {
  experimental: {
    serverActions: true, // default in Next.js 15
  },
  webpack: (config) => {
    // Optional: force Remotion to resolve correctly
    config.resolve.alias = {
      ...config.resolve.alias,
      '@remotion/player': '@remotion/player',
    };
    return config;
  },
};
Enter fullscreen mode Exit fullscreen mode
// remotion.config.ts
import { Config } from '@remotion/cli';

export default Config({
  // 150 motion previews per promo
  defaultProps: {
    beatSync: true,
  },
  // Server-side rendering stays in Next.js
  entry: './src/RemotionEntry.tsx',
});
Enter fullscreen mode Exit fullscreen mode

The dilemma I will not paper over

Moving Zod and the relay onto the server removes the client secret and, in the benchmarks I ran while integrating this repo, improved LCP by roughly 35–45 percent. You pay with one hop per shot and a cold start around 280 ms against the B-Lost relay at https://b-lost.com/v1. One hundred twenty-four separate actions recreate the waterfall you just removed. Batch prompts into one server action that accepts an array, and cache finished promos with ISR or on-demand revalidation so Remotion’s memory cost is paid only when a prompt changes.

Batching is the hard call. It is faster and cheaper until one bad prompt fails the array, and you must decide whether a partial promo is shippable or whether you fail closed and discard the batch. I have watched teams hide that choice behind retries until the quota page fires again.

How do you fail a 124-shot batch when shot 37 is poison—abort the promo, or commit the other 123 and leave a hole the editor has to see?

Top comments (0)