Prepare a server-side project
Use Node.js 20 or later, and store BGFREE_API_KEY in your deployment secrets. Never expose this value through a NEXT_PUBLIC_ variable or client bundle.
Upload an image
import { readFile, writeFile } from "node:fs/promises";
const bytes = await readFile("photo.jpg");
const form = new FormData();
form.set("image_file", new Blob([bytes], { type: "image/jpeg" }), "photo.jpg");
const response = await fetch("https://api.bgfree.app/v1.0/removebg", {
method: "POST",
headers: { "X-Api-Key": process.env.BGFREE_API_KEY },
body: form,
signal: AbortSignal.timeout(90_000),
});
if (!response.ok) throw new Error(`bgfree request failed: ${response.status} ${await response.text()}`);
await writeFile("cutout.png", Buffer.from(await response.arrayBuffer()));
Integrate with care
Handle non-2xx responses as errors, keep request IDs from response headers for diagnostics, and avoid logging image bodies or credentials. This request handles one image; build your own queue with bounded concurrency if needed.