Solution for CORS policy problem for Shelf Router, Dart

Emre Şurk
1 min readFeb 16, 2022

You don’t have that problem in mobile, but while developing a web frontend app, making HTTP requests from a different domain, sub-domain or port can cause CORS problems. Your request is being blocked.

There are several solutions for shelf router, but the problem is all of them use Pipeline, and it takes only one handler, so you lose the ability to use Router.

Here is the solution with Shelf Router:

return Response.ok(
"", // your data.
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, POST, DELETE, OPTIONS',
'Access-Control-Allow-Headers': 'Origin, Content-Type',
},
);

That is all. We simply return some headers that allow CORS.

Bonus:
You can create a helper function that takes a Map, put those headers, and returns it as a JSON.

static Response createSuccessResponse(Map? data) {
return Response.ok(
jsonEncode(ApiResponseData(status: "ok", message: "", data: data).toJson()),
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, POST, DELETE, OPTIONS',
'Access-Control-Allow-Headers': 'Origin, Content-Type',
},
);
}

--

--