Welcome to the new Golem Cloud Docs! 👋
Documentation
Setting up CORS

Setting up CORS in API Gateway

Setting up CORS in API Gateway is simple. Simply specify the preflight request endpoint for your resource, and all the operations under the resource will be CORS-enabled. This approach is largely inspired by AWS API Gateway.

Here is an example of how to set up CORS for your API definition.

Terminal
    id: users-api
    version: 0.0.1
    createdAt: 2024-08-21T07:42:15.696Z
    routes:
    - method: Options
      path: /users/{user-id}
      binding:
      bindingType: cors-preflight
    - method: Get
      path: /users/{user-id}
      binding:
      response: |
        {status: 200u64, body: "Hello World"}

Here, we define the preflight request endpoint for /users/{user-id} as the OPTIONS method. This is used by browsers to check if the actual request is allowed. Registering this API definition will ensure that the other operations (in the above example, GET) will also be CORS-enabled with the required headers in the response.

We can define a custom response for the preflight request as well using Rib as given below

Terminal
    id: users-api
    version: 0.0.1
    createdAt: 2024-08-21T07:42:15.696Z
    routes:
    - method: Options
      path: /users/{user-id}
      binding:
      bindingType: cors-preflight
      response: |
        {
          Access-Control-Allow-Origin: "*",
          Access-Control-Allow-Methods: "GET, POST, PUT, DELETE, OPTIONS",
          Access-Control-Allow-Headers: "Content-Type, Authorization",
          Access-Control-Expose-Headers: "Content-Length, X-Requested-With",
          Access-Control-Allow-Credentials: true,
          Access-Control-Max-Age: 86400u64
        }
    - method: Get
      path: /users/{user-id}
      binding:
      response: |
        {status: 200u64, body: "Hello World"}