> For the complete documentation index, see [llms.txt](https://docs.photoroom.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.photoroom.com/remove-background-api-basic-plan/code-samples/node.js-integration.md).

# Node.js Integration

In this tutorial, I will show you how you can integrate the Photoroom API into a Node.js codebase in just a few minutes.

### Step 1: Get Your API Key

The first thing you need to do is get your API key.

If you don't already have an API key, here are the [steps to create yours](/getting-started/introduction.md#how-can-i-get-my-api-key).

### Step 2: Use Our Sample Code

Visit [Photoroom’s GitHub](https://github.com/PhotoRoom/api-code-samples) to find a sample code that's ready to use.

Simply copy and paste the code into your project, and update the placeholder with your own API key.

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

// Please replace with your own apiKey
const apiKey = 'YOUR_API_KEY_HERE';

function removeBackground(imagePath, savePath) {
    return new Promise((resolve, reject) => {
        const boundary = '--------------------------' + Date.now().toString(16);
        
        const postOptions = {
            hostname: 'sdk.photoroom.com',
            path: '/v1/segment',
            method: 'POST',
            headers: {
                'Content-Type': `multipart/form-data; boundary=${boundary}`,
                'X-API-Key': apiKey
            }
        };

        const req = https.request(postOptions, (res) => {
            // Check if the response is an image
            const isImage = ['image/jpeg', 'image/png', 'image/gif'].includes(res.headers['content-type']);

            if (!isImage) {
                let errorData = '';
                res.on('data', (chunk) => errorData += chunk);
                res.on('end', () => reject(new Error(`Expected an image response, but received: ${errorData}`)));
                return;
            }

            // Create a write stream to save the image
            const fileStream = fs.createWriteStream(savePath);
            res.pipe(fileStream);

            fileStream.on('finish', () => {
                resolve(`Image saved to ${savePath}`);
            });

            fileStream.on('error', (error) => {
                reject(new Error(`Failed to save the image: ${error.message}`));
            });
        });

        req.on('error', (error) => {
            reject(error);
        });

        // Write form data
        req.write(`--${boundary}\r\n`);
        req.write(`Content-Disposition: form-data; name="image_file"; filename="${imagePath.split('/').pop()}"\r\n`);
        req.write('Content-Type: image/jpeg\r\n\r\n'); // assuming JPEG, adjust if another format is used

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

module.exports = removeBackground;
```

### Step 3: Call the API

Now it's time to call the API in your code! Just use the function removeBackground() and pass as arguments both the path of the original image and the path where the result image should be saved.

```javascript
const removeBackground = require('./remove-background');

const imagePath = './path/to/your/image.jpg';
const savePath = './path/where/you/want/to/save/response.jpg';

removeBackground(imagePath, savePath)
    .then(message => {
        console.log(message);
    })
    .catch(error => {
        console.error('Error:', error);
    });
```

### You're done!

That's it! With just these three easy steps, you can integrate the Photoroom Background Removal API into your Node.js project and provide your users with high-quality images with clean backgrounds.

According to resellers who use the Photoroom app, this feature can increase sales by 20 up to 100%.

If you want to learn more about the PhotoRoom API and get your API key, visit <https://www.photoroom.com/api>.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.photoroom.com/remove-background-api-basic-plan/code-samples/node.js-integration.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
