Skip to main content

Create a Simple Hugging Face Endpoint

  • NextJS
  • Requires you have a Hugging Face Key
  • installation: npm i @huggingface/inference

Code​

  • The below returns a blob of the image
import { HfInference } from "@huggingface/inference";
const { Readable } = require("stream");

export default async function handler(req, res) {
try {
const { prompt } = req.query;
const hf = new HfInference(process.env["HUGGING_FACE_KEY"]);
console.log(`ai image generation prompt ${prompt}`);
const response = await hf.textToImage({
inputs: `${prompt}`,
model: [YOUR_MODEL],
parameters: {
negative_prompt: "blurry",
},
});

const buffer = await response.arrayBuffer();
const readableInstanceStream = new Readable({
read() {
this.push(Buffer.from(buffer));
this.push(null);
},
});

res.statusCode = 200;
res.setHeader("Content-Type", "image/jpeg");
readableInstanceStream.pipe(res);
} catch (error) {
console.error(error);
res.status(500).send("An error occurred while generating the image.");
}
}