Node integration guide

Integrate BackgroundErase in Node.js using a simple no-dependency script built on the native https module.

Matt
Written by Matt
Updated in March 2026

The quickest way to integrate BackgroundErase in Node.js is with a simple script that uses the built-in https module. You do not need axios, node-fetch, form-data, or any other external package to get started.

Quick summary: Get an API token, save the helper module as backgroundRemoval.js, call it from example.js, and your processed image will be written to disk.


Prerequisites

Before you begin, make sure you have:

  • Node.js 14.x or higher
  • An API token from your account dashboard
  • An active Business or Enterprise subscription with API access

Authentication

API access requires an active business subscription. After subscribing:

  1. Go to your account dashboard.
  2. Find the API Access section.
  3. Generate a new token and store it securely.

No-dependency quickstart

Create a file called backgroundRemoval.js. This module uploads an image to the API and streams the processed output directly to disk.

const https = require('https');
const fs = require('fs');

const API_KEY = 'YOUR_API_KEY'; // Insert your API key here

function backgroundRemoval(srcPath, dstPath) {
  return new Promise((resolve, reject) => {
    const boundary = '----' + Date.now().toString(16);

    const options = {
      hostname: 'api.backgrounderase.com',
      path: '/v2',
      method: 'POST',
      headers: {
        'Content-Type': `multipart/form-data; boundary=${boundary}`,
        'x-api-key': API_KEY
      }
    };

    const req = https.request(options, (res) => {
      const isImage = /^image\//.test(res.headers['content-type'] || '');

      if (!isImage) {
        let errMsg = '';
        res.on('data', (chunk) => errMsg += chunk);
        res.on('end', () => reject(new Error(`❌ Error: ${errMsg}`)));
        return;
      }

      const fileStream = fs.createWriteStream(dstPath);
      res.pipe(fileStream);

      fileStream.on('finish', () => {
        console.log(`✅ File saved: ${dstPath}`);
        resolve(dstPath);
      });
      fileStream.on('error', reject);
    });

    req.on('error', reject);

    // Multipart form
    req.write(`--${boundary}\r\n`);
    req.write(`Content-Disposition: form-data; name="image_file"; filename="${srcPath.split('/').pop()}"\r\n`);
    req.write('Content-Type: application/octet-stream\r\n\r\n');

    const upload = fs.createReadStream(srcPath);
    upload.on('end', () => {
      req.write('\r\n');
      req.write(`--${boundary}--\r\n`);
      req.end();
    });
    upload.pipe(req, { end: false });
  });
}

module.exports = backgroundRemoval;

Basic usage example

Create a second file called example.js:

const backgroundRemoval = require('./backgroundRemoval');

(async () => {
  try {
    const input = './input.jpg';
    const output = './output.png';
    await backgroundRemoval(input, output);
  } catch (err) {
    console.error('Error:', err);
  }
})();

Then run it with:

node example.js

Using an environment variable

Instead of hardcoding your API key inside the module, you can read it from an environment variable. This is the safer option for production deployments and shared codebases.

const API_KEY = process.env.BACKGROUND_ERASE_API_KEY;

Tip: Keep API keys out of source control and avoid exposing them in frontend bundles or public repos.


Optional: low-latency JSON mode

If you want faster round-trips and more mask-oriented workflows, the JSON mode client downsizes inputs to 1024×1024 before sending them, receives a mask back, then upscales that mask and applies it to the original PNG locally.

This keeps payloads smaller while preserving the native-size source pixels, which makes it useful for:

  • Real-time UIs
  • Batch processing on constrained networks
  • Workflows where you want mask manipulation capability
  • Reducing network overhead while keeping final native resolution

Good default: Start with the multipart helper above. Move to JSON mode once you want to optimize latency further.

Why start with the built-in https module?

  • No third-party dependencies
  • Easy to understand and adapt
  • Direct control over the multipart upload flow
  • Simple to integrate into scripts, backends, and internal tools