1

I'm using Cloudflare D1 to store data and Cloudflare Pages to display it. I created a function to access the data which works fine until I want to limit access to the endpoint created by that function.

I want the endpoint to be only used by my app. I used the origin to exclude any request coming from outside the URL of my app, but I don't seems to make it work, what am I missing?

export async function onRequest(context) {
  const origin = context.origin;
  console.log('Request Origin:', origin);

  if (origin === 'https://xyz.pages.dev') {
    const ps = context.env.XYZDB.prepare('SELECT * from costs');
    const data = await ps.all();

    const response = new Response(JSON.stringify(data), {
      headers: {
        'Content-Type': 'application/json',
      },
    });

    console.log('Response:', response);

    return response;
  } else {
    console.log('Unauthorized Request');
    return new Response('Unauthorized', {
      status: 401,
    });
  }
}
Mrtsm
  • 35
  • 4

1 Answers1

0

You can read the origin from the request headers.

context.request.headers.get('origin')