Request Header Authentication

This example demonstrates how to use an Edge Function to perform simple permission control by verifying the value of the x-custom-token request header. If the value is token-123456, access is allowed. Otherwise, access is denied.

Sample Code

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

  if (token === 'token-123456') {
    return new Response('hello world');
  }

  // Incorrect key supplied. Reject the request.
  return new Response('Sorry, you have supplied an invalid token.', {
    status: 403,
  });
}

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

Sample Preview

In the address bar of the browser, enter a URL that matches a trigger rule of the Edge Function to preview the effect of the sample code.

  1. If authentication fails, access is denied.

4.png

  1. If authentication is successful, access is allowed.

4.1.png

References

  1. Runtime APIs: Headers
  2. Runtime APIs: Response