40
let url = new URL("https://stackoverflow.com/questions/ask")

It will get an error like this:

URL is not defined

Actually, in modern browsers, it works well. However, if you run it in the node.js environment, you will get an error like that.

I researched the documentation, it says it's a global class:

Browser-compatible URL class, implemented by following the WHATWG URL Standard. Examples of parsed URLs may be found in the Standard itself. The URL class is also available on the global object.

So, what's the problem?

3
  • 12
    Your Node version is old. There's URL global in Node 10. As for older versions, see the answer. Sep 29, 2018 at 8:53
  • 2
    yes, you are right, my node.js version is 8
    – zzzgoo
    Sep 29, 2018 at 8:58
  • In the hopes of helping someone who comes here with the same issue, I just spent a frustrating hour finding out that this is the error message you will get if you try to run npm install from OUTSIDE OF a lando container.
    – mmrtnt
    Dec 10, 2021 at 20:13

3 Answers 3

63

Try to add this line:

var URL = require('url').URL;

The full example is here:

var URL = require('url').URL;
var myURL = new URL('http://www.example.com/foo?bar=1#main');

console.log(myURL.host);

// prints 'www.example.com'

All of those are from this amazing tutorial.

2
  • What file? Where are you supposed to add this line?
    – Sam
    Oct 29, 2019 at 21:57
  • Nodejs official docs don't show the require. So that is good to know. Jan 28, 2020 at 15:39
3

URL is a global. Make sure you're using Node.js 10 or later. I had the same problem when using version v8.11.2.

You can use the following command to upgrade your node on Mac OS

brew upgrade node

or download from nodejs official website.

1
  • Is there any way to resolve this issue with v8? Oct 19, 2022 at 6:54
1

Sometimes you just have to change your local version of node:

for example: nvm use 12.18.3

but earlier check what versions you already have nvm list

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.