Node.js is a good fit for image workflows because it can accept uploads, call an image API, and stream the result without blocking the server. This guide uses the FAPIhub REST API and returns a transparent PNG that you can store or send to a browser.
Install the dependencies
This example uses axios for HTTP requests and form-data to create a multipart upload.
npm install axios form-dataRemove one background
The API expects the image in a multipart field named image and your key in the ApiKey header.
const axios = require("axios");
const FormData = require("form-data");
const fs = require("fs");
async function removeBackground(inputPath, outputPath) {
const form = new FormData();
form.append("image", fs.createReadStream(inputPath));
const response = await axios.post(
"https://fapihub.com/v2/rembg/",
form,
{
headers: {
ApiKey: process.env.FAPIHUB_API_KEY,
...form.getHeaders(),
},
responseType: "arraybuffer",
timeout: 30000,
validateStatus: () => true,
}
);
if (response.status !== 200) {
throw new Error(`Background removal failed: HTTP ${response.status}`);
}
fs.writeFileSync(outputPath, response.data);
}
removeBackground("input.jpg", "output.png").catch(console.error);Handle uploads safely
Keep the API key on the server. Validate the MIME type and file size before creating the request, and generate the output filename yourself instead of trusting a client-provided path. For user-facing uploads, process the image in a queue so a slow request does not hold an HTTP connection open.
Process a directory
For a small batch, reuse the helper and limit concurrency. Sending hundreds of requests at once can trigger rate limits and increase memory usage.
const path = require("path");
async function processDirectory(inputDir, outputDir) {
fs.mkdirSync(outputDir, { recursive: true });
const files = fs.readdirSync(inputDir)
.filter((name) => /\.(jpe?g|png|webp)$/i.test(name));
for (const name of files) {
const inputPath = path.join(inputDir, name);
const outputPath = path.join(outputDir, `${path.parse(name).name}.png`);
await removeBackground(inputPath, outputPath);
console.log(`Processed ${name}`);
}
}
processDirectory("raw", "processed").catch(console.error);Next steps for production
Add retries with exponential backoff for temporary 5xx responses, record the original filename and API status in your job table, and use object storage for the resulting PNG. The same endpoint can then sit behind a product editor, catalog importer, or media-processing worker.
For a Python implementation, see our Python background removal API tutorial.