How to limit access to a pages function (serverless)

Hi there,
I’m completely new to pages and serverless functions. I was just able to setup my first (incredibly basic) serverless function.

export async function onRequestGet(request) {
	const res = await fetch(``);
	const data = await res.json();
	const info = data.category;
	return new Response(info);

It works perfectly, but noticed that I can access the api directly in the browser – how can I limit the origin of who can access this? I’d like to limit it to my app/website.

I tried looking this up online and it seems that I need to set a Cross-Origin-Resource-Policy, but have no idea how to get started with this. As mentioned above my usecase is super simple, but would like to limit the origin of the request.

If the objective here is to allow accessing the function only when visiting your website there isn’t much you can do, short of implementing some sort of (even basic) auth check, that your website adds.

This will not prevent usage if someone wants to, but it’s a little harder than just pasting the URL in the browser.

This would be useful if you want to prevent someone from adding the API to their own website, but it’s still not 100%, of course.

Some places to get started, even if this Community isn’t the best place to find an answer to this question.

Hey - thanks for the reply!
Now thinking about my requirements a bit more:

  1. Not allowing the URL to be useed directly in the browser
  2. Not allowing someone to add the API to their site

I’m completely ok if it’s not 100% foolproof, but makes it a bit harder to do :slight_smile:

That’s basically impossible, unless you make the call only on your server. Functions don’t work this way… you can only try and make it harder how I told you above. How you do that it’s on you, there are so many ways, and they depend on so many factors that I can’t help.

Implement CORP, then :slight_smile: It’s not the easiest, but not that hard either.


This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.