php – Block access to javascript files


I have a javascript file that makes ajax requests to my API but I don't want anyone to discover its link is there any way to block access to this file?

If there is no way to release it so that only the site can access it?


By the time the AJAX request is made, it will always be possible to trace. Therefore, the origin of the request is made on the client. So, what can be done is to perform a validation on the server.


Let's assume you are making the request from the site:

In the index.php file, you can have a PHP instruction that checks if the origin of the request is

  if( $_SERVER['HTTP_ORIGIN'] === '' ){ 
     //seu codigo aqui

This will make only requests coming from the domain, to be executed.

Obs.: The solution above is not immune to failures, there are other aspects that must be taken into account.

Complementing the above solution, you can work with Token well. But for that, it will be necessary to define some criteria:

  1. Whether or not it will generate the Token , for everyone who accesses the site.
  2. The periodicity of the Token .

You may have other items to define, it's worth taking into account the context in which your API will be used.

Scroll to Top