Guillem
Guillem

Reputation: 1

replicate flux api image missing "src" property

I've been having problems while generating a flux's image on NextJS. I have the Image is missing src property error. I've tried to look at Replicate's Flux documentation and they don't mention anything about the src property on NextJS.

My route code is:

import { NextRequest, NextResponse } from "next/server"
import Replicate from "replicate"

const replicate = new Replicate({
  auth: process.env.REPLICATE_API_TOKEN,
})

export async function POST(req: NextRequest) {
  try {
    const { prompt } = await req.json()

    if (!prompt) {
      return NextResponse.json({ error: "Prompt is required" }, { status: 400 })
    }

    const output = await replicate.run("black-forest-labs/flux-schnell", {
      input: {
        prompt,
        num_outputs: 1,
        aspect_ratio: "1:1",
        output_format: "webp",
        output_quality: 80,
        go_fast: true,
      },
    })

    return NextResponse.json({ output })
  } catch (error) {
    console.error("Error generating image:", error)
    return NextResponse.json(
      { error: "Failed to generate image" },
      { status: 500 }
    )
  }
}

And my page.tsx is:

"use client"

import { useState } from "react"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Card } from "@/components/ui/card"
import { Loader2 } from "lucide-react"
import Image from "next/image"

export default function ImageGenerator() {
  const [prompt, setPrompt] = useState("")
  const [imageUrl, setImageUrl] = useState<string | null>(null)
  const [error, setError] = useState<string | null>(null)
  const [isLoading, setIsLoading] = useState(false)

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault()
    setImageUrl(null)
    setError(null)
    setIsLoading(true)

    try {
      const response = await fetch("/api/replicate", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ prompt }),
      })

      const data = await response.json()

      if (response.ok && data.output) {
        setImageUrl(data.output[0])
      } else {
        setError(data.error || "Failed to generate image")
      }
    } catch (error) {
      console.error("Error generating image:", error)
      setError("An error occurred while generating the image")
    } finally {
      setIsLoading(false)
    }
  }

  return (
    <div className="max-w-md mx-auto mt-10 p-6">
      <Card className="p-6">
        <h1 className="text-2xl font-bold mb-4">Image Generator</h1>
        <form onSubmit={handleSubmit} className="space-y-4">
          <div>
            <label
              htmlFor="prompt"
              className="block text-sm font-medium text-gray-700 mb-1"
            >
              Enter your prompt
            </label>
            <Input
              type="text"
              id="prompt"
              value={prompt}
              onChange={(e) => setPrompt(e.target.value)}
              placeholder="A serene landscape with mountains and a lake"
              required
            />
          </div>
          <Button type="submit" disabled={isLoading}>
            {isLoading ? (
              <>
                <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                Generating...
              </>
            ) : (
              "Generate Image"
            )}
          </Button>
        </form>
        {error && <p className="mt-4 text-red-600">{error}</p>}
        {imageUrl && (
          <div className="mt-6 relative w-full aspect-square">
            <Image
              src={imageUrl}
              alt="Generated image"
              fill
              sizes="(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 33vw"
              className="rounded-lg shadow-lg object-cover"
            />
          </div>
        )}
      </Card>
    </div>
  )
}

How to resolve this issue?

Upvotes: 0

Views: 52

Answers (0)

Related Questions