Configure HAProxy to Accept Preflight Requests (CORS)

Recently I developed an API with Spring Boot. All the tests on the local environment went well with Postman. However, when deploying to prod through HAProxy, I got this CORS error:

There are also other errors regarding missing headers, origin…

There are some solutions available, such as adding code to my Spring Boot code base. I don’t like this method since it’s not pure.

Why add non-business code in API?

That’s why I need to find another solution.

It turned out, that the solution is simple.

Enable CORS for OPTIONS request in HAProxy

First, add a new backend only for serving CORS in HAProxy:

backend cors_backend
  http-after-response set-header Access-Control-Allow-Origin "*"
  http-after-response set-header Access-Control-Allow-Headers "*"
  http-after-response set-header Access-Control-Max-Age "31536000"
  http-request return status 200

Now, in the frontend part, add a check for OPTIONS request and direct that request to this backend:

frontend your_fe
  ...
   acl is_options method OPTIONS
   
...

  use_backend cors_backend if is_options
  # put your actual backend below this

Of course, in your actual backend, you need to set the CORS headers:

backend your_main_backend
  ...

  # START CORS
  http-response add-header Access-Control-Allow-Origin "*"
  http-response add-header Access-Control-Allow-Headers "*"
  http-response add-header Access-Control-Max-Age 3600
  http-response add-header Access-Control-Allow-Methods "GET, DELETE, OPTIONS, POST, PUT, PATCH"
  # END CORS

  server w1 server:8080

And that’s all you need. Now you can work with your API CORS-free


Leave a Reply

Your email address will not be published.