Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/nodejs/undici/llms.txt

Use this file to discover all available pages before exploring further.

undici exposes a set of typed error classes accessible via the errors export. Each error has a code property with a stable string identifier. Use error.code checks rather than instanceof to reliably identify undici errors — this avoids version mismatch issues when Node.js’s bundled undici differs from the installed version.

Importing

import { errors } from 'undici'

// Recommended: check by error code
try {
  const { body } = await request('https://api.example.com/data')
  await body.json()
} catch (err) {
  if (err.code === 'UND_ERR_CONNECT_TIMEOUT') {
    console.error('Connection timed out')
  } else if (err.code === 'UND_ERR_HEADERS_TIMEOUT') {
    console.error('Server did not send headers in time')
  }
}
Avoid instanceof errors.UndiciError checks when using both Node.js built-in fetch (which bundles its own undici) and the installed undici package. The global dispatcher may be from a different undici version. Always check error.code instead.

Error reference

Error ClassCodeDescription
UndiciErrorUND_ERRBase class for all undici errors
ConnectTimeoutErrorUND_ERR_CONNECT_TIMEOUTSocket destroyed due to connect timeout
HeadersTimeoutErrorUND_ERR_HEADERS_TIMEOUTSocket destroyed due to headers timeout
HeadersOverflowErrorUND_ERR_HEADERS_OVERFLOWSocket destroyed due to headers exceeding max size
BodyTimeoutErrorUND_ERR_BODY_TIMEOUTSocket destroyed due to body timeout
InvalidArgumentErrorUND_ERR_INVALID_ARGAn invalid argument was passed
InvalidReturnValueErrorUND_ERR_INVALID_RETURN_VALUEA callback or factory returned an invalid value
RequestAbortedErrorUND_ERR_ABORTEDThe request was aborted via AbortSignal
ClientDestroyedErrorUND_ERR_DESTROYEDAttempt to use a destroyed client
ClientClosedErrorUND_ERR_CLOSEDAttempt to use a closed client
SocketErrorUND_ERR_SOCKETA socket-level error occurred
NotSupportedErrorUND_ERR_NOT_SUPPORTEDUnsupported functionality was used
RequestContentLengthMismatchErrorUND_ERR_REQ_CONTENT_LENGTH_MISMATCHRequest body size doesn’t match Content-Length header
ResponseContentLengthMismatchErrorUND_ERR_RES_CONTENT_LENGTH_MISMATCHResponse body size doesn’t match Content-Length header
InformationalErrorUND_ERR_INFOExpected error with informational reason
ResponseExceededMaxSizeErrorUND_ERR_RES_EXCEEDED_MAX_SIZEResponse body exceeded maxResponseSize limit
SecureProxyConnectionErrorUND_ERR_PRX_TLSTLS connection to a proxy server failed
MessageSizeExceededErrorUND_ERR_WS_MESSAGE_SIZE_EXCEEDEDWebSocket decompressed message exceeded maximum size

SocketError

SocketError includes a .socket property with metadata about the connection:
interface SocketInfo {
  localAddress?: string
  localPort?: number
  remoteAddress?: string
  remotePort?: number
  remoteFamily?: string
  timeout?: number
  bytesWritten?: number
  bytesRead?: number
}
Handling SocketError
import { errors, request } from 'undici'

try {
  await request('https://api.example.com')
} catch (err) {
  if (err.code === 'UND_ERR_SOCKET') {
    console.error('Socket error:', err.message)
    if (err.socket) {
      console.error('Remote:', err.socket.remoteAddress, err.socket.remotePort)
      console.error('Bytes read:', err.socket.bytesRead)
    }
  }
}
The .socket property may be null in some error scenarios even when the error code is UND_ERR_SOCKET.

Timeout errors

Configure timeouts on Client, Pool, or Agent to control when these errors are thrown:
Configuring timeouts
import { Agent, setGlobalDispatcher } from 'undici'

setGlobalDispatcher(new Agent({
  connectTimeout: 5_000,   // UND_ERR_CONNECT_TIMEOUT after 5s
  headersTimeout: 10_000,  // UND_ERR_HEADERS_TIMEOUT after 10s
  bodyTimeout: 30_000      // UND_ERR_BODY_TIMEOUT after 30s
}))

Abort errors

Use AbortController to cancel requests, which throws RequestAbortedError:
Aborting requests
import { request } from 'undici'

const controller = new AbortController()

setTimeout(() => controller.abort(), 5_000)

try {
  const { body } = await request('https://api.example.com/slow', {
    signal: controller.signal
  })
  await body.json()
} catch (err) {
  if (err.code === 'UND_ERR_ABORTED') {
    console.log('Request was aborted')
  }
}

Handling errors comprehensively

Comprehensive error handling
import { request, errors } from 'undici'

async function fetchWithHandling(url) {
  try {
    const { statusCode, body } = await request(url)
    const data = await body.json()
    return { statusCode, data }
  } catch (err) {
    switch (err.code) {
      case 'UND_ERR_CONNECT_TIMEOUT':
        throw new Error(`Could not connect to ${url}: timeout`)
      case 'UND_ERR_HEADERS_TIMEOUT':
        throw new Error(`Server at ${url} did not respond in time`)
      case 'UND_ERR_ABORTED':
        throw new Error('Request cancelled')
      case 'UND_ERR_SOCKET':
        throw new Error(`Network error: ${err.message}`)
      default:
        throw err
    }
  }
}

Build docs developers (and LLMs) love