I would like to serve a JS file by CDN, but I want to be able to control the sites/pages that are allowed to use it. (Using the CDN. I know people can still just copy the file if they wanted to.)

Is there a way to control what site/url can request the file? I only have found things like preventing hotlinking (= only allowing the main domain)

I guess the alternative would be just serving the file by CDN and having it send a request to some API and which will then check if it is allowed to use the file. This would cause me & them bandwidth and another request, which, if possible, would be great to keep low. I could serve the file by myself, but I am expecting high request numbers, so I thought a CDN would be better.

1 Answer 1


Many CDNs have built-in hotlinking protection that you can turn on. The method of configuring it differs between each CDN provider, so you'll want to look at your specific CDN provider's support articles to see how they do it.

If built-in hotlink protection is unavailable at your CDN, you could always include a one-liner like this in the critical path of your JavaScript file if you're concerned:

if (window.location.hostname !== 'www.yoursite.example') return;

That will make the JS file totally useless to anyone who tries to hotlink it from a different site.

All in all though, I don't think stuff like that is all that necessary for JavaScript files, because nobody really hotlinks them from untrusted domains like they do with images, due to the security ramifications.

At worst case, hotlinking your JS file could give you near-complete power over their website and its content; at best case (if they had enough foresight to link your JS using SRI but not enough foresight to avoid hotlinking JS altogether), they would give you the power to break the script on their site at any time by moving, removing, or editing it.

  • 1
    Yeah...imagine how much fun you could have if someone hotlinked a JS file :o)
    – Steve
    Nov 22, 2021 at 22:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.