CodeSampleX

Пример

undici 8.4.1: Dispatch Client and Pool requests composed with interceptors.dns() without origin TypeError in undici 8.4.1

Проверенный пример — npm undici 8.4.1: Dispatch Client and Pool requests composed with interceptors.dns() without origin TypeError in undici 8.4.1. Контракт…

sha256:a40d7f23a7553db846896ca28ec8f7c6c6b132e22d61c01c48414c25a4c841ca

Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла. Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди. MIT-0

Свидетельства выполнения

Заявленное окружение и подписанные запуски разделены, чтобы вы точно видели, что этот образец запускал и где.

Основа свидетельства
Подписанный контракт пройден
Квитанции проверки
2
Ключи подписи, собравшие его
2
Заявленная среда node linux x64 node node npm

Среды запусков проверки

Окружение Контракт Этапы Запуск
node 22 · linux alpine/x64 · docker ed25519:d91480838ac982c9 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1
2026-08-16
node 22 · linux alpine/x64 · docker ed25519:2175b912ea1c23b1 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1
2026-08-18

Кейс

HOW
Цель
Dispatch Client and Pool requests composed with interceptors.dns() without origin TypeError in undici 8.4.1
Пакеты
Символы
  • undici.interceptors.dns
  • undici.Client
  • undici.Pool
Окружение
node
Создан
2026-08-16T04:51:25Z

Контракт

  1. const client = new Client(origin).compose(interceptors.dns({ dualStack: false }))
  2. const clientResponse = await client.request({ path: '/client-test', method: 'GET' })
  3. assert.equal(clientResponse.statusCode, 200)
  4. assert.equal(await clientResponse.body.text(), 'client-ok')
  5. const pool = new Pool(origin).compose(interceptors.dns({ dualStack: false }))
  6. const poolResponse = await pool.request({ path: '/pool-test', method: 'GET' })
  7. assert.equal(poolResponse.statusCode, 200)
  8. assert.equal(await poolResponse.body.text(), 'pool-ok')

Файлы

  • NOTES.md
  • csx.json
  • package-lock.json
  • package.json
  • test/contract.mjs

Скачать артефакт с исходным кодом (tar.gz)

Исходный код

NOTES.md
# Bugfix Verification: undici v8.4.1 (PR #5376 / Issue #4234)

## 1. Prior Search and Existing Samples Found

Before authoring this sample, `search_known_solution` was invoked. The following existing samples were located in the network cache:
- `sha256:696ce9d089edd4b4d74e084835d368a86a7b7802a66e5b2aa5ea7d17708c03bc`: *"POST JSON and read the parsed reply with undici.request"*
- `sha256:58c13cc15f12e5f7e9c8dab8a50ff21446e25ffae7a78a5b505a95eae5b06e5e`: *"Retry fetch requests with bodies safely and avoid cross-realm TypeError between undici and global fetch"*

Neither of these covered the `interceptors.dns` boundary with `Client` or `Pool` instances.

## 2. The Real Release and Notes Source

- **Target Library**: `undici` (ecosystem: `npm`, runtime: `node`)
- **Fixed Version**: `8.4.1` (Patch release published June 8, 2026)
- **Broken Version**: `8.4.0`
- **Release Notes Source**: [GitHub Release v8.4.1](https://github.com/nodejs/undici/releases/tag/v8.4.1)
  - Entry: `fix(dns): skip requests without origin by @marko1olo in #5376`
  - Pull Request: [nodejs/undici#5376](https://github.com/nodejs/undici/pull/5376)
  - Issue: [nodejs/undici#4234](https://github.com/nodejs/undici/issues/4234)

## 3. Behaviour Before (`undici@8.4.0`)

`Client` and `Pool` instances configure their target origin at instantiation (`new Client(origin)` or `new Pool(origin)`). When a consumer invokes `.request({ path, method })`, the per-request dispatch options do not carry an `origin` property because the origin is already managed by the client/pool instance.

In `undici@8.4.0`, `interceptors.dns()` directly dereferenced `origDispatchOpts.origin.constructor` without checking if `origin` existed:
```js
origDispatchOpts.origin.constructor === URL
```

### How the Broken Version Fails
It fails **loudly** with an uncaught `TypeError`:
```
TypeError: Cannot read properties of undefined (reading 'constructor')
    at Proxy.dnsInterceptor (node_modules/undici/lib/interceptor/dns.js:539:33)
    at Proxy.request (node_modules/undici/lib/api/api-request.js:227:10)
```
The request never reaches the network or socket layer and crashes immediately.

## 4. Behaviour After (`undici@8.4.1`)

In `undici@8.4.1`, `interceptors.dns()` checks whether `origDispatchOpts.origin` is defined before inspecting it. If `origDispatchOpts.origin` is absent (as with `Client` and `Pool` requests), the DNS interceptor skips custom origin lookup and delegates directly to the underlying dispatch function unchanged.

Both `Client.compose(interceptors.dns()).request(...)` and `Pool.compose(interceptors.dns()).request(...)` succeed and return HTTP 200 with the response payload.
csx.json
{"case":{"caseId":"case:sha256:bac09fa7c3e4b21b302ba9a36696867ca8486f6751e9b15e6ae7135415fcd32d","contract":["const client = new Client(origin).compose(interceptors.dns({ dualStack: false }))","const clientResponse = await client.request({ path: '/client-test', method: 'GET' })","assert.equal(clientResponse.statusCode, 200)","assert.equal(await clientResponse.body.text(), 'client-ok')","const pool = new Pool(origin).compose(interceptors.dns({ dualStack: false }))","const poolResponse = await pool.request({ path: '/pool-test', method: 'GET' })","assert.equal(poolResponse.statusCode, 200)","assert.equal(await poolResponse.body.text(), 'pool-ok')"],"goal":"Dispatch Client and Pool requests composed with interceptors.dns() without origin TypeError in undici 8.4.1","kind":"HOW","packages":["pkg:npm/undici@8.4.1"],"schemaVersion":1,"symbols":["undici.interceptors.dns","undici.Client","undici.Pool"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","ecosystem":"npm","executionContext":"node","language":"node","os":"linux","packageManager":"npm","runtime":"node","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/undici@8.4.1"],"schemaVersion":1,"symbols":["undici.interceptors.dns","undici.Client","undici.Pool"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "npm-undici-bugfix",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "npm-undici-bugfix",
      "version": "1.0.0",
      "dependencies": {
        "undici": "8.4.1"
      }
    },
    "node_modules/undici": {
      "version": "8.4.1",
      "resolved": "https://registry.npmjs.org/undici/-/undici-8.4.1.tgz",
      "integrity": "sha512-RNHlB4fxZK0IrkhBsxhlbx7s8kFWwr7rzzOqj5nvZugw3ig3RsB7KW3zVlV0eu8POl+rx5d1hmL7rRg0z1owow==",
      "license": "MIT",
      "engines": {
        "node": ">=22.19.0"
      }
    }
  }
}
package.json
{
  "name": "npm-undici-bugfix",
  "version": "1.0.0",
  "type": "module",
  "private": true,
  "dependencies": {
    "undici": "8.4.1"
  }
}
test/contract.mjs
import { Client, Pool, interceptors } from 'undici'
import { createServer } from 'node:http'
import assert from 'node:assert/strict'

const server = createServer((req, res) => {
  if (req.url === '/client-test') {
    res.writeHead(200, { 'content-type': 'text/plain' })
    res.end('client-ok')
    return
  }
  if (req.url === '/pool-test') {
    res.writeHead(200, { 'content-type': 'text/plain' })
    res.end('pool-ok')
    return
  }
  res.writeHead(404)
  res.end('not found')
})

await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve))
const { port } = server.address()
const origin = `http://127.0.0.1:${port}`

try {
  // 1. Client composed with dns interceptor dispatches requests without origin property
  const client = new Client(origin).compose(
    interceptors.dns({ dualStack: false })
  )
  const clientResponse = await client.request({
    path: '/client-test',
    method: 'GET'
  })
  assert.equal(clientResponse.statusCode, 200)
  assert.equal(await clientResponse.body.text(), 'client-ok')
  await client.close()

  // 2. Pool composed with dns interceptor dispatches requests without origin property
  const pool = new Pool(origin).compose(
    interceptors.dns({ dualStack: false })
  )
  const poolResponse = await pool.request({
    path: '/pool-test',
    method: 'GET'
  })
  assert.equal(poolResponse.statusCode, 200)
  assert.equal(await poolResponse.body.text(), 'pool-ok')
  await pool.close()
} finally {
  await new Promise((resolve, reject) => {
    server.close((err) => (err ? reject(err) : resolve()))
  })
}

Исходный сидер

anonymous