Node.js connection error when submitting data to HubSpot forms API

I keep getting a connection reset error when trying to submit form data to HubSpot using Node.js. The same logic works perfectly in PHP but fails in my Node.js application. I tested this on both local development and production environments with the same result.

app.post('/submit-form', (req, res) => {
    const https = require('https');
    const querystring = require('querystring');

    const PORTAL_ID = "YOUR_PORTAL_ID";
    const FORM_ID = "YOUR_FORM_GUID";

    const formData = querystring.stringify({
        'email': "[email protected]",
        'name': "John Doe",
        'phone_number': "555-123-4567",
        'comments': "Test message from Node.js",
        'hs_context': JSON.stringify({
            "hutk": '',
            "ipAddress": req.ip || req.connection.remoteAddress,
            "pageUrl": "/contact-us",
            "pageName": "Contact Form"
        })
    });

    const requestOptions = {
        hostname: 'forms.hubspot.com',
        path: `/uploads/form/v2/${PORTAL_ID}/${FORM_ID}`,
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Content-Length': Buffer.byteLength(formData)
        }
    };

    const req = https.request(requestOptions, (response) => {
        console.log(`Response status: ${response.statusCode}`);
        response.on('data', (data) => {
            console.log(`Response data: ${data}`);
        });
    });

    req.on('error', (error) => {
        console.log(`Request failed: ${error.message}`);
    });

    req.write(formData);
    req.end();

    res.json({"status": "Form submission processed"});
});

The error I get is: Request failed: Error: read ECONNRESET

What could be causing this connection issue in Node.js when PHP works fine with the same API endpoint?

make sure your server and hubspot are both using https. sometimes switching your local server to https helps fix those connection reset errors.

I had the same problem recently. Turned out I was missing the User-Agent header - HubSpot’s API will reject requests without it. Add ‘User-Agent’: ‘YourAppName/1.0’ to your headers. Also, make sure you’re handling the response stream correctly. If you don’t end the response properly, you’ll get connection timeouts. I fixed my ECONNRESET errors by using response.on(‘end’, () => { res.json({status: ‘success’}); }); to terminate the response correctly.