Validate a URL in JavaScript
Intermediate · 3 min read
Profile pages let you add a website link. Comment boxes turn URLs into clickable links. Bookmark tools, link shorteners and "share this page" forms all need to know whether a piece of text is a real web address before they save it or show it as a link.
In this tutorial you will check URLs in JavaScript. You will try a hand-written pattern first, see where it goes wrong, and then switch to the URL parser that browsers and Node.js already include. Then you will add the check that keeps a link from running code on your page. You need to know try and catch and what a Set is. The rest is explained as we go.
The parts of a URL
Here is one URL, split into its parts:
https://example.com:8080/routes?from=Ojota#seats
protocol: https:
host: example.com
port: 8080
path: /routes
query: ?from=Ojota
fragment: #seats
Most parts are optional. The protocol is not. example.com on its own is a domain name, not a URL.
The URL parser
JavaScript has a built-in URL class that understands all of this. new URL(text) breaks a URL into its parts, and throws an error when the text isn't a URL:
const url = new URL('https://example.com:8080/routes?from=Ojota');
console.log(url.protocol); // 'https:'
console.log(url.hostname); // 'example.com'
console.log(url.port); // '8080'
Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.
9 Validate a URL
fairCheck whether a string is a valid URL. Compare a pattern against the parser the browser already has.
Stuck? Three hints, smallest first
- 1.
URL.canParse(value), ornew URL()in atry/catch, is the real answer. - 2. The parser accepts things you may not want, like
javascript:anddata:. - 3. So validating a URL is two questions: is it parseable, and is its protocol one you allow?
Step 1: a hand-written pattern
A typical pattern says: http or https, then ://, then labels separated by dots, an optional port, and an optional path. s? makes the s optional, and \/ is a slash written so it doesn't end the pattern:
const URL_PATTERN = /^https?:\/\/[A-Za-z0-9-]+(\.[A-Za-z0-9-]+)+(:\d+)?(\/[^\s]*)?$/;
console.log(URL_PATTERN.test('https://example.com/a/b')); // true
console.log(URL_PATTERN.test('example.com')); // false
console.log(URL_PATTERN.test('https://localhost:3000')); // false
That last result is wrong. https://localhost:3000 is a perfectly good URL, the one you open every day while building a site. The pattern refuses it because it insists on a dot in the host. Hand-written URL patterns are full of small mistakes like this.
Step 2: let the parser decide
Instead of a pattern, try to build a URL. If it works, the text parses. If new URL throws, catch returns false:
const parses = (value) => {
try { new URL(value); return true; } catch { return false; }
};
console.log(parses('https://localhost:3000')); // true
console.log(parses('example.com')); // false
console.log(parses('not a url')); // false
console.log(parses('')); // false
Newer engines also have URL.canParse(value), which does the same thing in one call.
Step 3: the danger of "it parsed"
Now try these:
const parses = (value) => {
try { new URL(value); return true; } catch { return false; }
};
console.log(parses('javascript:alert(1)')); // true
console.log(parses('ftp://files.example.com')); // true
console.log(parses('mailto:ada@example.com')); // true
All three are valid URLs. The first one is a problem. If you take a URL from a user and put it in a link, clicking a javascript: link runs the code after the colon on your page. That is how a harmless-looking link becomes an attack.
Step 4: allow only web protocols
So validating a URL is really two questions: does it parse, and is its protocol one you allow? Keep the allowed protocols in a Set, and check url.protocol against it:
const ALLOWED = new Set(['http:', 'https:']);
function isSafeWebUrl(value) {
try {
const url = new URL(value);
return ALLOWED.has(url.protocol);
} catch {
return false;
}
}
console.log(isSafeWebUrl('https://example.com')); // true
console.log(isSafeWebUrl('https://localhost:3000')); // true
console.log(isSafeWebUrl('javascript:alert(1)')); // false
console.log(isSafeWebUrl('ftp://files.example.com')); // false
console.log(isSafeWebUrl('example.com')); // false
This is an allow-list: a short list of what is permitted, with everything else refused. A block-list of bad protocols would always miss one.
The full solution
The panel runs a list of URLs through all three checks: the pattern, the parser, and the safe web URL check. Press Run and look for the rows where the parser says yes and the safe check says no.
// A typical hand-written pattern. Reasonable, and it disagrees with the parser.
const URL_PATTERN = /^https?:\/\/[A-Za-z0-9-]+(\.[A-Za-z0-9-]+)+(:\d+)?(\/[^\s]*)?$/;
const looksLikeUrl = (value) => URL_PATTERN.test(value);
// What the browser actually does.
const parses = (value) => {
try { new URL(value); return true; } catch { return false; }
};
/* Validating a URL is really two questions. The second one is the security
question, and it is the one people forget: a parseable URL can be
javascript:alert(1), which is how a link becomes an attack. */
const ALLOWED = new Set(['http:', 'https:']);
function isSafeWebUrl(value) {
try {
const url = new URL(value);
return ALLOWED.has(url.protocol);
} catch {
return false;
}
}
const cases = [
'https://example.com',
'http://example.com/routes?from=Ojota#seats',
'https://example.com:8080/a/b',
'https://sub.domain.example.co.uk',
'example.com',
'https://localhost:3000',
'ftp://files.example.com',
'javascript:alert(1)',
'data:text/html,<script>alert(1)</script>',
'mailto:ada@example.com',
'not a url',
'',
];
for (const u of cases) {
console.log(JSON.stringify(u).slice(0, 42).padEnd(44),
'pattern:', String(looksLikeUrl(u)).padEnd(6),
'parses:', String(parses(u)).padEnd(6),
'safe web url:', isSafeWebUrl(u));
}
Output
19 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 19 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('an https URL is valid', isSafeWebUrl('https://example.com'), true);
test('with a path, query and fragment', isSafeWebUrl('http://example.com/routes?from=Ojota#seats'), true);
test('with a port', isSafeWebUrl('https://example.com:8080/a/b'), true);
test('with subdomains', isSafeWebUrl('https://sub.domain.example.co.uk'), true);
test('a bare domain is not a URL', isSafeWebUrl('example.com'), false);
test('and the parser agrees', parses('example.com'), false);
test('nonsense is refused', isSafeWebUrl('not a url'), false);
test('an empty string is refused', isSafeWebUrl(''), false);
test('localhost parses', parses('https://localhost:3000'), true);
test('but the pattern rejects it, needing a dot', looksLikeUrl('https://localhost:3000'), false);
test('which is the pattern being wrong, not localhost', parses('https://localhost:3000'), true);
test('ftp parses as a URL', parses('ftp://files.example.com'), true);
test('but is not a web URL', isSafeWebUrl('ftp://files.example.com'), false);
test('javascript: PARSES as a URL', parses('javascript:alert(1)'), true);
test('which is exactly why the protocol must be checked', isSafeWebUrl('javascript:alert(1)'), false);
test('a data: URL parses too', parses('data:text/html,<script>alert(1)</script>'), true);
test('and is also refused', isSafeWebUrl('data:text/html,<script>alert(1)</script>'), false);
test('mailto: parses and is not a web URL', [parses('mailto:ada@example.com'), isSafeWebUrl('mailto:ada@example.com')], [true, false]);
test('URL.canParse agrees with the try/catch', URL.canParse('https://example.com'), parses('https://example.com'));
Do not write a pattern for this. new URL() is a complete, standards-tracking parser that already exists in every browser and in Node, and the assertions show the hand-written pattern rejecting https://localhost:3000 — which is a perfectly good URL you will use every day — because it insists on a dot.
The security point is the one to carry away. javascript:alert(1) and data:text/html,... are both valid URLs, and the assertions confirm the parser accepts both. So if you take a URL from a user and put it in an href, "it parsed" is not enough: that is how a link becomes script execution in your page. Check url.protocol against an allow-list of the schemes you actually want, which for a link is almost always just http: and https:. An allow-list, not a block-list — you will not think of every scheme worth blocking.
Common mistakes
- Writing your own URL pattern. It will refuse real URLs like
localhostand accept things it shouldn't. Usenew URL. - Stopping at "it parses".
javascript:anddata:URLs parse fine. Always check the protocol before using a URL in a link. - Using a block-list. Listing bad protocols means guessing every one. List the good ones instead.
Try it yourself
- Change
isSafeWebUrlto also allowmailto:links. - Write
hostOf(value)that returns the hostname of a safe URL, ornullfor anything else. - Use
url.searchParams.get('from')to read'Ojota'fromhttps://example.com/routes?from=Ojota.