RemBG Background Removal API – Developer Docs & Integration Guide






OpenAPI Β· Live playground

Explore the full APIβ€”run real requests in your browser

Browse every endpoint, parameters, and responses. Try requests with your API key, then grab the raw spec at /api/openapi anytime.

Launch interactive reference

Installation of rembg.js

latest npm versionGitHub starsnpm downloadslicenseGitHub issues

npm i @remove-background-ai/rembg.js
                        

API Reference for rembg.js

@remove-background-ai/rembg.js is a zero-config Node.js wrapper for the free Rembg API, enabling background removal with simple, customizable parameters.

Parameters for RemBG.js
ParameterTypeRequiredDefaultDescription
apiKeystring
Required

–

Your Rembg API key
inputImagestring | Buffer | { base64: string }
Required

–

Image file, buffer, or base64 payload
onDownloadProgress(event) => void
Optional

–

Hook for upload progress events
onUploadProgress(event) => void
Optional

–

Hook for download progress events
options.formatwebp (default) | png
Optional
webp
Specifies the output image format. Either "webp" (default) or "png"
options.returnBase64boolean
Optional
false
Return Base64 string instead of file
options.returnMaskboolean
Optional
false
Return only the alpha mask
options.wnumber
Optional

–

Target width (maintains aspect ratio)
options.hnumber
Optional

–

Target height (maintains aspect ratio)
options.exact_resizeboolean
Optional
false
Force exact width Γ— height (may distort)
options.anglenumber
Optional
0
Rotation angle in degrees
options.expandboolean
Optional
true
Add padding so rotated images aren’t cropped
options.bg_colorstring
Optional
-
Optional solid background color in hex (e.g. #FFFFFFFF) or named color (e.g. "red", "blue")
  • Setting up Your Environment: Ensure you have a .env file in your project root containing your API key.

  • Importing the Necessary Modules: Begin by importing the rembg function from @remove-background-ai/rembg.js and the dotenv module to handle environment variables.

  • Configuring Progress Callbacks: The library offers onDownloadProgress and onUploadProgress callbacks to track the progress of file operations. In the provided example, we're logging these events directly to the console.

Now, let's take a closer look at a sample usage:


// script.mjs file

import  { rembg } from '@remove-background-ai/rembg.js';
import dotenv from 'dotenv';
// Load environment variables from .env file
dotenv.config();

// API_KEY will be loaded from the .env file
const API_KEY = process.env.API_KEY;

// log upload and download progress
const onDownloadProgress = console.log;
const onUploadProgress = console.log;
rembg({
    apiKey: API_KEY,
    inputImage: './input.png', //inputImage can be one of these: string | Buffer | { base64: string };
    onDownloadProgress,
    onUploadProgress
}).then(({ outputImagePath, cleanup }) => {
    console.log('βœ…πŸŽ‰ background removed and saved under path=', outputImagePath);
    // if called, it will cleanup (remove from disk) your removed background image
    // cleanup();
});
					
						

Remember, the cleanup function can be called if you wish to remove the processed image from your disk after background removal.

Showing Progress bar

When integrating a background removal service, it's often beneficial to provide users with feedback on the progress of their upload or download request. To facilitate this, you can define your own onDownloadProgress and onUploadProgress callbacks. Both of these callbacks accept AxiosProgressEvent as an event parameter. As the request proceeds, these callbacks are invoked multiple times, allowing you to, for instance, display a progress bar and adjust its length based on the progress.


 (base) root@DESKTOP-C0Q8KK7:~/rembg.js-test# node index.mjs
 {
   loaded: 65687,
   total: 68474,
   progress: 0.9592984198381868, <---- @95% progress 
   bytes: 65687,
   rate: undefined,
   estimated: undefined,
   upload: true  <---- upload progress
 }
 {
   loaded: 68474,
   total: 68474,
   progress: 1, <---- @100% progress 
   bytes: 2787,
   rate: undefined,
   estimated: undefined,
   upload: true <---- upload progress 
 }
 {
   loaded: 1002,
   total: 68824,
   progress: 0.014558874811112402, <---- @1% progress 
   bytes: 1002,
   rate: undefined,
   estimated: undefined,
   download: true <---- download progress 
 }
 {
   loaded: 68824,
   total: 68824,
   progress: 1, <---- @100% progress 
   bytes: 67822,
   rate: undefined,
   estimated: undefined,
   download: true <---- download progress
 }
 βœ…πŸŽ‰ background removed and saved under path=/tmp/rembg--3339-DBqqeJ2eOs4D-.png
					

Membership & Credits Usage

Returns your plan label, included and prepaid credit balances, and usage. You can query by UTC calendar month (legacy), by Stripe-aligned billing period (for monitoring through renewal), or list known billing periods. Authenticate with your API key only.

For schemas, examples, and a try-it console, see the same endpoint in the full reference: Open API docs

Endpoint
GET https://www.rembg.com/api/membership-usage
Authentication

Send your API key: header x-api-key: YOUR_API_KEY_HERE (create and manage keys in your profile on rembg.com).

Query parameters
ParameterTypeDescription
yearnumberCalendar year (1–9999). With month, reads Redis keys user:{uid}:app_usage:{year}:{month}. If omitted (and periodStartUnix is not used), defaults to current UTC year.
monthnumber (1–12)Calendar month 1–12 (UTC convention used for keys). If omitted, defaults to current UTC month.
periodStartUnixnumberUnix timestamp in seconds: start of a billing window. Reads user:{uid}:app_usage:cycle:{periodStartUnix} and api_usage:cycle:…. Cannot be combined with year or month.
expandstringComma-separated flags. Include billing_cycle to add a billingCycle object: current Stripe period when billing_period_* exists in Redis, otherwise the current UTC calendar month. Also works with periodStartUnix for a specific window.
includeBillingCycle1 / trueSame as expand containing billing_cycle: set to 1 or true to include the billingCycle object.
listBillingCycles1 / trueDedicated mode: listBillingCycles=1 or true returns only { billingCycles: [...] }. Scans Redis for cycle keys for this user; other query parameters are ignored on this request.

Do not pass periodStartUnix together with year or month β€” the API returns 400. The listBillingCycles mode is separate and ignores other params.

List billing periods

Use this to populate a dropdown of past and current subscription windows (each entry is a periodStartUnix you can pass back with periodStartUnix=…). Period end times are inferred (next period start βˆ’ 1, or Stripe current_period_end for the active period).

curl --location 'https://www.rembg.com/api/membership-usage?listBillingCycles=1' \
  --header 'x-api-key: YOUR_API_KEY_HERE'

Example response

{
  "billingCycles": [
    {
      "periodStartUnix": 1774268612,
      "periodEndUnix": 1776947012,
      "appUsage": 120,
      "apiUsage": 880
    }
  ]
}

Sorted newest period first. A period appears if there is a cycle usage key or if it is the current billing_period_start from Stripe webhooks.

The billingCycle object

Present when expand includes billing_cycle or includeBillingCycle is set. Use it for dashboards: renewal boundary, usage in the window, and remaining included credits.

FieldDescription
periodStartUnixStart of the billing window (unix seconds). Matches Stripe current_period_start when the account is synced.
periodEndUnixEnd of the current window (unix seconds), i.e. just before the next renewal β€” Stripe current_period_end when synced. Not the same as subscription cancellation date.
appUsage / apiUsageIncluded-credit usage counted in this window: web/editor (app) vs API key (api). usedIncludedCredits equals their sum.
includedCreditsYour included (plan) credit allowance as stored in Redis (same idea as top-level credits).
prepaidCreditsPrepaid (purchased) balance; does not reset each billing period.
usedIncludedCreditsTotal included usage in the window (app + API). Prepaid consumption is not added here.
remainingIncludedCreditsmax(0, includedCredits βˆ’ usedIncludedCredits) for this snapshot.
stripeBillingSyncedtrue when Redis has billing_period_start/end from Stripe so the window matches your subscription; false means the API fell back to a UTC calendar month for this block.

Until Stripe webhooks have written billing periods for the user, stripeBillingSynced may be false and the billingCycle window follows the UTC calendar month. After sync, usage limits on the image API align with the same cycle keys.

For β€œcredits used before next renewal”, call with expand=billing_cycle and use billingCycle.periodEndUnix as the renewal boundary, billingCycle.usedIncludedCredits (or appUsage + apiUsage), and billingCycle.remainingIncludedCredits. Add prepaidCredits if you want total disposable balance.

Examples (cURL)

Usage for a specific UTC calendar month

curl --location 'https://www.rembg.com/api/membership-usage?year=2026&month=3' \
  --header 'x-api-key: YOUR_API_KEY_HERE'

Current billing cycle + full billingCycle block (renewal-aligned when synced)

# Current subscription window + usage (renewal-aligned when Stripe is synced)
curl --location 'https://www.rembg.com/api/membership-usage?expand=billing_cycle' \
  --header 'x-api-key: YOUR_API_KEY_HERE'

One historical billing window by period start (from listBillingCycles or Stripe)

# Specific billing period by Stripe period start (unix seconds)
curl --location 'https://www.rembg.com/api/membership-usage?periodStartUnix=1774268612&expand=billing_cycle' \
  --header 'x-api-key: YOUR_API_KEY_HERE'
Example JSON (with billing cycle)

Top-level app_usage and api_usage always reflect either the requested calendar month or, when periodStartUnix is set, that cycle’s counters. When expand=billing_cycle is omitted, billingCycle is absent.

{
  "membership": "Premium-20000",
  "credits": 18500,
  "prepaidCredits": 2000,
  "app_usage": 8500,
  "api_usage": 10000,
  "billingCycle": {
    "periodStartUnix": 1740441600,
    "periodEndUnix": 1743033599,
    "appUsage": 4200,
    "apiUsage": 5100,
    "includedCredits": 18500,
    "prepaidCredits": 2000,
    "usedIncludedCredits": 9300,
    "remainingIncludedCredits": 9200,
    "stripeBillingSynced": true
  }
}

When stripeBillingSynced is true, billingCycle matches enforcement on the background-removal API. When false, rely on calendar month fields or wait until webhooks populate billing_period_* in Redis.

Error Responses

All error responses return a JSON body with a status field matching the HTTP status code.

Single Error Response

HTTP/1.1 400 Bad Request

HTTP/1.1 400 Bad Request
Content-Type: application/json

{
  "error": "Image width (12000px) exceeds the maximum allowed width of 10000px.",
  "field": "image",
  "status": 400
}

HTTP/1.1 400 Bad Request

HTTP/1.1 400 Bad Request
Content-Type: application/json

{
  "error": "Multiple validation errors",
  "details": [
    { "field": "w", "message": "'w' must be an integer, got: 'abc'" },
    { "field": "angle", "message": "'angle' must be between -360 and 360 degrees, got: 500.0" }
  ],
  "status": 400
}
Error Reference
ScenarioStatusError Message
No image provided
400
No image file provided. Please include an 'image' field in your form data.
No file selected
400
No file selected. Please choose an image file to upload.
Unsupported file type
400
File type '.exe' is not supported. Allowed formats: webp, bmp, png, jpg, jpeg
Corrupt image
400
File does not appear to be a valid image (invalid file signature)
Empty file (0 bytes)
400
Uploaded file is empty (0 bytes).
File too large
400
File size (55.2 MB) exceeds the maximum allowed size of 50 MB.
Image too wide
400
Image width (12000px) exceeds the maximum allowed width of 10000px.
Image too tall
400
Image height (15000px) exceeds the maximum allowed height of 10000px.
Bad w or h value
400
'w' must be an integer, got: 'abc'
w or h out of range
400
'w' must be at least 1, got: -5
w or h above max
400
'w' must be at most 10000, got: 15000
Bad angle
400
'angle' must be a number, got: 'ninety'
Angle out of range
400
'angle' must be between -360 and 360 degrees, got: 500.0
Bad output format
400
Invalid format 'gif'. Allowed formats: PNG, JPEG, WEBP, BMP
Bad bg_color
400
Invalid color format '#12345'. Use hex format: #RGB, #RGBA, #RRGGBB, or #RRGGBBAA
mask + bg_color conflict
400
Cannot use 'mask=true' together with 'bg_color'. Choose one or the other.
Email not verified
403
Email address not verified – please check your inbox
Invalid API key
401
invalid api key
Both API key and user token sent
400
This is a mistake: Cannot use both API key and user token
Rate limit exceeded (short-term)
429
You're making requests too quickly, Please Upgrade or slow down.
Rate limit exceeded (daily, anonymous)
429
You've reached your daily limit. Please sign up for more access.
Rate limit exceeded (monthly, authenticated)
429
You've reached your monthly limit. Consider purchasing more credits.
Error Handling Guidelines
  • Check HTTP status code 400 to identify validation errors
  • Parse the error field for the error message
  • Check for the details array when handling multiple validation errors
  • Use the field property to map errors to specific request parameters