Skip to content
Guides

Next.js AI Image Generation With a Server Route

Nextjs AI image generation done safely: a route handler that holds the key, progress in the page, files served from your domain, and webhooks for video.

Updated 5 min read

Next.js AI image generation belongs on the server: a route handler receives the prompt from your page, calls the image API with a key the browser never sees, and hands back only an id to watch. On Frameport that route reaches Nano Banana Pro, Frameport Image 1 and every other image model with one key, and the same pattern, plus a webhook, runs video models such as Frameport Motion 1.

This guide builds it in the App Router: the architecture, a route that submits, a page that shows progress, a route that serves the files from your own domain, and a webhook receiver for video clips.

Next.js AI image generation: the architecture

The browser never calls the API. Your key spends your balance, and anything in client code, including any variable prefixed NEXT_PUBLIC_, ships to every visitor. So three server routes sit between the page and the API:

RouteWhat it does
POST /api/imagesChecks the user, validates the prompt, submits the generation, remembers who asked
GET /api/images/[id]Reads the generation for its owner, returns its status and image paths
GET /api/images/[id]/file/[index]Streams one image from the API, so the page never handles signed links

The key lives in .env.local as FRAMEPORT_API_KEY, without the public prefix, and one server-only module is the only code that reads it:

lib/ai.ts
import 'server-only' // npm install server-only: importing this from a client component fails the build

export function api(path: string, init: RequestInit = {}): Promise<Response> {
  return fetch(`https://frameport.ai/v1${path}`, {
    ...init,
    cache: 'no-store',
    headers: {
      'Authorization': `Bearer ${process.env.FRAMEPORT_API_KEY}`,
      'Content-Type': 'application/json',
      ...init.headers,
    },
  })
}

Each generation id is stored with the user who started it, and every read checks that link; otherwise one user could watch another's images by guessing ids. Swap this sketch for your database and your auth:

lib/jobs.ts
import 'server-only'
import { cookies } from 'next/headers'

const owners = new Map<string, string>() // generation id → user id: use your database

export async function currentUser(): Promise<string | null> {
  return (await cookies()).get('session')?.value ?? null // use your auth
}
export const remember = (id: string, user: string) => owners.set(id, user)
export const owns = (id: string, user: string) => owners.get(id) === user

A route handler that submits

The route refuses what it should before anything is spent, then sends the request with a max_cost_usd cap, so no single call can cost more than you planned:

app/api/images/route.ts
import { api } from '@/lib/ai'
import { currentUser, remember } from '@/lib/jobs'

export async function POST(request: Request) {
  const user = await currentUser()
  if (!user) return Response.json({ message: 'Sign in first.' }, { status: 401 })

  const { prompt } = await request.json()
  if (typeof prompt !== 'string' || !prompt.trim() || prompt.length > 2400) {
    return Response.json({ message: 'Write a prompt of up to 2,400 characters.' }, { status: 400 })
  }

  const res = await api('/images/generations', {
    method: 'POST',
    body: JSON.stringify({ model: 'fp-image-1', prompt, n: 2, max_cost_usd: 0.05 }),
  })
  const gen = await res.json()
  if (gen.error) return Response.json({ message: gen.error.message }, { status: res.status })

  remember(gen.id, user)
  return Response.json({ id: gen.id }, { status: 202 })
}

Two images on Frameport Image 1 cost $0.05, and an image that fails is not charged. To switch to Nano Banana Pro, change the model and the cap; the body is the same for every image model (images reference). A server action ('use server') can do the same job, but it is a public endpoint just like a route, so it needs the same user check. If your server retries a submit after a timeout, send an Idempotency-Key header so the retry returns the first generation instead of a second one (idempotency keys).

Showing progress

The page polls your route, never the API. A read every two seconds, the low end of the interval the docs suggest, shows each image soon after it is ready:

app/generate/page.tsx
'use client'
import { type FormEvent, useState } from 'react'

type Job = { status: string; images: string[]; message: string | null }

export default function Generate() {
  const [prompt, setPrompt] = useState('')
  const [job, setJob] = useState<Job | null>(null)
  const busy = job?.status === 'queued' || job?.status === 'running'

  async function submit(event: FormEvent) {
    event.preventDefault()
    setJob({ status: 'queued', images: [], message: null })
    const res = await fetch('/api/images', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ prompt }),
    })
    const started = await res.json()
    if (!res.ok) return setJob({ status: 'failed', images: [], message: started.message })

    let current: Job
    do {
      await new Promise(resolve => setTimeout(resolve, 2000))
      current = await fetch(`/api/images/${started.id}`).then(r => r.json())
      setJob(current)
    } while (current.status === 'queued' || current.status === 'running')
  }

  return (
    <form onSubmit={submit}>
      <textarea value={prompt} onChange={event => setPrompt(event.target.value)} maxLength={2400} />
      <button disabled={busy}>{busy ? 'Generating…' : 'Generate'}</button>
      {job?.message && <p>{job.message}</p>}
      {job?.images.map(src => <img key={src} src={src} alt="" width={512} height={512} />)}
    </form>
  )
}

The read route turns the generation into what the page needs and nothing more:

app/api/images/[id]/route.ts
import { api } from '@/lib/ai'
import { currentUser, owns } from '@/lib/jobs'

export async function GET(_request: Request, { params }: { params: Promise<{ id: string }> }) {
  const { id } = await params
  const user = await currentUser()
  if (!user || !owns(id, user)) return Response.json({ message: 'Not found.' }, { status: 404 })

  const res = await api(`/generations/${id}`)
  if (!res.ok) return Response.json({ message: 'Try again in a moment.' }, { status: 503 })
  const gen = await res.json()

  return Response.json({
    status: gen.status, // queued, running, succeeded or failed
    images: gen.outputs.flatMap((output: { status: string }, index: number) =>
      output.status === 'succeeded' ? [`/api/images/${id}/file/${index}`] : []),
    message: gen.status === 'failed' ? gen.error.message : null,
  })
}

Reads cost nothing and do not count against the workspace's 60 requests a minute, which only counts requests that start work.

Serving the file

Each output has a signed url that works without a key for about an hour, which is awkward to hand to a page that may stay open longer. Instead, stream the bytes through your own route from GET /v1/generations/{id}/content/{index}, which reads the output at that position with your key:

app/api/images/[id]/file/[index]/route.ts
import { api } from '@/lib/ai'
import { currentUser, owns } from '@/lib/jobs'

export async function GET(_request: Request, { params }: { params: Promise<{ id: string; index: string }> }) {
  const { id, index } = await params
  const user = await currentUser()
  if (!user || !owns(id, user) || !/^[0-3]$/.test(index)) return new Response('Not found', { status: 404 })

  const file = await api(`/generations/${id}/content/${index}`)
  if (!file.ok) return new Response(null, { status: file.status === 409 ? 409 : 404 })
  return new Response(file.body, {
    headers: {
      'Content-Type': file.headers.get('content-type') ?? 'image/png',
      'Cache-Control': 'private, max-age=86400',
    },
  })
}

The image now lives at a stable path on your domain, behind your auth, and the body streams through without being held in memory. A 409 means the file is not ready yet. Files are not kept forever, though: copy the images users keep to your own storage (S3, R2, your CDN) once they succeed, and serve those copies.

Webhooks for video

For video, let the API call you rather than keep a page polling for the whole render. Submit from a route as above (/videos/generations with fp-motion-1, a duration, a resolution and an aspect_ratio), then add an endpoint under Webhooks in the dashboard. Each delivery is a signed POST with the generation in data; verify it on the raw body and answer fast:

app/api/hooks/generations/route.ts
import { createHmac, timingSafeEqual } from 'node:crypto'
import { after } from 'next/server'

export const runtime = 'nodejs'

function verified(raw: string, header: string | null): boolean {
  const parts = Object.fromEntries((header ?? '').split(',').map(part => part.trim().split('=')))
  if (!parts.t || !parts.v1 || Math.abs(Date.now() / 1000 - Number(parts.t)) > 300) return false
  const expected = createHmac('sha256', process.env.WEBHOOK_SECRET!).update(`${parts.t}.${raw}`).digest('hex')
  return expected.length === parts.v1.length && timingSafeEqual(Buffer.from(expected), Buffer.from(parts.v1))
}

async function settle(gen: { id: string; status: string; cost_usd: number | null }) {
  console.log(gen.id, gen.status, gen.cost_usd) // mark the job in your database, copy the file, notify the user
}

export async function POST(request: Request) {
  const raw = await request.text() // the exact text that was signed
  if (!verified(raw, request.headers.get('Frameport-Signature'))) return new Response('Bad signature', { status: 400 })
  const event = JSON.parse(raw)
  after(() => settle(event.data)) // runs once the response is sent
  return new Response(null, { status: 204 })
}

Answer within 10 seconds: a delivery without a 2xx is retried after 1, 5 and 15 minutes with the same delivery id, so make settle safe to run twice. An endpoint covers every generation of the workspace, Studio runs included, so ignore ids your database does not know. The endpoint must be a public https URL; in development, expose your local server through a tunnel. A delivery goes out when the job closes, which a read or a background check that runs every minute triggers, so keep a slow poll for jobs that stay quiet too long (polling vs webhooks).

A Frameport Motion 1 clip of 5 seconds at 768p costs $0.30, with sound on or off at the same price. For the parts of a larger product, such as per-user budgets, storage and pricing, see how to build an AI video app; the webhooks reference has every header, and the image generation API JavaScript guide covers the same calls outside a framework.

FAQ

How do I add AI image generation to a Next.js app?

Put the API call in a route handler or a server action, read the key from a server-only environment variable, and let your page call that route. The route returns a generation id; the page polls a second route for the status and shows the images through a third that streams the files.

Can I call the image API from a React component?

Not with your key. A client component ships to the browser, and so does any NEXT_PUBLIC_ variable. Keep the key in server code and let the component call your own route.

Is there a free image generation API for Next.js?

The account, the API key and price quotes are free, and an image that fails costs nothing. Images are paid from a prepaid balance with no subscription, from $0.025 each on Frameport Image 1.

Do I need next/image for generated images?

No. A plain img pointing at your file route works, since the route already serves the right type and cache headers. If you use next/image, point it at your own route or storage rather than the signed links, which expire.

Can I use Grok Imagine or Nano Banana Pro from Next.js?

Yes, with the same route: change model to grok-imagine-2-0 or nano-banana-pro and adjust max_cost_usd. One key and one balance cover every model in the catalog.

Start building.

Your API key is free. Top up from $10 when you are ready.