CORS Helper

This utility is used to help define CORS headers for a given request origin.

API

CreateCORSHelper Function (default export)

The default export is a function that creates a CORS helper object given the following parameters:

The CORS helper has the following methods that take a request object as a parameter:

Example Usage

// 0. Create helper object
import CreateCORSHelper from "...";
const helper = CreateCORSHelper([
  "http://localhost:3000",
  new URLPattern({ hostname: "{:subdomain.}*example.com" }),
  /./,
]);
const handler = (request) => {
  // 1. If the request method is "OPTIONS"
  // respond immediately with response object
  // returned by the helper's getResponse method
  if (request.method === "OPTIONS") {
    return helper.getResponse(request);
  }
  // 2. Otherwise, construct a response object
  // using the array from the helper's
  // getHeadersInit method as a base for it's headers
  const otherHeades = [];
  const headers = new Headers([
    ...helper.getHeadersInit(request),
    ...otherHeaders,
  ]);
  return new Response("...", {
    headers,
  });
};