A PATCH request with multipart/form-data content-type returns 400 error

NextJS front-end/middleware, Rails back-end

In my shop settings page I have a submit button that sends a multipart/form-data body to nextjs api endpoint that forwards it to rails server. The code is working on my local but netlify returns a 400 error.

submit function

function handleFormSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault()

    const formData = new FormData()
    integrationFormDataAppend(formData, logoFile, bannerFile, shopName, streetAddress, city, tags, website, instagram, facebook, linkedin, youtube, twitter, pixelId, editorState)

    axios.patch(`/api/merchants/integrations/${integration.id}`, formData)
      .then(res => {

        if (res.status === 200) {
          if (res.data.data?.integration) {
            setIntegrations(prev => {
              return prev.map(i =>
                i.id === integration.id ? res.data.data.integration : i
              )
            })
          }

          toast.success('Shop updated successfully!')
        } else {
          throw new Error('Failed to update shop')
        }
      })
      .catch(error => {
        toast.error(error.response?.data?.error || 'Something went wrong!')
        console.error('Submission error:', error.response || error)
      })
  }

api endpoint

import { getAccessToken, withApiAuthRequired } from "@auth0/nextjs-auth0"
import EXTERNAL_API from "@/api/externalApi/externalApiConfig"
import { NextRequest, NextResponse } from "next/server"

export const PATCH = withApiAuthRequired(async function ProtectedRoute(req: NextRequest, { params }) {
  const { accessToken } = await getAccessToken()
  const { method, url } = req
  const { integration_id } = params!

  let response = { error: "Something went wrong" }
  let status = 500

  if (method === "PATCH") {
    const formData = await req.formData()

    response = await EXTERNAL_API(accessToken)
      .patch(`/api/merchants/integrations/${integration_id}?type=merchant`, formData)
      .then(res => {
        status = 200
        return res.data
      })
      .catch((err) => {
        status = err.response?.status ?? 400
        response = { error: err.message || "Unknown error occurred" }
        return response
      })
  }

  return NextResponse.json({ response }, { status })
})

error

Nov 25, 12:24:53 PM: 500b8b3a ERROR  K [AxiosError]: Request failed with status code 400
    at eS (/var/task/.next/server/chunks/9712.js:11:18151)
    at IncomingMessage.<anonymous> (/var/task/.next/server/chunks/9712.js:13:8488)
    at IncomingMessage.emit (node:events:529:35)
    at endReadableNT (node:internal/streams/readable:1400:12)
    at process.processTicksAndRejections (node:internal/process/task_queues:82:21) {
  code: 'ERR_BAD_REQUEST',
  config: {
    transitional: {
      silentJSONParsing: true,
      forcedJSONParsing: true,
      clarifyTimeoutError: false
    },
    adapter: [ 'xhr', 'http', 'fetch' ],
    transformRequest: [ [Function (anonymous)] ],
    transformResponse: [ [Function (anonymous)] ],
    timeout: 0,
    xsrfCookieName: 'XSRF-TOKEN',
    xsrfHeaderName: 'X-XSRF-TOKEN',
    maxContentLength: -1,
    maxBodyLength: -1,
    env: { FormData: [Function], Blob: [class Blob] },
    validateStatus: [Function: validateStatus],
    headers: Object [AxiosHeaders] {
      Accept: 'application/json, text/plain, */*',
      'Content-Type': 'multipart/form-data; boundary=axios-1.7.2-boundary-NCMFxXU_wAwQ13oOs6LHuDyu9',
      Authorization: 'Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6InVyelRxVEIzaEFTQk1DQzJLd2p6TyJ9.eyJpc3MiOiJodHRwczovL21lcmNoYW50cy1kZXYudXMuYXV0aDAuY29tLyIsInN1YiI6ImF1dGgwfDY2N2RjODM5ODA3YWUwNDBkZTMzNDBiYiIsImF1ZCI6WyJodHRwczovL2xvY2FsLXNob3BzLW1lcmNoYW50cy9hcGkvZGV2IiwiaHR0cHM6Ly9tZXJjaGFudHMtZGV2LnVzLmF1dGgwLmNvbS91c2VyaW5mbyJdLCJpYXQiOjE3MzI1NjI2NzksImV4cCI6MTczMjY0OTA3OSwic2NvcGUiOiJvcGVuaWQgcHJvZmlsZSBlbWFpbCIsImF6cCI6IlRISk85aW9ESDJsZVlod3YxUzBvWUJBMlY5MUJKVVlBIn0.NT8ucJjjlgwQY3NdwST1cEBLuVek4q4pfVQzOmmvRiu1yavaH3Fah8EegkKcoCJwhjGtu_pf6nq9zJqEJri43PCdor0byfxD5VFNGSchubcrVYi-Lf-NvWNgUTQsBdT7gEQVvUW9KMZP4hReIw8g2wplnvjNt1Lay0h83u3PCPN8LP_fKvCT-3C6STqb-ciMRPuwzCVqJYDujXPqx_78w3oZP1vl8pdV8eEuJCaew5EgUjekC4r4-cxwsviyxvPkuc5xquF6ne-iATszzI-Y-JIg-4nrHYpCJYqeeiZk-CWRJ-ETBU8ChKDlRIwJT4AQpr7kIfngVkpGpbldP2eVyw',
      'User-Agent': 'axios/1.7.2',
      'Content-Length': '1601',
      'Accept-Encoding': 'gzip, compress, deflate, br'
    },
    baseURL: 'https://staging.localshops.com',
    method: 'patch',
    url: '/api/merchants/integrations/1043?type=merchant',
    data: FormData { [Symbol(state)]: [Array] }
  },
  request: <ref *1> ClientRequest {
    _events: [Object: null prototype] {
      abort: [Function (anonymous)],
      aborted: [Function (anonymous)],
      connect: [Function (anonymous)],
      error: [Function (anonymous)],
      socket: [Function (anonymous)],
      timeout: [Function (anonymous)],
      finish: [Function: requestOnFinish]
    },
    _eventsCount: 7,
    _maxListeners: undefined,
    outputData: [],
    outputSize: 0,
    writable: true,
    destroyed: false,
    _last: true,
    chunkedEncoding: false,
    shouldKeepAlive: false,
    maxRequestsOnConnectionReached: false,
    _defaultKeepAlive: true,
    useChunkedEncodingByDefault: true,
    sendDate: false,
    _removedConnection: false,
    _removedContLen: false,
    _removedTE: false,
    strictContentLength: false,
    _contentLength: '1601',
    _hasBody: true,
    _trailer: '',
    finished: true,
    _headerSent: true,
    _closed: false,
    socket: TLSSocket {
      _tlsOptions: [Object],
      _secureEstablished: true,
      _securePending: false,
      _newSessionPending: false,
      _controlReleased: true,
      secureConnecting: false,
      _SNICallback: null,
      servername: 'staging.localshops.com',
      alpnProtocol: false,
      authorized: true,
      authorizationError: null,
      encrypted: true,
      _events: [Object: null prototype],
      _eventsCount: 10,
      connecting: false,
      _hadError: false,
      _parent: null,
      _host: 'staging.localshops.com',
      _closeAfterHandlingError: false,
      _readableState: [ReadableState],
      _maxListeners: undefined,
      _writableState: [WritableState],
      allowHalfOpen: false,
      _sockname: null,
      _pendingData: null,
      _pendingEncoding: '',
      server: undefined,
      _server: null,
      ssl: [TLSWrap],
      _requestCert: true,
      _rejectUnauthorized: true,
      parser: null,
      _httpMessage: [Circular *1],
      [Symbol(alpncallback)]: null,
      [Symbol(res)]: [TLSWrap],
      [Symbol(verified)]: true,
      [Symbol(pendingSession)]: null,
      [Symbol(async_id_symbol)]: 5340,
      [Symbol(kHandle)]: [TLSWrap],
      [Symbol(lastWriteQueueSize)]: 0,
      [Symbol(timeout)]: null,
      [Symbol(kBuffer)]: null,
      [Symbol(kBufferCb)]: null,
      [Symbol(kBufferGen)]: null,
      [Symbol(kCapture)]: false,
      [Symbol(kSetNoDelay)]: false,
      [Symbol(kSetKeepAlive)]: true,
      [Symbol(kSetKeepAliveInitialDelay)]: 60,
      [Symbol(kBytesRead)]: 0,
      [Symbol(kBytesWritten)]: 0,
      [Symbol(connect-options)]: [Object]
    },
    _header: 'PATCH /api/merchants/integrations/1043?type=merchant HTTP/1.1\r\n' +
      'Accept: application/json, text/plain, */*\r\n' +
      'Content-Type: multipart/form-data; boundary=axios-1.7.2-boundary-NCMFxXU_wAwQ13oOs6LHuDyu9\r\n' +
      'Authorization: Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6InVyelRxVEIzaEFTQk1DQzJLd2p6TyJ9.eyJpc3MiOiJodHRwczovL21lcmNoYW50cy1kZXYudXMuYXV0aDAuY29tLyIsInN1YiI6ImF1dGgwfDY2N2RjODM5ODA3YWUwNDBkZTMzNDBiYiIsImF1ZCI6WyJodHRwczovL2xvY2FsLXNob3BzLW1lcmNoYW50cy9hcGkvZGV2IiwiaHR0cHM6Ly9tZXJjaGFudHMtZGV2LnVzLmF1dGgwLmNvbS91c2VyaW5mbyJdLCJpYXQiOjE3MzI1NjI2NzksImV4cCI6MTczMjY0OTA3OSwic2NvcGUiOiJvcGVuaWQgcHJvZmlsZSBlbWFpbCIsImF6cCI6IlRISk85aW9ESDJsZVlod3YxUzBvWUJBMlY5MUJKVVlBIn0.NT8ucJjjlgwQY3NdwST1cEBLuVek4q4pfVQzOmmvRiu1yavaH3Fah8EegkKcoCJwhjGtu_pf6nq9zJqEJri43PCdor0byfxD5VFNGSchubcrVYi-Lf-NvWNgUTQsBdT7gEQVvUW9KMZP4hReIw8g2wplnvjNt1Lay0h83u3PCPN8LP_fKvCT-3C6STqb-ciMRPuwzCVqJYDujXPqx_78w3oZP1vl8pdV8eEuJCaew5EgUjekC4r4-cxwsviyxvPkuc5xquF6ne-iATszzI-Y-JIg-4nrHYpCJYqeeiZk-CWRJ-ETBU8ChKDlRIwJT4AQpr7kIfngVkpGpbldP2eVyw\r\n' +
      'User-Agent: axios/1.7.2\r\n' +
      'Content-Length: 1601\r\n' +
      'Accept-Encoding: gzip, compress, deflate, br\r\n' +
      'Host: staging.localshops.com\r\n' +
      'CDN-Loop: netlify\r\n' +
      'Connection: close\r\n' +
      '\r\n',
    _keepAliveTimeout: 0,
    _onPendingData: [Function: nop],
    agent: Agent {
      _events: [Object: null prototype],
      _eventsCount: 2,
      _maxListeners: undefined,
      defaultPort: 443,
      protocol: 'https:',
      options: [Object: null prototype],
      requests: [Object: null prototype] {},
      sockets: [Object: null prototype],
      freeSockets: [Object: null prototype] {},
      keepAliveMsecs: 1000,
      keepAlive: false,
      maxSockets: Infinity,
      maxFreeSockets: 256,
      scheduling: 'lifo',
      maxTotalSockets: Infinity,
      totalSocketCount: 1,
      maxCachedSessions: 100,
      _sessionCache: [Object],
      [Symbol(kCapture)]: false
    },
    socketPath: undefined,
    method: 'PATCH',
    maxHeaderSize: undefined,
    insecureHTTPParser: undefined,
    joinDuplicateHeaders: undefined,
    path: '/api/merchants/integrations/1043?type=merchant',
    _ended: true,
    res: IncomingMessage {
      _readableState: [ReadableState],
      _events: [Object: null prototype],
      _eventsCount: 4,
      _maxListeners: undefined,
      socket: [TLSSocket],
      httpVersionMajor: 1,
      httpVersionMinor: 1,
      httpVersion: '1.1',
      complete: true,
      rawHeaders: [Array],
      rawTrailers: [],
      joinDuplicateHeaders: undefined,
      aborted: false,
      upgrade: false,
      url: '',
      method: null,
      statusCode: 400,
      statusMessage: 'Bad Request',
      client: [TLSSocket],
      _consuming: false,
      _dumped: false,
      req: [Circular *1],
      responseUrl: 'https://staging.localshops.com/api/merchants/integrations/1043?type=merchant',
      redirects: [],
      [Symbol(kCapture)]: false,
      [Symbol(kHeaders)]: [Object],
      [Symbol(kHeadersCount)]: 10,
      [Symbol(kTrailers)]: null,
      [Symbol(kTrailersCount)]: 0
    },
    aborted: false,
    timeoutCb: null,
    upgradeOrConnect: false,
    parser: null,
    maxHeadersCount: null,
    reusedSocket: false,
    host: 'staging.localshops.com',
    protocol: 'https:',
    _redirectable: Writable {
      _writableState: [WritableState],
      _events: [Object: null prototype],
      _eventsCount: 6,
      _maxListeners: undefined,
      _options: [Object],
      _ended: true,
      _ending: true,
      _redirectCount: 0,
      _redirects: [],
      _requestBodyLength: 1601,
      _requestBodyBuffers: [],
      _onNativeResponse: [Function (anonymous)],
      _currentRequest: [Circular *1],
      _currentUrl: 'https://staging.localshops.com/api/merchants/integrations/1043?type=merchant',
      [Symbol(kCapture)]: false
    },
    [Symbol(kCapture)]: false,
    [Symbol(kBytesWritten)]: 0,
    [Symbol(kNeedDrain)]: false,
    [Symbol(corked)]: 0,
    [Symbol(kOutHeaders)]: [Object: null prototype] {
      accept: [Array],
      'content-type': [Array],
      authorization: [Array],
      'user-agent': [Array],
      'content-length': [Array],
      'accept-encoding': [Array],
      host: [Array],
      'cdn-loop': [Array]
    },
    [Symbol(errored)]: null,
    [Symbol(kHighWaterMark)]: 16384,
    [Symbol(kRejectNonStandardBodyWrites)]: false,
    [Symbol(kUniqueHeaders)]: null
  },
  response: {
    status: 400,
    statusText: 'Bad Request',
    headers: Object [AxiosHeaders] {
      date: 'Mon, 25 Nov 2024 19:24:53 GMT',
      'content-type': 'text/html',
      'content-length': '150',
      connection: 'close',
      'x-powered-by': 'cloud66'
    },
    config: {
      transitional: [Object],
      adapter: [Array],
      transformRequest: [Array],
      transformResponse: [Array],
      timeout: 0,
      xsrfCookieName: 'XSRF-TOKEN',
      xsrfHeaderName: 'X-XSRF-TOKEN',
      maxContentLength: -1,
      maxBodyLength: -1,
      env: [Object],
      validateStatus: [Function: validateStatus],
      headers: [Object [AxiosHeaders]],
      baseURL: 'https://staging.localshops.com',
      method: 'patch',
      url: '/api/merchants/integrations/1043?type=merchant',
      data: [FormData]
    },
    request: <ref *1> ClientRequest {
      _events: [Object: null prototype],
      _eventsCount: 7,
      _maxListeners: undefined,
      outputData: [],
      outputSize: 0,
      writable: true,
      destroyed: false,
      _last: true,
      chunkedEncoding: false,
      shouldKeepAlive: false,
      maxRequestsOnConnectionReached: false,
      _defaultKeepAlive: true,
      useChunkedEncodingByDefault: true,
      sendDate: false,
      _removedConnection: false,
      _removedContLen: false,
      _removedTE: false,
      strictContentLength: false,
      _contentLength: '1601',
      _hasBody: true,
      _trailer: '',
      finished: true,
      _headerSent: true,
      _closed: false,
      socket: [TLSSocket],
      _header: 'PATCH /api/merchants/integrations/1043?type=merchant HTTP/1.1\r\n' +
        'Accept: application/json, text/plain, */*\r\n' +
        'Content-Type: multipart/form-data; boundary=axios-1.7.2-boundary-NCMFxXU_wAwQ13oOs6LHuDyu9\r\n' +
        'Authorization: Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6InVyelRxVEIzaEFTQk1DQzJLd2p6TyJ9.eyJpc3MiOiJodHRwczovL21lcmNoYW50cy1kZXYudXMuYXV0aDAuY29tLyIsInN1YiI6ImF1dGgwfDY2N2RjODM5ODA3YWUwNDBkZTMzNDBiYiIsImF1ZCI6WyJodHRwczovL2xvY2FsLXNob3BzLW1lcmNoYW50cy9hcGkvZGV2IiwiaHR0cHM6Ly9tZXJjaGFudHMtZGV2LnVzLmF1dGgwLmNvbS91c2VyaW5mbyJdLCJpYXQiOjE3MzI1NjI2NzksImV4cCI6MTczMjY0OTA3OSwic2NvcGUiOiJvcGVuaWQgcHJvZmlsZSBlbWFpbCIsImF6cCI6IlRISk85aW9ESDJsZVlod3YxUzBvWUJBMlY5MUJKVVlBIn0.NT8ucJjjlgwQY3NdwST1cEBLuVek4q4pfVQzOmmvRiu1yavaH3Fah8EegkKcoCJwhjGtu_pf6nq9zJqEJri43PCdor0byfxD5VFNGSchubcrVYi-Lf-NvWNgUTQsBdT7gEQVvUW9KMZP4hReIw8g2wplnvjNt1Lay0h83u3PCPN8LP_fKvCT-3C6STqb-ciMRPuwzCVqJYDujXPqx_78w3oZP1vl8pdV8eEuJCaew5EgUjekC4r4-cxwsviyxvPkuc5xquF6ne-iATszzI-Y-JIg-4nrHYpCJYqeeiZk-CWRJ-ETBU8ChKDlRIwJT4AQpr7kIfngVkpGpbldP2eVyw\r\n' +
        'User-Agent: axios/1.7.2\r\n' +
        'Content-Length: 1601\r\n' +
        'Accept-Encoding: gzip, compress, deflate, br\r\n' +
        'Host: staging.localshops.com\r\n' +
        'CDN-Loop: netlify\r\n' +
        'Connection: close\r\n' +
        '\r\n',
      _keepAliveTimeout: 0,
      _onPendingData: [Function: nop],
      agent: [Agent],
      socketPath: undefined,
      method: 'PATCH',
      maxHeaderSize: undefined,
      insecureHTTPParser: undefined,
      joinDuplicateHeaders: undefined,
      path: '/api/merchants/integrations/1043?type=merchant',
      _ended: true,
      res: [IncomingMessage],
      aborted: false,
      timeoutCb: null,
      upgradeOrConnect: false,
      parser: null,
      maxHeadersCount: null,
      reusedSocket: false,
      host: 'staging.localshops.com',
      protocol: 'https:',
      _redirectable: [Writable],
      [Symbol(kCapture)]: false,
      [Symbol(kBytesWritten)]: 0,
      [Symbol(kNeedDrain)]: false,
      [Symbol(corked)]: 0,
      [Symbol(kOutHeaders)]: [Object: null prototype],
      [Symbol(errored)]: null,
      [Symbol(kHighWaterMark)]: 16384,
      [Symbol(kRejectNonStandardBodyWrites)]: false,
      [Symbol(kUniqueHeaders)]: null
    },
    data: '<html>\r\n' +
      '<head><title>400 Bad Request</title></head>\r\n' +
      '<body>\r\n' +
      '<center><h1>400 Bad Request</h1></center>\r\n' +
      '<hr><center>nginx</center>\r\n' +
      '</body>\r\n' +
      '</html>\r\n'
  }
}

I think the issue is either with PATCH request or multipart/form-data content-type since other requests (GET, POST, DELETE) and json body work fine

The 400 seems to be coming from your API:

and not Netlify.