1 min read

Handle CORS on CaddyServer

Handle CORS on CaddyServer

What is CORS?

CORS (Cross-Origin Resource Sharing) is a Header used to let your Browser know that a Website with a different URL is allowed to use your API.

For example, your api is at https://api.website.com and your frontend is served at https://website.com, these are served at 2 different origins: api.website.com and website.com.

To counter this issue a Header named Access-Control-Allow-Origin is used on https://api.website.com to let the Browser know that https://website.com

CaddyServer config

The header is simply added like this on the server block:

api.website.com {
    header {
        Access-Control-Allow-Origin https://website.com
    }
    reverse_proxy 192.168.1.240:8080
}

Note

This can be done using any webserver that sends a header, can also be done at the code level, but in general I strongly suggest decoupling network operations and code (e.g code shouldn't be aware about URLs, Browser configurations, etc). When doing so it makes it tenfolds easier to deliver your product to multiple customers, or let your DevOps/SRE teams handle network specifics

That's it.