Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

bentz's avatar
Level 4

Secure Laravel API Endpoint Consumed Solely by Javascript?

Hi folks - has anyone here had experience setting up a Laravel API endpoint that was to be consumed solely by Javascript on someone else's site? I'm trying to determine how that API endpoint could be properly protected.

I have a request to build an api endpoint and provide multiple clients with a javascript they can inject into their page that will make calls back to my api endpoint. I have zero control over these client websites, except for what I can accomplish through javascript, and therefore, I cannot implement anything like a server to server request (which would be ideal).

Anything I can think of to secure the endpoint using any form of token or authentication in javascript can be reproduced by a malicious user to gain access to my api.

Hoping someone else has an idea on how best to accomplish this. I can't be the only one, but google hasn't been a great resource for this as everyone else is typically just using some form of security that requires control over the end-user website or authentication outside of the browser.

0 likes
3 replies
martinbean's avatar

@bentz Just check the referring URL, and compare it against a whitelist. Only allow requests from domains you’ve authored to implement the widget or whatever it is.

bentz's avatar
Level 4

Thanks @martinbean. I have thought of that and do think it's a necessary step. Referrer is something that is easily spoofed, so not the best thing to rely on solely.

After giving this a lot more thought, I'm thinking the solution is a lot of these little steps like referrer check, IP/fingerprint request throttling, proxy script to hide api url, etc.... There just doesn't seem to be a viable single secure solution for client side api consumption.

martinbean's avatar
Level 80

@bentz No, there isn’t, because as you say, anything client-side can be spoofed.

Services offering some form of JavaScript embed usually use a combination of a token or key, and then the ability to set whitelisted domains in their admin panel.

So think of things like reCAPTCHA, Font Awesome, etc. You’ll get a unique code to use client-side, but then you’ll also be able to specify the domains that key should be used with in your admin panel.

Please or to participate in this conversation.