Check If an URL is Internal or External in JavaScript/TypeScript

mail
Cyrus Kao
Last modified

Knowing whether a link is internal or external is essential for setting rel in HTML a tag. For an external link, noreferrer noopener nofollow is usually recommended. To test a full URL or relative path in JavaScript/TypeScript, we'll be using URL constructor. It's available in both browsers and Node.js.

It's recommended adding at least rel="noopener" to an external HTML anchor with target="_blank" for security reasons.

noopener
Link type noopener in HTML Standard

Configure Base URL

Base URL is the full URL of your site's root, usually the home page (e.g. https://nocache.org). This is for reconstructing a relative path to full URL.

Static

Set the base URL to a static URL, change https://nocache.org to your own URL:

const base = new URL('https://nocache.org');
JavaScript

Dynamic (Browsers Only)

Set the base URL to the root of the current URL, only works in browsers:

const base = new URL(`${window.location.protocol}//${window.location.host}`);
JavaScript

Create Function

Create a function that takes an url argument, returns boolean for whether the URL is internal:

  • JavaScript

    ...
    
    function isInternal(url) {
    	return new URL(url, base).hostname === base.hostname;
    }
    JavaScript
  • TypeScript

    ...
    
    function isInternal(url: string): boolean {
    	return new URL(url, base).hostname === base.hostname;
    }
    TypeScript

Usage

A relative path will always return true since it's reconstructed with the base URL:

console.log(isInternal('/about'));
JavaScript
true
Output

Test full URLs:

console.log(isInternal('https://nocache.org/about'));
JavaScript
true
Output
console.log(isInternal('https://google.com'));
JavaScript
false
Output

Comments

0500