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.

If you prefer to watch the video, here it is:

https://youtu.be/IsLNCrdg154

Enable CORS for OPTIONS request in HAProxy

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

Plain Text

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

Plain Text

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

Plain Text

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

The Complete configuration

Here are the complete configuration files:

  • docker-compose.yml
YAML
  • haproxy.cfg
Plain Text

Caution

On a production server, you may need to replace the “*” with only the hosts you allowed (from your frontend, for example). In that case, you can replace * with your client URL (starts with http/https).

4 thoughts on “Configure HAProxy to Accept Preflight Requests (CORS)”

  1. Hey, Thanks for this article, I am currently stuck with this problem, But I was unable to solve this:

    I have a single frontend application with multiple backend, Can you publish your ha-proxy config file and replace the confidential data with a dump one, May be via Github , Thanks

    Reply

Leave a Comment