NoCache

Table of Contents

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

Cyrus Kao
Last modified on .

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 the URL constructor. It's available in both browsers and Node.js.

It's recommended to add 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)

Setting 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

Test URL

Create a function that takes an url argument, returns a boolean value 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

Sign in to leave a comment.