Request Header Authentication

In this example, an Edge Function is used to validate the request headers, implementing basic access control.

Code

const VALID_TOKEN = '123456';

async function handleRequest(request) {
  const token = request.headers.get('x-custom-token');

  if (token === VALID_TOKEN) {
    return new Response('Valid token');
  }

  return new Response('Invalid token', {
    status: 403,
  });
}

addEventListener('fetch', event => {
  event.respondWith(handleRequest(event.request));
});

Preview

If authentication fails, access is denied.

Xnip2024-07-02_17-22-47.png

If authentication is successful, access is allowed.

Xnip2024-07-02_17-23-49.png

References