CORS on the Drogon web framework

CORS, the problem that every web developer has faced at least once in their life. Drogon does not come with built-in middleware to handle CORS, but it is easy to implement it yourself.

Usually, you'll want to expose your APIs to the world. This code will allow any request to the /api path to go through, and will respond to any OPTIONS request with the appropriate CORS headers.

using namespace drogon;
app().registerPreRoutingAdvice([](const HttpRequestPtr &req,
                                  FilterCallback &&stop,
                                  FilterChainCallback &&pass)
{
    // Let anything not starting with /api or not a preflight request through
    if(!req->path().starts_with("/api") || req->method() != Options) {
        pass();
        return;
    }

    auto resp = HttpResponse::newHttpResponse();
    resp->addHeader("Access-Control-Allow-Origin", "*");
    resp->addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
    // Add other CORS headers you need
    stop(resp); // stops processing the request and sends the response
}

Depending on your use case you might want to try pre-handling adivce if you want to exclude static files from CORS handling. Alternatively, you can add your own hander to APIs individually, like this:

Task MyController::myApi(HttpRequestPtr req)
{
    if(req->method() == Options) {
        auto resp = HttpResponse::newHttpResponse();
        resp->addHeader("Access-Control-Allow-Origin", "*");
        resp->addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
        // Add other CORS headers you need
        co_return resp;
    }

    // Your API code here
    ...
}

That's it. It is possible to use a filter for this. But I never find it specially fitting better then AOP. I only use filters when a few APIs have special authentication requirements. AOP is much suitable for these wide area concerns.

Proxy Information
Original URL
gemini://gemini.clehaxze.tw/gemlog/2024/03-02-cors-on-the-drogon-web-framework.gmi
Status Code
Success (20)
Meta
text/gemini
Capsule Response Time
1411.692822 milliseconds
Gemini-to-HTML Time
0.736207 milliseconds

This content has been proxied by September (ba2dc).