nodejs / nodejs/undici

Avoiding `instanceof Request`, etc.

Open
#2,155 9 comments 7 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug fetch
Dominant language
JavaScript
Stars
7.7k
Forks
880
Avg merge
2d 16h
Merged PRs (30d)
68

Description

In Node.js 18.6, this piece of code doesn't work:

import { fetch } from "undici";

fetch(new Request("https://example.com"));

Error:

TypeError: Failed to parse URL from [object Request]
    at fetch (<>/node_modules/undici/index.js:109:13) {
  [cause]: TypeError [ERR_INVALID_URL]: Invalid URL
      at new NodeError (node:internal/errors:405:5)
      at new URL (node:internal/url:743:13)
      at new Request (<>/node_modules/undici/lib/fetch/request.js:86:21)
      at fetch (<>node_modules/undici/lib/fetch/index.js:137:21)
      at fetch (<>/node_modules/undici/index.js:107:20)
      at file://<>/test.js:3:1
      at ModuleJob.run (node:internal/modules/esm/module_job:192:25)
      at async DefaultModuleLoader.import (node:internal/modules/esm/loader:246:24)
      at async loadESM (node:internal/process/esm_loader:40:7)
      at async handleMainPromise (node:internal/modules/run_main:66:12) {
    input: '[object Request]',
    code: 'ERR_INVALID_URL'
  }
}

This is because instanceof Request fails due to the global Request and the Undici Request not being the same.

https://github.com/nodejs/undici/blob/7153a1c78d51840bbe16576ce353e481c3934701/lib/fetch/request.js#L854

While many libraries accept a fetch argument (like ky), not many libraries accept another set of globals (Request, Response, Headers). Next to that, global.Request is a read-only property in Node.js. I think that instead of using instanceof Undici should be using another type of check for these. (e.g. request[Symbol.toStringTag] === 'Request').

I'd like to collect thoughts and then I'll create a PR.

This would also fix https://github.com/cloudflare/miniflare/issues/454

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start in lib/fetch/request.js around the instanceof check referenced in the issue, then reproduce the Node.js 18.6 example using the global Request and Undici's fetch. Review the comment discussion for the expected cross-global behavior. Done means fetch accepts the global Request without treating it as a URL string, while preserving normal Request handling.

Written by the indexing model from the issue text.

Assessment

Tech stack
javascript, node.js
Domain
api, backend
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Quiet
Clarity
Mostly clear
Newbie friendliness
48/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.