Skip to content

Avoiding instanceof Request, etc. #2155

Description

@hansottowirtz

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.

if (V instanceof Request) {

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 cloudflare/miniflare#454

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't workingfetch

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions