Set Custom FormData Boundary in Axios

This article explains how to configure and send a custom boundary string when submitting multipart/form-data requests using Axios. While Axios and HTTP clients typically generate multipart boundaries automatically, certain APIs or legacy backends require specific, predetermined boundary strings. Below are the precise steps and code examples for setting custom boundaries in both Node.js and browser environments.

Setting a Custom Boundary in Node.js

In Node.js, Axios relies on the form-data package rather than the browser's native FormData implementation. The form-data library provides a built-in method called setBoundary() to define a custom boundary string.

Step 1: Install Dependencies

Ensure you have both axios and form-data installed:

npm install axios form-data

Step 2: Configure the FormData Instance

Create an instance of FormData, define your custom boundary using .setBoundary(), and pass the appropriate Content-Type header to Axios.

const axios = require('axios');
const FormData = require('form-data');
const fs = require('fs');

async function uploadWithCustomBoundary() {
  const form = new FormData();
  const customBoundary = '----CustomBoundaryString123456';

  // Explicitly set the custom boundary
  form.setBoundary(customBoundary);

  // Append fields and files
  form.append('username', 'john_doe');
  form.append('file', fs.createReadStream('./example.txt'));

  try {
    const response = await axios.post('https://api.example.com/upload', form, {
      headers: {
        // Option 1: Let the library generate headers using the new boundary
        ...form.getHeaders(),

        // Option 2: Set the header manually
        // 'Content-Type': `multipart/form-data; boundary=${customBoundary}`
      },
    });

    console.log('Upload successful:', response.data);
  } catch (error) {
    console.error('Upload failed:', error.message);
  }
}

uploadWithCustomBoundary();

Setting a Custom Boundary in the Browser

The native browser FormData API does not allow developers to set or inspect the multipart boundary directly for security and standard-compliance reasons. If you manually set Content-Type: multipart/form-data; boundary=... with native FormData, the browser will not format the payload to match your custom boundary string, resulting in a malformed request.

If a custom boundary is strictly required in the browser, you must construct the payload manually using a Blob or string.

Manual Multipart Payload Construction

import axios from 'axios';

async function sendManualMultipart() {
  const boundary = '----BrowserCustomBoundary98765';
  const textContent = 'Hello World';

  // Construct the multipart body manually
  const body = 
    `--${boundary}\r\n` +
    `Content-Disposition: form-data; name="textField"\r\n\r\n` +
    `${textContent}\r\n` +
    `--${boundary}--\r\n`;

  try {
    const response = await axios.post('https://api.example.com/upload', body, {
      headers: {
        'Content-Type': `multipart/form-data; boundary=${boundary}`,
      },
    });

    console.log('Response:', response.data);
  } catch (error) {
    console.error('Error:', error.message);
  }
}

Key Considerations