How to prevent a function from being successfully called from the browser

Hi,

Is there any way to prevent a function from running from the browser, i.e. it can only be run if the call comes from a netlify page? I’m make a call (/.netlify/functions/xxx) and it works as it should, but I don’t want it to be accessible from a browser. It can only be called from a page off netlify. I’m coming from the php world, and that was not a problem there. Just wondering how to do it on netlify. Here’s an example of a script from my account that can be called from the browser. Is it possible to not allows that?

https://eager-johnson-677c66.netlify.app/.netlify/functions/protected

Thanks

You can check for event.headers.host and match it with proces.env.URL or something like that, I don’t remember perfectly. However, it’s not 100% safe. Anyone desperate enough can spoof the headers and get access to the function. Sadly, there is no other way.

I don’t recall where it came from but the old saying goes “You can latch the gate, but you can’t lock it”. A Netlify Function is specifically designed to be callable from the public internet. You can check that the invoker is a particular web URL, but that can be spoofed by a knowledgeable user. You can add a token to your webpage that gets passed to the function, but by virtue of it being on a webpage (public), the token can be found and again, spoofed by a knowledgeable user. These are various ways of latching the gate. You can’t lock it.

Unless you setup a user-login framework with Netlify Identity and want to go that route.

That said, this does feel like an XY problem — we may be better able to help you get where you want to go if you can give us more context around the problem you’re trying to solve for directly :slight_smile:


Jon

I understand what you’re saying. Here’s a bit more context. A string of key/values is passed to the function. The function takes that string, encrypts it, and outputs the result. Hopefully that helps.

Hey there, @tddesign

It has been a few days since any activity has happened on this thread. Are you still encountering obstacles with this?

Hi,

I’ve come to the conclusion that I can only do so much regarding this issue, and have accepted the limitations regarding my question. All done here. Thanks.

1 Like

Thank you for letting us know, @tddesign . Please do not hesitate to bring future questions our way.