How to Add CORS Headers to a Response

CORS (Cross-Origin Resource Sharing) headers enable secure communication between different origins. In this guide, you will learn how to configure Membrane API Gateway to add CORS headers to responses, allowing controlled cross-origin access.

Configuration

The following configuration adds CORS headers, allowing requests from any origin, authentication credentials, and restricting allowed HTTP methods to GET only.

<api port="2000">
    <response>
        <setHeader name="Access-Control-Allow-Origin" value="*" />
        <setHeader name="Access-Control-Allow-Methods" value="GET" />
        <setHeader name="Access-Control-Allow-Headers" value="Content-Type, Authorization" />
        <setHeader name="Access-Control-Allow-Credentials" value="true" />
        <setHeader name="Access-Control-Max-Age" value="3600" />
      </response>
    <target url="https://api.predic8.de" />
</api>

Understanding CORS Headers

  • Access-Control-Allow-Origin: Specifies which domains can access the resource.
  • Access-Control-Allow-Methods: Defines the allowed HTTP methods.
  • Access-Control-Allow-Headers: Lists the headers permitted in the request.
  • Access-Control-Allow-Credentials: Enables credentialed requests.
  • Access-Control-Max-Age: Specifies how long the response can be cached.

Resources

setHeader Documentation