Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Timeout error when calling external API from node.js

I have the following index.js(node v19.6.0) with POST request that calls external API and register a webhook. The url of the hook I am registering already works and tested it.

I googled the error but I couldn't find any results. The error comes when I call /register/hook method. It shows that there is a timeout but doesn't give me much more detail. Is the issue from the API provider or the way I am making REST calls ?

The code was generated by Alchemy.

const express = require('express');
const app = express();

const port = 8080;
app.listen(port, () => {
    console.log(`listening on port ${port}`)
})

app.post("/register/hook", (req, res) => {
    const options = {
        method: 'POST',
        headers: {
          accept: 'application/json',
          'X-Alchemy-Token': 'abc...def',
          'content-type': 'application/json'
        },
        body: JSON.stringify({
          AddressWebhookParams: {addresses: ['0xe592427a0aece92de3edee1f18e0157c05861564']},
          url: 'https://webhook.site/dfb04cab-8ca9-40f1-a522-66918d4a7015',
          type: 'ADDRESS_ACTIVITY'
        })
      };
      
      fetch('https://alchemy-sdk-core-example.com/create-webhook', options)
        .then(response => response.json())
        .then(response => console.log(response))
        .catch(err => console.error(err));
})

Here is the error:

TypeError: fetch failed
    at Object.fetch (node:internal/deps/undici/undici:12789:11)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
  cause: ConnectTimeoutError: Connect Timeout Error
      at onConnectTimeout (node:internal/deps/undici/undici:8236:28)
      at node:internal/deps/undici/undici:8194:50
      at Immediate._onImmediate (node:internal/deps/undici/undici:8225:13)
      at process.processImmediate (node:internal/timers:475:21) {
    code: 'UND_ERR_CONNECT_TIMEOUT'
  }
}

  [1]: https://docs.alchemy.com/reference/sdk-create-webhook
like image 499
WowBow Avatar asked May 30 '26 21:05

WowBow


1 Answers

I fixed it by adding

import { fetch, setGlobalDispatcher, Agent } from 'undici'
...
setGlobalDispatcher(new Agent({ connect: { timeout: 60_000 } }) )

before my fetch to configure the timeout. Of course you should first install undici

like image 187
Kavoos Avatar answered Jun 01 '26 11:06

Kavoos