CORS (Cross-origin resource sharing) is a standard mechanism that allows XMLHttpRequest (XHR) calls executed in a web page to interact with resources from different origins. Without CORS, the [same-origin policy](https://developer.mozilla.org/docs/Web/Security/Same-origin_policy) enforced by all browsers would prevent cross-origin requests. For more background information on CORS, see the [Mozilla Developer Network (MDN) reference documentation](https://developer.mozilla.org/docs/Web/HTTP/CORS).

The CORS standard requires that web clients issue a CORS preflight `OPTIONS` to determine if the requested web server supports CORS. If a web server supports CORS request, it will handle the `OPTIONS` request with proper CORS response headers.

## Handle CORS in your backend application

If your backend supports CORS, you can configure ESP or ESPv2 to pass the CORS request to your backend.
you can enable pass-through in the OpenAPI spec for your API as shown:

```
swagger: "2.0"
host: "my-cool-api.endpoints.my-project-id.cloud.goog"
x-google-endpoints:
- name: "my-cool-api.endpoints.my-project-id.cloud.goog"
  allowCors: True
```

You can also enable pass-through in an OpenAPI 3.x spec for your API as shown:

```
openapi: 3.0.4
servers:
- url: https://my-cool-api.endpoints.my-project-id.cloud.goog
  x-google-endpoint:
    allowCors: True
```

> [!WARNING]
> **Warning:** the `name` field under `x-google-endpoints` must match the `host` field value. Both fields should use the endpoint service name.

## Handle CORS with ESP or ESPv2

If your backend does not support CORS, you can configure ESP or ESPv2 to handle CORS requests by specifying CORS startup flags. In this approach, [CORS Preflight requests](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#preflighted_requests) will not pass through to your backend application. Additionally, ESP or ESPv2 will append the configured CORS headers to responses from the backend service when appropriate.

The following CORS startup options are available for ESP and ESPv2

- [ESP CORS startup flags](https://docs.cloud.google.com/endpoints/docs/openapi/specify-proxy-startup-options.md.txt#adding_cors_support_to_esp)
- [ESPv2 CORS startup flags](https://docs.cloud.google.com/endpoints/docs/openapi/specify-esp-v2-startup-options.md.txt#cors)

<br />

> [!WARNING]
> **Warning:** if CORS is handled by ESPv2, the `OPTIONS` CORS preflight request must have a valid `Origin` and `Access-Control-Request-Method` headers, otherwise it will not be handled properly.