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);Use built-in fetch on Node 18 and newer
If you would rather not add dependencies, Node 18 ships fetch, FormData, and Blob as globals. The request is the same multipart upload: the file goes in the image field and the key goes in the ApiKey header. Do not set Content-Type yourself, because fetch has to generate the multipart boundary. The examples in this section use ES modules, so set "type": "module" in package.json or use the .mjs extension.
import { readFile, writeFile } from "node:fs/promises";
import path from "node:path";
const API_URL = "https://fapihub.com/v2/rembg/";
export async function removeBackground(inputPath, outputPath, { model } = {}) {
const bytes = await readFile(inputPath);
const form = new FormData();
form.append("image", new Blob([bytes]), path.basename(inputPath));
if (model) form.append("model", model); // falcon (default), aurora, or ghost
const response = await fetch(API_URL, {
method: "POST",
headers: { ApiKey: process.env.FAPIHUB_API_KEY },
body: form,
signal: AbortSignal.timeout(30_000),
});
if (!response.ok) {
throw await toApiError(response);
}
// The body is the PNG itself: no JSON wrapper and no second download.
await writeFile(outputPath, Buffer.from(await response.arrayBuffer()));
}The API accepts JPEG, PNG, WebP, BMP, and GIF input up to 10 MB per image, so you can widen the extension filter in the directory example above if your sources include BMP or GIF files.
Turn error responses into useful exceptions
Successful responses are binary, but errors come back as JSON with a machine-readable code, a message, and a request ID. Parse that body instead of throwing a bare status number, so your logs say why a job failed and support can trace a specific request.
| Status | Code | Meaning | What your code should do |
|---|---|---|---|
| 400 | invalid_image | The file is not a valid image or a parameter is wrong | Mark the job failed and show the user a clear message. Do not retry. |
| 401 | invalid_api_key | Missing, wrong, or deactivated key | Stop processing and alert whoever owns the configuration. |
| 402 | insufficient_credits | The plan's quota is used up | Pause the queue and upgrade the plan or wait for the next billing period. |
| 429 | rate_limit_exceeded | Too many requests in the current minute | Wait for the number of seconds in Retry-After, then retry. |
| 5xx | varies | Server-side problem | Retry with backoff. 5xx responses are not counted against your quota. |
export class FapihubError extends Error {
constructor({ status, code, message, requestId, retryAfter }) {
super(`${status} ${code}: ${message}`);
this.status = status;
this.code = code;
this.requestId = requestId;
this.retryAfter = retryAfter;
}
get retryable() {
return this.status === 429 || this.status >= 500;
}
}
async function toApiError(response) {
let error = {};
try {
error = (await response.json()).error ?? {};
} catch {
// Some 5xx responses may not have a JSON body.
}
return new FapihubError({
status: response.status,
code: error.code ?? "unknown",
message: error.message ?? response.statusText,
requestId: error.request_id,
retryAfter: Number(response.headers.get("Retry-After")) || null,
});
}Retry the failures that can succeed
Only two classes of failure are worth repeating: rate limiting and server-side or network errors. Everything else in the 4xx range will fail the same way on the next attempt, and because successful requests and 4xx errors both count toward your quota, blind retries of a bad file waste requests. A small wrapper keeps that policy in one place.
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
export async function withRetry(task, { attempts = 4 } = {}) {
for (let attempt = 0; ; attempt++) {
try {
return await task();
} catch (err) {
// Timeouts and connection errors are not FapihubError instances.
const retryable = !(err instanceof FapihubError) || err.retryable;
if (!retryable || attempt === attempts - 1) throw err;
const delaySeconds = err.retryAfter ?? 2 ** attempt;
await sleep(delaySeconds * 1000);
}
}
}
await withRetry(() => removeBackground("input.jpg", "output.png"));Process a batch with bounded concurrency
The sequential loop above is safe but slow for large folders. Every plan has a per-minute rate limit, so the goal is a fixed number of requests in flight, not one request per file. The helper below runs a configurable number of workers that pull from a shared list. Start with a low number such as 3 or 4, watch for 429 responses, and raise it only if you stay well under the limit.
import { readdir, mkdir } from "node:fs/promises";
async function processDirectory(inputDir, outputDir, concurrency = 4) {
await mkdir(outputDir, { recursive: true });
const queue = (await readdir(inputDir))
.filter((name) => /\.(jpe?g|png|webp|bmp|gif)$/i.test(name));
const failures = [];
async function worker() {
while (queue.length > 0) {
const name = queue.shift();
const output = path.join(outputDir, `${path.parse(name).name}.png`);
try {
await withRetry(() => removeBackground(path.join(inputDir, name), output));
console.log(`Processed ${name}`);
} catch (err) {
failures.push({ name, code: err.code ?? "network", requestId: err.requestId });
}
}
}
await Promise.all(Array.from({ length: concurrency }, worker));
return failures;
}Returning the failures instead of stopping on the first one lets you write a report, fix the bad inputs, and rerun only those files. For a deeper look at batch sizing, see our bulk background removal guide.
Accept uploads in an Express route
A common pattern is a server endpoint that receives an image from your own frontend, forwards it to the API, and returns the PNG. The browser never sees the API key. This example uses multer with memory storage and enforces the same 10 MB and format limits as the API, so obviously invalid files are rejected before they cost a request.
import express from "express";
import multer from "multer";
const ALLOWED_TYPES = new Set([
"image/jpeg", "image/png", "image/webp", "image/bmp", "image/gif",
]);
const upload = multer({
storage: multer.memoryStorage(),
limits: { fileSize: 10 * 1024 * 1024 },
});
const app = express();
app.post("/api/remove-background", upload.single("image"), async (req, res) => {
if (!req.file || !ALLOWED_TYPES.has(req.file.mimetype)) {
return res.status(400).json({ error: "Upload a JPEG, PNG, WebP, BMP, or GIF under 10 MB." });
}
const form = new FormData();
form.append("image", new Blob([req.file.buffer], { type: req.file.mimetype }), "upload");
const apiResponse = await fetch("https://fapihub.com/v2/rembg/", {
method: "POST",
headers: { ApiKey: process.env.FAPIHUB_API_KEY },
body: form,
signal: AbortSignal.timeout(30_000),
});
if (!apiResponse.ok) {
const err = await toApiError(apiResponse);
console.error("Background removal failed", err.code, err.requestId);
const status = err.status === 400 ? 400 : 502; // hide key and quota problems from users
return res.status(status).json({ error: "Could not process this image." });
}
res.type("png").send(Buffer.from(await apiResponse.arrayBuffer()));
});
app.listen(3000);Install it with npm install express multer. Note how 401 and 402 are logged but reported to the user as a generic failure: an end user cannot fix your key or your plan, and you should not reveal those details. For a framework-specific walkthrough, see the Node.js background removal page.
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.
Frequently asked questions
Should I use axios or the built-in fetch?
Either works. The axios and form-data version at the top of this guide supports older Node releases and streams the file from disk. Built-in fetch on Node 18 and newer needs no dependencies. Whichever you pick, make sure binary responses are read as a buffer, not as text.
Why does my output file contain JSON instead of an image?
The request failed and you wrote the error body to disk. Check response.ok or the status code before saving, and log the error.code and request_id fields from the JSON body.
Can I call the API directly from browser JavaScript?
No. Anyone could read the key from the page. Send the upload to your own backend, as in the Express example, and call FAPIhub from there.
How many images can I process in Node.js for free?
The free Basic plan includes 100 requests per month with no credit card. Pro covers 7,500 requests for $15 per month, and per-usage packs cost $10 per 1,000 requests that never expire. See pricing for every plan.
Do failed requests count against my quota?
Successful requests and 4xx errors count. 5xx server errors do not, so retrying them costs nothing extra. Validate files before sending to avoid paying for 400 responses.