Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Restrict REST API access to only my website

I created MongoDB and Node.js REST API for my website. I am accessing my database data from the API and showing it on my website. I am doing these things locally on localhost.

Now I want to host my REST API. I don't have any idea regarding hosting. If I host my REST API somewhere and start getting data through its endpoints, then anybody can use those endpoints and access my data, but I want to restrict it to my website only. Meaning, that only my website can make requests to that API, no other websites can make a request. If other websites try to access it, it should show an error. How can I achieve this? Can someone please explain me step by step how do I do this?

like image 350
ZaihamM Code Avatar asked Oct 26 '25 06:10

ZaihamM Code


1 Answers

I think you are referring to CORS. You need to set your API to have a response header like this on all requests:

Access-Control-Allow-Origin: https://yourSiteDomain.com

You can read more about it here: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin

Other people can still access your API directly though, through postman etc.

like image 74
alexvdvalk Avatar answered Oct 28 '25 21:10

alexvdvalk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!