next.js: NextJS 14 returns fetch failed with UND_ERR_CONNECT_TIMEOUT error on serverless function

Link to the code that reproduces this issue

https://codesandbox.io/p/devbox/gifted-shirley-mzlvgy?file=%2Fapp%2Fapi%2Froute.js%3A1%2C1-39%2C1

To Reproduce

  1. From a client-side component, start a fecth POST request to an API endpoint (route handler) on form submission;
  2. On an API serverless function realise another fetch POST request to an external API (in my case I used Slack message API);
  3. On a production environment hosted on Vercel, around 70% of the requests to Slack are working while another 30% fail returning 500 server error code “UND_ERR_CONNECT_TIMEOUT”.

Systems:

  • Next.js v14.1.4
  • Errors happen in both Pages and App Router
  • Could only reproduce on a Prod environment hosted on Vercel
  • Serverless function running node v20x
  • Requests to external APIs from a client component work fine. Only serverless functions error out
  • Slack API is working fine. Tested on other pure React apps and Postman and had no errors at all
  • Problem seems to happen only on external API calls (tested Mailchimp as well and failed less times than Slack but still failing);

Full error message: Unhandled Rejection: TypeError: fetch failed at node:internal/deps/undici/undici:12345:11 at process.processTicksAndRejections (node:internal/process/task_queues:95:5) { cause: ConnectTimeoutError: Connect Timeout Error at onConnectTimeout (node:internal/deps/undici/undici:7492:28) at node:internal/deps/undici/undici:7448:50 at Immediate._onImmediate (node:internal/deps/undici/undici:7480:13) at process.processImmediate (node:internal/timers:478:21) at process.callbackTrampoline (node:internal/async_hooks:130:17) { code: 'UND_ERR_CONNECT_TIMEOUT' } } Node.js process exited with exit status: 128. The logs above can help with debugging the issue.

Current vs. Expected behavior

Currently some external API calls from a serverless function are returning unhandled fetch errors. Expected behaviour is no errors being returned and API call succeeding.

Provide environment information

Operating System:
Vercel Servers

Binaries:
Node: v20x (default vercel v20 setting)
npm: 10.2.3
yarn: 1.22.19
build command: yarn build

Relevant Packages: 
next: 14.1.4
react: 18.2.0
react-dom: 18.2.0

Next.js Config:
/** @type {import('next').NextConfig} */
const nextConfig = {
  reactStrictMode: true,
  trailingSlash: true,
  images: {
    remotePatterns: [
      {
        protocol: 'https',
        hostname: 'site.com',
        port: '',
        pathname: '/wp-content/uploads/**',
      },
    ],
  },
}

module.exports = nextConfig;

Which area(s) are affected? (Select all that apply)

Module Resolution, Pages Router, Runtime

Which stage(s) are affected? (Select all that apply)

Vercel (Deployed)

Additional context

Additional information about the issue and more cases can be found at this discussion: https://github.com/vercel/next.js/discussions/57384

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Reactions: 14
  • Comments: 28 (5 by maintainers)

Most upvoted comments

I successfully resolved the issue by configuring the undici global dispatcher in the root layout. CleanShot 2024-06-17 at 20 03 50@2x

Facing same issue in my project using nextjs 14.

I am also getting a bunch of undici errors as well recently. These are the 3 main ones

“next”: “^14.2.3”, node v20.9.0

I also tried setting vercel env variable: NODE_OPTIONS=–dns-result-order=ipv4first but it has not solved the issue

`TypeError: fetch failed
    at node:internal/deps/undici/undici:12618:11
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
  cause: Error: connect ETIMEDOUT 76.76.21.241:443
      at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1555:16)
      at TCPConnectWrap.callbackTrampoline (node:internal/async_hooks:128:17) {
    errno: -110,
    code: 'ETIMEDOUT',
    syscall: 'connect',
    address: '76.76.21.241',
    port: 443
  }`
  

  `TypeError: fetch failed
    at node:internal/deps/undici/undici:12618:11
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
  cause: ConnectTimeoutError: Connect Timeout Error
      at onConnectTimeout (node:internal/deps/undici/undici:7760:28)
      at node:internal/deps/undici/undici:7716:50
      at Immediate._onImmediate (node:internal/deps/undici/undici:7748:13)
      at process.processImmediate (node:internal/timers:476:21)
      at process.callbackTrampoline (node:internal/async_hooks:128:17) {
    code: 'UND_ERR_CONNECT_TIMEOUT'
  }
}`

`TypeError: fetch failed
    at node:internal/deps/undici/undici:12618:11
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
  cause: [Error: C0AFB780CE7F0000:error:0A00010B:SSL routines:ssl3_get_record:wrong version number:ssl/record/ssl3_record.c:355:
  ] {
    library: 'SSL routines',
    reason: 'wrong version number',
    code: 'ERR_SSL_WRONG_VERSION_NUMBER'
  }
}`

@andremendonca03

  1. We are getting these issues in server-rendered pages. We are fetching apis and creating pages during build.
  2. Same apis are working in browser during runtime.
  3. I am randomly getting this issue; not every time. Once issue occurs, for rest of the day, it behaves same. But next day again it starts working.
Node: 18.17.1
Nextjs: 14.2.3

Thanks. So what can I do in order to eliminate this issue?

@ornakash, I just included NODE_OPTIONS=--dns-result-order=ipv4first in Vercel’s environment variables for our project, and everything works fine.

Note that setting --dns-result-order=ipv4first prioritizes IPv4 addresses over IPv6 addresses but does not disregard IPv6 addresses entirely. Both IPv4 and IPv6 addresses are still resolved and included in the results, but IPv4 addresses appear first in the list. This configuration can be useful when you prefer IPv4 connectivity but still want to support IPv6.

Alright, this suggestion https://github.com/nodejs/undici/issues/1531#issuecomment-1416212916 might be the fix for UND_ERR_CONNECT_TIMEOUT error. After some additional research and debugging, I tried using dns.lookup(), dns.resolve4(), and dns.resolve6() to determine which family (IPv4 or IPv6) the DNS I am accessing supports. It turns out that it supports IPv4.

Same problem here. All day yesterday, we were getting UND_ERR_CONNECT_TIMEOUT errors only on Vercel’s production build attempts. It was working when built locally. We’re still on Next13.

However, at 4:30 am, I tried to build it again in production, and everything worked fine.

This is weird. We may still encounter this issue in future builds. Hoping for someone to find a fix for this. I’ll also continue to observe.

Err log:

ERROR FETCH ITEMPAGE GETSTATICPATHS: TypeError: fetch failed

at Object.fetch (node:internal/deps/undici/undici:11731:11) at process.processTicksAndRejections (node:internal/process/task_queues:95:5) at async getStaticPaths (/vercel/path0/.next/server/pages/used-cars/[slug]/[itemPage].js:1471:26) at async buildStaticPaths (/vercel/path0/node_modules/next/dist/build/utils.js:598:33) at async /vercel/path0/node_modules/next/dist/build/utils.js:933:115 at async Span.traceAsyncFn (/vercel/path0/node_modules/next/dist/trace/trace.js:79:20) { cause: ConnectTimeoutError: Connect Timeout Error at onConnectTimeout (node:internal/deps/undici/undici:6869:28) at node:internal/deps/undici/undici:6825:50 at Immediate._onImmediate (node:internal/deps/undici/undici:6857:13) at process.processImmediate (node:internal/timers:476:21) { code: 'UND_ERR_CONNECT_TIMEOUT' } }

Facing the same problem with Nextjs 14.2.3 and node 20 under comporate http_proxy network. In build time, Nextjs is trying to fetch some cloudflare addresses

[cause]: ConnectTimeoutError: Connect Timeout Error (attempted addresses: 104.16.24.34:443, 104.16.28.34:443, 104.16.26.34:443, 104.16.2.35:443, 104.16.0.35:443, 104.16.27.34:443, 104.16.31.34:443, 104.16.1.35:443, 104.16.30.34:443, 104.16.25.34:443, 104.16.29.34:443, 104.16.3.35:443)