Validating a URL in Node.js

There's a package called valid-url

var validUrl = require('valid-url');

var url = "http://bla.com"
if (validUrl.isUri(url)){
    console.log('Looks like an URI');
} 
else {
    console.log('Not a URI');
}

Installation:

npm install valid-url --save

If you want a simple REGEX - check this out


There is no need to use a third party library.

To check if a string is a valid URL

  const URL = require("url").URL;

  const stringIsAValidUrl = (s) => {
    try {
      new URL(s);
      return true;
    } catch (err) {
      return false;
    }
  };

  stringIsAValidUrl("https://www.example.com:777/a/b?c=d&e=f#g"); //true
  stringIsAValidUrl("invalid"): //false

Edit

If you need to restrict the protocol to a range of protocols you can do something like this

const { URL, parse } = require('url');

const stringIsAValidUrl = (s, protocols) => {
    try {
        new URL(s);
        const parsed = parse(s);
        return protocols
            ? parsed.protocol
                ? protocols.map(x => `${x.toLowerCase()}:`).includes(parsed.protocol)
                : false
            : true;
    } catch (err) {
        return false;
    }
};

stringIsAValidUrl('abc://www.example.com:777/a/b?c=d&e=f#g', ['http', 'https']); // false
stringIsAValidUrl('abc://www.example.com:777/a/b?c=d&e=f#g'); // true

Edit

Due to parse depreciation the code is simplified a little bit more. To address protocol only test returns true issue, I have to say this utility function is a template. You can adopt it to your use case easily. The above mentioned issue is covered by a simple test of url.host !== ""

const { URL } = require('url');

const stringIsAValidUrl = (s, protocols) => {
    try {
        url = new URL(s);
        return protocols
            ? url.protocol
                ? protocols.map(x => `${x.toLowerCase()}:`).includes(url.protocol)
                : false
            : true;
    } catch (err) {
        return false;
    }
};