TIL: Enabling CORS when using HAProxy as a gateway
2022-04-19 00:00:00 +0000 UTCFor my local development of And Then I serve the frontend React app using the React development server on port 3000 and have a set of Docker containers running the backend, including a HAProxy API gateway with port 80 exposed. Despite requests sharing the same IP/hostname, the differing ports mean that requests from the frontend to the API violate CORS policy.
To set up CORS in HAProxy, you first have to download and place cors.lua on the API gateway machine. This meant adding a line to my Dockerfile for the gateway:
COPY cors.lua /usr/local/etc/haproxy/
Once the Lua library is available to HAProxy, you can source it and configure CORS policy like this:
global
...
lua-load /usr/local/etc/haproxy/cors.lua
...
frontend api_gateway
...
http-request lua.cors "GET,POST" "intranet-ip:3000" "*"
http-response lua.cors
...
The first argument to http-request lua.cors
is a list of allowed HTTP request methods, followed by the list of allowed origins for CORS requests separated by commas, finally followed by a list of allowed custom HTTP headers (in this case all are allowed).
And that’s it for a simple CORS setup with HAProxy! More information available in the linked HAProxy github repo above and in this HAProxy article.