In a pet project that I worked on recently, one of the requirements was to allow users to submit the URL to their Facebook social media profile. This article describes how I ensured that only Facebook profile URLs were submitted.
JavaScript was used but it does not matter as much as the algorithm used; and that algorithm is described here.
function validateUrl(url, expectedOrigin) {
const urlObject = new URL(url);
const originPattern = new RegExp(expectedOrigin.toLowerCase() + "$");
const isValid = urlObject.origin.toLowerCase().match(originPattern);
if (!isValid) {
throw new Error("Invalid URL");
}
return `${urlObject.origin}${urlObject.pathname}`;
}
console.log(validateUrl("https://facebook.com/hi-there", "facebook.com")); //https://facebook.com/hi-there
console.log(validateUrl("https://handbook.com/hi-there", "facebook.com")); // throws error
The goal of the algorithm is to extract the domain name or the origin of the submitted URL and verify that it is the same as the expected origin. Since JavaScript is being used, we can use the URL API to extract the origin. Using RegEx or any string comparator, we can verify if the origin of the URL submitted matches the one that is expected by checking that it ends with the expected origin.
RegEx was used for this article because it cuts across many programming languages. In JavaScript, we can use endsWith .
Checking that it ends with is for cases where a URL like web.facebook.com is submitted. web.facebook.com is valid for the use case.
This method can be used on the frontend and the backend with Node.js. The URL API exists in both environments.
Cheers!