I’m working on a Next.js project that generates images using the Replicate.ai API. Although images are generated correctly on the Replicate.ai dashboard, the API response in my Next.js serverless function returns a ReadableStream
instead of the expected image URL.
API Route (route.jsx
):
import { NextResponse } from "next/server";
import Replicate from "replicate";
export async function POST(req) {
try {
const { prompt } = await req.json();
const replicate = new Replicate({
auth: process.env.REPLICATE_API_TOKEN
});
const input = {
prompt: prompt,
height: 1280,
width: 1024,
num_outputs: 1,
};
const output = await replicate.run(
"bytedance/sdxl-lightning-4step:5599ed30703defd1d160a25a63321b4dec97101d98b4674bcc56e41f62f35637",
{ input }
);
console.log("Generated Image:", output);
return NextResponse.json({ result: output[0] });
} catch (error) {
console.error("Error generating image:", error);
}
}
Frontend Function in page.jsx
:
const GenerateImage = async () => {
let images = [];
videoSCRIPT.forEach(async (element) => {
await axios.post('/api/generate-image', { prompt: element?.imagePrompt })
.then((resp) => {
console.log("Frontend Response:", resp.data.result);
images.push(resp.data.result);
});
});
console.log(images);
setImageList(images);
setLoading(false);
}
What I See in the Console:
Generated Image: [ ReadableStream { locked: false, state: ‘readable’, supportsBYOB: false } ] Frontend Response: {},{}
What I Expected:
-
The generated image URL to appear in the browser console and be passed back correctly.
Troubleshooting Steps Taken:
-
Checked the Replicate.ai dashboard—images are generated successfully.
-
Confirmed the API key and endpoint are correct.
-
2
Answers
change the replicate verion in package.json to
"replicate": "^0.33.0"
don’t forget npm install to apply the changes
Pass the
useFileOutput: false
option to theReplicate
constructor and you will get back the URL of the file instead of the file itself.