Search code examples
javascriptnode.jstypescriptrestfile-upload

Socket connection timout error in Node js


I've been having trouble uploading images to cloudinary in Node JS because when I try to I get this error

Error [ERR_SOCKET_CONNECTION_TIMEOUT]: Socket connection timeout 
 {
   error: Error [ERR_SOCKET_CONNECTION_TIMEOUT]: Socket connection timeout
       at new NodeError (node:internal/errors:399:5)
       at internalConnectMultiple (node:net:1099:20)
       at Timeout.internalConnectMultipleTimeout (node:net:1638:3)
       at listOnTimeout (node:internal/timers:575:11)
       at process.processTimers (node:internal/timers:514:7) {
     code: 'ERR_SOCKET_CONNECTION_TIMEOUT'
   }
 }

Sometimes the image gets uploaded and sometimes it doesn't. I've looked it up online and it says poor internet connection but my internet is good enough, I've had the entire application dockerized so idk if that has something to do with it.

const addProduct = async (req: Request, res: Response, next: NextFunction) => {
  const {
    title,
    snippet,
    description,
    quantity,
    price,
    coverImage,
    imageArray,
    category,
  } = req.body;
  try {
    cloudinary.api
      .ping()
      .then((res) => {
        console.log(`Cloudinary connection ${res.status}`);
      })
      .catch((err) => console.log(err));

    const imageUrlArray: Array<imageObjectType> = [];
    const coverImageUpload = await cloudinary.uploader.upload(coverImage);
    if (imageArray !== undefined) {
      for (let i = 0; i < imageArray.length; i++) {
        const image = await cloudinary.uploader.upload(imageArray[i]);
        imageUrlArray.push({
          publicId: image.public_id,
          secureUrl: image.secure_url,
        });
      }
    }
    console.log(req.seller);
    const product = await Product.create({
      title: title,
      snippet: snippet,
      description: description,
      quantity: quantity,
      price: price,
      coverImage: {
        publicId: coverImageUpload.public_id,
        secureUrl: coverImageUpload.secure_url,
      },
      imageArray: imageUrlArray,
      category: category,
      sellerId: req.seller,
    });
    console.log(product);
    if (product) {
      res.status(200).json({
        message: "Product added",
        category: category,
      });
    }
  } catch (err) {
    console.log(err);
  }
};

This is where I'm uploading the images and it's giving me error in the bit where I try to ping to cloudinary.


Solution

  • Upgrading to NodeJS 20.3.0 fixed it for me, as it seemed to have been a bug with Node 20 as pointed out by others