CORS
suggest changeBrowsers enforce the same-origin policy: JavaScript (or Dart compiled to JavaScript or WebAssembly) running on a page from one origin can't read responses from another origin. CORS (Cross-Origin Resource Sharing) is how a server opts out of that restriction. The server sends Access-Control-* response headers that tell the browser which other origins may read its responses.
You need CORS when:
- a Flutter web or Dart web app served from
https://app.example.comcalls an API onhttps://api.example.com - during development the front end runs on
http://localhost:5000and the Dart server onhttp://localhost:8080 - a third-party site should be able to call your public API from the browser
This article covers:
- what an origin is and what the browser blocks
- simple requests vs preflight requests
- adding CORS headers with plain
dart:io - writing a correct CORS middleware for Shelf
- credentials (cookies), exposed headers, preflight caching
- ordering CORS with error handling and authentication
- the
shelf_cors_headerspackage and its defaults - calling a CORS API from Dart in the browser with
BrowserClient - common mistakes and how to read the browser's error messages
Packages used:
dart pub add shelf shelf_router shelf_cors_headers http
The examples were run with Dart 3.13, shelf 1.4.3, shelf_router 1.1.5, shelf_cors_headers 0.1.5 and http 1.6.0. Browser results come from Chrome 155.
Origins and the same-origin policy
An origin is the triple scheme + host + port. Two URLs have the same origin only if all three match:
| Page origin | Request URL | Same origin? |
|---|---|---|
https://app.example.com |
https://app.example.com/api/items |
yes |
https://app.example.com |
http://app.example.com/api |
no, different scheme |
https://app.example.com |
https://api.example.com/items |
no, different host |
http://localhost:5000 |
http://localhost:8080/items |
no, different port |
http://localhost:5000 |
http://127.0.0.1:5000/items |
no, different host |
For a cross-origin request the browser adds an Origin request header, such as Origin: http://localhost:5000. The server answers with Access-Control-Allow-Origin if it allows that origin. If the header is missing or doesn't match, the browser refuses to give the response to the page.
Three things that surprise people:
- CORS is enforced only by browsers. A Dart command-line program, a Flutter app on Android, iOS or desktop,
curland server-to-server calls ignore it completely. Only Flutter web and other browser code is affected. - CORS is not access control. It protects the user's browser from pages that would read data using the user's cookies or network position. It doesn't stop anyone from calling your API directly. Authentication and authorization are still your job.
- A blocked simple request still reaches the server. The browser hides the response from the page, but the request was sent and the server ran the handler.
The last point is easy to show. This server has no CORS headers at all, and a Dart VM client happily reads the response, even with a made-up Origin:
import 'dart:io';
import 'package:http/http.dart' as http;
Future<void> main() async {
// A server that sends no CORS headers at all.
final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
server.listen((req) {
req.response
..write('secret data')
..close();
});
// A Dart VM client can even claim to be any origin. Nothing stops it.
final response = await http.get(
Uri.parse('http://localhost:${server.port}/'),
headers: {'origin': 'https://evil.example'},
);
print('${response.statusCode} ${response.body}');
print('allow-origin: ${response.headers['access-control-allow-origin']}');
await server.close();
}
Output:
200 secret data
allow-origin: null
Simple requests and preflight requests
Browsers divide cross-origin requests into two kinds.
A simple request is sent directly. It must meet all of these conditions:
- the method is
GET,HEADorPOST - the only headers set by the page are "CORS-safelisted" ones, such as
Accept,Accept-Language,Content-LanguageandContent-Type Content-Type, if set, isapplication/x-www-form-urlencoded,multipart/form-dataortext/plain
These are the requests an HTML <form> could always send, so allowing them cross-origin gives an attacker nothing new. The browser sends the request with Origin, then checks Access-Control-Allow-Origin in the response.
Everything else needs a preflight. That includes PUT, PATCH and DELETE, any POST with Content-Type: application/json, and any request with an Authorization header or a custom X-... header. Before the real request, the browser sends an OPTIONS request that asks for permission:
OPTIONS /items/7 HTTP/1.1
Origin: http://localhost:5000
Access-Control-Request-Method: PUT
Access-Control-Request-Headers: content-type
The server must answer with a 2xx status and headers that allow that origin, method and headers:
HTTP/1.1 204 No Content
Access-Control-Allow-Origin: http://localhost:5000
Access-Control-Allow-Methods: GET, POST, PUT, PATCH, DELETE
Access-Control-Allow-Headers: content-type, authorization
Access-Control-Max-Age: 7200
Vary: Origin, Access-Control-Request-Method, Access-Control-Request-Headers
Only then does the browser send the real PUT. Its response must also carry Access-Control-Allow-Origin.
The headers involved:
| Header | Sent in | Meaning |
|---|---|---|
Origin |
request | origin of the page making the request |
Access-Control-Request-Method |
preflight request | method of the real request |
Access-Control-Request-Headers |
preflight request | non-safelisted headers the real request will send, lowercase, comma-separated |
Access-Control-Allow-Origin |
response | the allowed origin, or * for any origin |
Access-Control-Allow-Methods |
preflight response | methods allowed for the real request |
Access-Control-Allow-Headers |
preflight response | request headers allowed for the real request |
Access-Control-Max-Age |
preflight response | seconds the browser may cache this preflight result |
Access-Control-Allow-Credentials |
response | true if the page may send and receive cookies |
Access-Control-Expose-Headers |
response | response headers, beyond the safelisted ones, that the page may read |
Vary |
response | tells caches the response depends on Origin |
Seeing it in a browser
The next program starts two dart:io servers on random ports. One serves an HTML page, so the page's origin is http://localhost:<page port>. The other is the API, which is a different origin because the port differs. /no-cors sends no CORS headers, /cors sends Access-Control-Allow-Origin: *:
import 'dart:convert';
import 'dart:io';
// The page is served from one origin and calls an API on another origin.
const pageHtml = r'''
<!doctype html>
<pre id="out"></pre>
<script>
const api = 'http://localhost:API_PORT';
const out = document.getElementById('out');
async function tryFetch(label, path, options) {
try {
const r = await fetch(api + path, options);
out.textContent += label + ': ' + r.status + ' ' + (await r.text()) + '\n';
} catch (e) {
out.textContent += label + ': ' + e.name + ': ' + e.message + '\n';
}
}
(async () => {
await tryFetch('GET /no-cors', '/no-cors');
await tryFetch('GET /cors', '/cors');
await tryFetch('PUT /cors', '/cors', {method: 'PUT', body: '{}',
headers: {'Content-Type': 'application/json'}});
out.textContent += 'done\n';
})();
</script>
''';
Future<void> main() async {
final api = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
api.listen((req) async {
print('API got: ${req.method} ${req.uri.path} '
'origin=${req.headers.value('origin')}');
final res = req.response;
if (req.uri.path == '/cors') {
res.headers.set('Access-Control-Allow-Origin', '*');
}
res.headers.contentType = ContentType.json;
res.write(jsonEncode({'msg': 'hello'}));
await res.close();
});
final pages = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
pages.listen((req) async {
req.response.headers.contentType = ContentType.html;
req.response.write(pageHtml.replaceFirst('API_PORT', '${api.port}'));
await req.response.close();
});
print('Open http://localhost:${pages.port} (API on port ${api.port})');
}
Server output after opening the page in Chrome:
Open http://localhost:61934 (API on port 61933)
API got: GET /no-cors origin=http://localhost:61934
API got: GET /cors origin=http://localhost:61934
API got: OPTIONS /cors origin=http://localhost:61934
What the page shows:
GET /no-cors: TypeError: Failed to fetch
GET /cors: 200 {"msg":"hello"}
PUT /cors: TypeError: Failed to fetch
done
And the browser's DevTools console:
Access to fetch at 'http://localhost:61933/no-cors' from origin 'http://localhost:61934' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Access to fetch at 'http://localhost:61933/cors' from origin 'http://localhost:61934' has been blocked by CORS policy: Method PUT is not allowed by Access-Control-Allow-Methods in preflight response.
What happened:
GET /no-corswas a simple request. It reached the server (see the log), but the page only got a genericTypeError: Failed to fetch. The page can't see the status code or the reason. The details are only in the console, on purpose, so that a page can't probe your network.GET /corsworked becauseAccess-Control-Allow-Origin: *allows any origin.PUTwith a JSON body needed a preflight. The server answered theOPTIONSrequest with status 200 andAccess-Control-Allow-Origin: *, but withoutAccess-Control-Allow-Methods, so the browser never sent thePUT. The handler forPUTdidn't run.
For a public, read-only API with no cookies, Access-Control-Allow-Origin: * is all you need. Anything more involved deserves a proper middleware.
A CORS middleware for Shelf
A good CORS implementation:
- allows only origins from an explicit list, and echoes back the matching origin
- recognizes a preflight as
OPTIONSwith anAccess-Control-Request-Methodheader, and answers it directly without calling the inner handler - checks the requested method and headers and rejects what isn't allowed
- adds
Vary: Originso that a cache (a CDN or the browser's HTTP cache) doesn't serve a response made for one origin to another origin - adds
Access-Control-Allow-CredentialsandAccess-Control-Expose-Headersonly when configured
Here it is as Shelf middleware. Save it as cors.dart; the following examples import it:
import 'package:shelf/shelf.dart';
/// CORS middleware for Shelf with an explicit allowlist of origins.
Middleware cors({
required Set<String> allowedOrigins,
Set<String> allowedMethods = const {'GET', 'POST', 'PUT', 'PATCH', 'DELETE'},
Set<String> allowedHeaders = const {'content-type', 'authorization'},
Set<String> exposedHeaders = const {},
bool allowCredentials = false,
Duration maxAge = const Duration(hours: 2),
}) {
final methods = allowedMethods.map((m) => m.toUpperCase()).toSet();
final headers = allowedHeaders.map((h) => h.toLowerCase()).toSet();
return (Handler inner) {
return (Request request) async {
final origin = request.headers['origin'];
final isPreflight = request.method == 'OPTIONS' &&
request.headers.containsKey('access-control-request-method');
final allowed = origin != null && allowedOrigins.contains(origin);
if (isPreflight) {
final vary = {
'vary': 'Origin, Access-Control-Request-Method, '
'Access-Control-Request-Headers',
};
if (!allowed) return Response.forbidden(null, headers: vary);
final method =
request.headers['access-control-request-method']!.toUpperCase();
final requested = (request.headers['access-control-request-headers'] ?? '')
.split(',')
.map((h) => h.trim().toLowerCase())
.where((h) => h.isNotEmpty);
if (!methods.contains(method) || !requested.every(headers.contains)) {
return Response.forbidden(null, headers: vary);
}
return Response(204, headers: {
...vary,
'access-control-allow-origin': origin,
'access-control-allow-methods': methods.join(', '),
if (headers.isNotEmpty)
'access-control-allow-headers': headers.join(', '),
'access-control-max-age': '${maxAge.inSeconds}',
if (allowCredentials) 'access-control-allow-credentials': 'true',
});
}
final response = await inner(request);
final existingVary = response.headers['vary'];
return response.change(headers: {
// The response depends on Origin even when we add no CORS headers.
'vary': existingVary == null ? 'Origin' : '$existingVary, Origin',
if (allowed) ...{
'access-control-allow-origin': origin,
if (allowCredentials) 'access-control-allow-credentials': 'true',
if (exposedHeaders.isNotEmpty)
'access-control-expose-headers': exposedHeaders.join(', '),
},
});
};
};
}
Notes on the design:
- Comparing
originwith aSetof exact strings is the safest check. Don't useendsWith('example.com'), which also matchesevil-example.com, or a regular expression with an unescaped.. - Requests without
Origin(same-originGETs,curl, mobile apps) pass through unchanged, apart fromVary. - For a disallowed origin we don't return an error for normal requests. We just don't add CORS headers, and the browser blocks the page from reading the response. For a preflight we return 403, which the browser treats as a failure.
- Header names in Shelf's
request.headersare case-insensitive, and browsers sendAccess-Control-Request-Headersin lowercase. We lowercase our configured names to compare them.
A Shelf Handler is just a function, so we can call it with hand-made Request objects and look at the result, without starting a server:
import 'package:shelf/shelf.dart';
import 'cors.dart';
Response api(Request request) => Response.ok('{"items":[]}',
headers: {'content-type': 'application/json', 'x-total-count': '0'});
Future<void> show(Handler handler, String method, Map<String, String> headers) async {
final request = Request(method, Uri.parse('http://api.example.com/items'),
headers: headers);
final response = await handler(request);
print('$method ${headers['origin'] ?? '(no origin)'} -> ${response.statusCode}');
response.headers.forEach((name, value) {
if (name.startsWith('access-control') || name == 'vary') {
print(' $name: $value');
}
});
}
Future<void> main() async {
final handler = const Pipeline()
.addMiddleware(cors(
allowedOrigins: {'https://app.example.com'},
exposedHeaders: {'x-total-count'},
))
.addHandler(api);
// Same-origin request or non-browser client: no Origin header.
await show(handler, 'GET', {});
// Simple cross-origin request from an allowed origin.
await show(handler, 'GET', {'origin': 'https://app.example.com'});
// From an origin that is not on the list.
await show(handler, 'GET', {'origin': 'https://evil.example'});
// Preflight for a PUT with a JSON body.
await show(handler, 'OPTIONS', {
'origin': 'https://app.example.com',
'access-control-request-method': 'PUT',
'access-control-request-headers': 'content-type',
});
// Preflight asking for a header we don't allow.
await show(handler, 'OPTIONS', {
'origin': 'https://app.example.com',
'access-control-request-method': 'POST',
'access-control-request-headers': 'content-type, x-debug',
});
}
Output:
GET (no origin) -> 200
vary: Origin
GET https://app.example.com -> 200
vary: Origin
access-control-allow-origin: https://app.example.com
access-control-expose-headers: x-total-count
GET https://evil.example -> 200
vary: Origin
OPTIONS https://app.example.com -> 204
vary: Origin, Access-Control-Request-Method, Access-Control-Request-Headers
access-control-allow-origin: https://app.example.com
access-control-allow-methods: GET, POST, PUT, PATCH, DELETE
access-control-allow-headers: content-type, authorization
access-control-max-age: 7200
OPTIONS https://app.example.com -> 403
vary: Origin, Access-Control-Request-Method, Access-Control-Request-Headers
The last preflight asks for x-debug, which isn't allowed, so it gets a 403 and the browser won't send the real request.
Credentials: cookies and HTTP authentication
By default a cross-origin fetch doesn't send cookies and ignores Set-Cookie in the response. Credentials need opt-in on both sides:
- the page uses
fetch(url, {credentials: 'include'}), or in DartBrowserClient()..withCredentials = true - the server responds with
Access-Control-Allow-Credentials: trueand a specific origin inAccess-Control-Allow-Origin. The wildcard*is not allowed with credentials
The cookie itself must also be allowed by its SameSite attribute. localhost:5000 and localhost:8080 are the same site (ports don't matter for sites), so SameSite=Lax works there and for app.example.com with api.example.com. For a truly different site, such as myapp.dev calling myapi.com, the cookie needs SameSite=None; Secure, and some browsers block such third-party cookies anyway. See Cookies for cookie attributes.
The next program is a Shelf API with a cookie login, a PUT with a JSON body and a custom response header, and a route that throws. The API allows the page's origin with credentials and exposes x-total-count:
import 'dart:convert';
import 'dart:io';
import 'package:shelf/shelf.dart';
import 'package:shelf/shelf_io.dart' as shelf_io;
import 'package:shelf_router/shelf_router.dart';
import 'cors.dart';
const pageHtml = r'''
<!doctype html>
<pre id="out"></pre>
<script>
const api = 'http://localhost:API_PORT';
const out = document.getElementById('out');
const log = (s) => out.textContent += s + '\n';
async function call(label, path, options = {}) {
try {
const r = await fetch(api + path, options);
log(`${label}: ${r.status} ${await r.text()}`);
return r;
} catch (e) {
log(`${label}: ${e.name}: ${e.message}`);
}
}
(async () => {
await call('me (no credentials)', '/me');
await call('login', '/login', {method: 'POST', credentials: 'include'});
await call('me (credentials)', '/me', {credentials: 'include'});
const r = await call('PUT item', '/items/7', {
method: 'PUT',
credentials: 'include',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({name: 'Lamp'}),
});
log(` x-total-count: ${r.headers.get('x-total-count')}`);
log(` x-internal: ${r.headers.get('x-internal')}`);
await call('boom', '/boom');
log('done');
})();
</script>
''';
Router buildRouter() {
final router = Router();
router.post('/login', (Request request) {
return Response.ok('logged in', headers: {
'set-cookie': 'session=alice; Path=/; HttpOnly; SameSite=Lax',
});
});
router.get('/me', (Request request) {
final cookie = request.headers['cookie'] ?? '';
if (!cookie.contains('session=alice')) {
return Response.unauthorized('no session');
}
return Response.ok(jsonEncode({'user': 'alice'}));
});
router.put('/items/<id>', (Request request, String id) async {
final body = jsonDecode(await request.readAsString());
return Response.ok(jsonEncode({'id': id, ...body}), headers: {
'content-type': 'application/json',
'x-total-count': '42',
'x-internal': 'secret',
});
});
router.get('/boom', (Request request) {
throw StateError('database is down');
});
return router;
}
Future<void> main() async {
final pages = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
final pageOrigin = 'http://localhost:${pages.port}';
final handler = const Pipeline()
.addMiddleware(cors(
allowedOrigins: {pageOrigin},
allowCredentials: true,
exposedHeaders: {'x-total-count'},
))
.addHandler(buildRouter().call);
final api = await shelf_io.serve(handler, InternetAddress.loopbackIPv4, 0);
pages.listen((req) async {
req.response.headers.contentType = ContentType.html;
req.response.write(pageHtml.replaceFirst('API_PORT', '${api.port}'));
await req.response.close();
});
print('Open $pageOrigin (API on port ${api.port})');
}
What the page shows in Chrome:
me (no credentials): 401 no session
login: 200 logged in
me (credentials): 200 {"user":"alice"}
PUT item: 200 {"id":"7","name":"Lamp"}
x-total-count: 42
x-internal: null
boom: TypeError: Failed to fetch
done
Server output:
Open http://localhost:55545 (API on port 55546)
ERROR - 2026-10-17 21:39:10.896883
GET /boom
Error thrown by handler.
Bad state: database is down
bin\ex4.dart 67:5 buildRouter.<fn>
...
Going through the results:
- The first
/mereturns 401 and the page can read it, because the 401 response has CORS headers. Being able to read error responses matters: the app can show "please log in" instead of a generic network error. loginwithcredentials: 'include'stores the cookie. WithoutAccess-Control-Allow-Credentials: truethe browser would discard theSet-Cookieheader.- The second
/mesends the cookie, so it succeeds. - By default the page can read only safelisted response headers:
Cache-Control,Content-Language,Content-Length,Content-Type,Expires,Last-ModifiedandPragma.x-total-countis readable because it's listed inAccess-Control-Expose-Headers;x-internalis not, soheaders.get()returnsnull. /boomthrows. The exception goes up throughcors()before any headers are added, soshelf_iosends a bare 500 response withoutAccess-Control-Allow-Origin. The browser reports a CORS error and the page never learns that it was a server error. The next section fixes that.
Ordering CORS with errors and authentication
Middleware order matters for CORS:
- CORS must be outside the error handler. Put a middleware that turns exceptions into 500 responses inside
cors(), so that error responses get CORS headers too. - CORS must be outside authentication. A preflight never carries cookies or an
Authorizationheader. If the authentication check runs first, it rejects the preflight with 401 and the browser never sends the real, authenticated request.
In a Pipeline, the first addMiddleware is the outermost. This program shows both problems and their fixes:
import 'dart:io';
import 'package:shelf/shelf.dart';
import 'cors.dart';
final corsMiddleware = cors(allowedOrigins: {'https://app.example.com'});
// Turns exceptions into a 500 response that still passes through cors().
Middleware catchErrors() => (Handler inner) => (Request request) async {
try {
return await inner(request);
} on HijackException {
rethrow; // used by shelf for WebSockets, must propagate
} catch (e) {
stderr.writeln('${request.method} /${request.url}: $e');
return Response.internalServerError(body: 'internal error');
}
};
// Requires a bearer token on every request.
Middleware requireToken() => (Handler inner) => (Request request) {
if (request.headers['authorization'] != 'Bearer s3cret') {
return Response.unauthorized('missing token');
}
return inner(request);
};
Response failing(Request request) => throw StateError('database is down');
Response hello(Request request) => Response.ok('hello');
Future<void> send(String label, Handler handler, String method,
[Map<String, String> extra = const {}]) async {
final request = Request(method, Uri.parse('http://api.example.com/x'),
headers: {'origin': 'https://app.example.com', ...extra});
try {
final r = await handler(request);
print('$label: ${r.statusCode} '
'allow-origin=${r.headers['access-control-allow-origin']}');
} catch (e) {
print('$label: threw $e (shelf_io sends a bare 500)');
}
}
Future<void> main() async {
await send('error, no catchErrors', const Pipeline()
.addMiddleware(corsMiddleware)
.addHandler(failing), 'GET');
await send('error, catchErrors inside cors', const Pipeline()
.addMiddleware(corsMiddleware)
.addMiddleware(catchErrors())
.addHandler(failing), 'GET');
const preflight = {
'access-control-request-method': 'GET',
'access-control-request-headers': 'authorization',
};
await send('preflight, auth before cors', const Pipeline()
.addMiddleware(requireToken())
.addMiddleware(corsMiddleware)
.addHandler(hello), 'OPTIONS', preflight);
await send('preflight, cors before auth', const Pipeline()
.addMiddleware(corsMiddleware)
.addMiddleware(requireToken())
.addHandler(hello), 'OPTIONS', preflight);
await send('no token, cors before auth', const Pipeline()
.addMiddleware(corsMiddleware)
.addMiddleware(requireToken())
.addHandler(hello), 'GET');
}
Output:
error, no catchErrors: threw Bad state: database is down (shelf_io sends a bare 500)
GET /x: Bad state: database is down
error, catchErrors inside cors: 500 allow-origin=https://app.example.com
preflight, auth before cors: 401 allow-origin=null
preflight, cors before auth: 204 allow-origin=https://app.example.com
no token, cors before auth: 401 allow-origin=https://app.example.com
The GET /x: ... line is written to stderr by catchErrors(). Note the last line: a request without a token is still rejected with 401, but the response has CORS headers, so the page can read the 401 and react to it.
The usual order is: logging, then CORS, then error handling, then authentication, then the router:
final handler = const Pipeline()
.addMiddleware(logRequests())
.addMiddleware(cors(allowedOrigins: {'https://app.example.com'}))
.addMiddleware(catchErrors())
.addMiddleware(requireToken())
.addHandler(router.call);
If your router only handles GET and POST for a path, don't worry about OPTIONS routes: cors() answers preflights before the router sees them.
For how Shelf middleware works in general (the Middleware type, Pipeline, writing your own), see HTTP middleware.
Caching preflights
Every preflight is an extra round trip before the real request. Access-Control-Max-Age lets the browser cache a preflight result per origin, URL, method and headers. Browsers cap the value: Chrome uses at most 7200 seconds (2 hours), Firefox at most 86400 seconds (24 hours). Without the header, Chrome caches a preflight for only 5 seconds.
To avoid preflights altogether, keep requests simple: GET without custom headers, or a POST with a form-encoded body. That's rarely worth reshaping an API for. A longer Max-Age is usually enough.
Using shelf_cors_headers
shelf_cors_headers is a popular package that provides corsHeaders() middleware. Its defaults are permissive, so look at what it actually sends:
import 'package:shelf/shelf.dart';
import 'package:shelf_cors_headers/shelf_cors_headers.dart';
Response hello(Request request) => Response.ok('hello');
Future<void> show(String label, Handler handler, String method, String origin) async {
final response = await handler(Request(
method, Uri.parse('http://api.example.com/x'),
headers: {'origin': origin}));
print('$label: $method from $origin -> ${response.statusCode}');
response.headers.forEach((name, value) {
final lower = name.toLowerCase();
if (lower.startsWith('access-control') || lower == 'vary') {
print(' $name: $value');
}
});
}
Future<void> main() async {
// Defaults: every origin is allowed, with credentials.
final open = const Pipeline().addMiddleware(corsHeaders()).addHandler(hello);
await show('defaults', open, 'GET', 'https://evil.example');
// Restricted to a list of origins, no credentials.
final strict = const Pipeline()
.addMiddleware(corsHeaders(
originChecker: originOneOf(['https://app.example.com']),
headers: {
ACCESS_CONTROL_ALLOW_CREDENTIALS: 'false',
ACCESS_CONTROL_ALLOW_METHODS: 'GET, POST',
ACCESS_CONTROL_MAX_AGE: '7200',
},
))
.addHandler(hello);
await show('strict', strict, 'OPTIONS', 'https://app.example.com');
await show('strict', strict, 'GET', 'https://evil.example');
}
Output:
defaults: GET from https://evil.example -> 200
Access-Control-Expose-Headers:
Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: accept,accept-encoding,authorization,content-type,dnt,origin,user-agent
Access-Control-Allow-Methods: DELETE,GET,OPTIONS,PATCH,POST,PUT
Access-Control-Max-Age: 86400
Access-Control-Allow-Origin: https://evil.example
strict: OPTIONS from https://app.example.com -> 200
Access-Control-Expose-Headers:
Access-Control-Allow-Credentials: false
Access-Control-Allow-Headers: accept,accept-encoding,authorization,content-type,dnt,origin,user-agent
Access-Control-Allow-Methods: GET, POST
Access-Control-Max-Age: 7200
Access-Control-Allow-Origin: https://app.example.com
strict: GET from https://evil.example -> 200
Things to know about this package (version 0.1.5):
- The defaults allow every origin, with credentials. It echoes back whatever
Originthe request has and sendsAccess-Control-Allow-Credentials: true. That means any website can make credentialed requests to your API and read the responses with the visitor's cookies. Fine for local development; for production, always passoriginChecker: originOneOf([...]). Access-Control-Allow-Credentials: falseworks in practice because browsers only accept the exact valuetrue, but it's cleaner to not send the header.- It doesn't add
Vary: Originwhen it echoes the origin. Add it yourself if a CDN or reverse proxy caches your responses. - Every
OPTIONSrequest is answered as a preflight, without checking the requested method or headers. A route that servesOPTIONSitself never gets called. - For a disallowed origin it adds nothing, which is correct.
If you need more than what the package offers, the 64 lines of the cors() middleware above are easy to own.
Calling the API from Dart in the browser
In Flutter web or a Dart web app, package:http uses BrowserClient, which is built on fetch. Cookies are not sent cross-origin unless you set withCredentials:
import 'package:http/browser_client.dart';
import 'package:http/http.dart' as http;
Future<void> main() async {
final api = Uri.base.queryParameters['api']!; // e.g. http://localhost:55546
// A plain client: no cookies are sent cross-origin.
final plain = BrowserClient();
final r1 = await plain.get(Uri.parse('$api/me'));
print('me without credentials: ${r1.statusCode} ${r1.body}');
// withCredentials = true is the same as fetch(..., {credentials: 'include'}).
final client = BrowserClient()..withCredentials = true;
try {
await client.post(Uri.parse('$api/login'));
final r2 = await client.get(Uri.parse('$api/me'));
print('me with credentials: ${r2.statusCode} ${r2.body}');
final r3 = await client.get(Uri.parse('$api/boom'));
print('boom: ${r3.statusCode}');
} on http.ClientException catch (e) {
// A CORS failure gives no status code and no details.
print('ClientException: ${e.message}');
} finally {
plain.close();
client.close();
}
}
Compiled with dart compile js web/main.dart -o web/main.js, served from the page origin and pointed at the API from the previous section, the browser console shows:
me without credentials: 401 no session
me with credentials: 200 {"user":"alice"}
Access to fetch at 'http://localhost:59955/boom' from origin 'http://localhost:59954' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
ClientException: Failed to fetch
A CORS failure becomes a ClientException with the message Failed to fetch, the same as a DNS error or a refused connection. If your Flutter web app gets ClientException: Failed to fetch while the same code works on Android, CORS is the first suspect. Open DevTools and look at the console and the Network tab, which shows the preflight as a separate OPTIONS request.
The plain http.get() and http.post() functions create a BrowserClient on the web, but always without credentials. Use your own client when you need cookies.
Avoiding CORS during development
CORS only applies across origins, so serving the front end and the API from one origin removes the problem:
- In production, put both behind one reverse proxy (
https://example.com/for the app,https://example.com/api/for the API), or let the Dart server serve the static files of the web build withpackage:shelf_static. - During development, use a dev-server proxy, for example the
proxyoption of Vite, orpackage:shelf_proxyin a small Dart server that serves the app and forwards/apito the backend.
Chrome can be started with --disable-web-security (and flutter run -d chrome --web-browser-flag "--disable-web-security"). That turns off the same-origin policy for the whole browser profile. Use it only in a throwaway profile, never as a fix, because production users won't have it.
Common mistakes
| Console message (Chrome) | Cause and fix |
|---|---|
| No 'Access-Control-Allow-Origin' header is present on the requested resource | No CORS headers on this response. Often it's an error response (500, 404 from a proxy) produced outside the CORS middleware |
| Response to preflight request doesn't pass access control check: It does not have HTTP ok status | The OPTIONS request got 401, 404 or 405. Run CORS before authentication and routing |
| Method PUT is not allowed by Access-Control-Allow-Methods in preflight response | Add the method to Access-Control-Allow-Methods |
| Request header field authorization is not allowed by Access-Control-Allow-Headers in preflight response | Add the header to Access-Control-Allow-Headers |
| The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include' | Echo the specific allowed origin instead of * |
| The 'Access-Control-Allow-Origin' header has a value 'http://localhost:5000' that is not equal to the supplied origin | The allowed origin doesn't match exactly: check scheme, port, localhost vs 127.0.0.1, and trailing slashes (an origin never has one) |
| The 'Access-Control-Allow-Origin' header contains multiple values | Two layers (for example nginx and the Dart server) both add CORS headers. Add them in one place only |
Security mistakes that don't produce errors:
- Reflecting any origin with credentials. Echoing
Originback without checking it, together withAccess-Control-Allow-Credentials: true, lets any site read your users' data. This is exactly what theshelf_cors_headersdefaults do. - Allowing
Origin: null. Sandboxed iframes andfile://pages sendnull, and an attacker can produce it too. Never put'null'in the allowlist. - Loose matching. Use exact strings. If you must allow subdomains, parse the origin with
Uri.parseand checkuri.scheme == 'https'and thaturi.hostequals your domain or ends with.plus your domain. See Parsing URLs. - Forgetting
Vary: Origin. A cache may then serve a response withAccess-Control-Allow-Origin: https://a.example.comto a page onhttps://b.example.com, breaking it, or the other way around. - Treating CORS as protection against CSRF. Simple requests, such as a form
POST, are sent without a preflight and their side effects happen even when the response is blocked. UseSameSitecookies, CSRF tokens or token-based authentication (see JWT and Sessions).
Summary
| Task | How |
|---|---|
| Allow any origin, no cookies | Access-Control-Allow-Origin: * |
| Allow specific origins | check Origin against a Set, echo it back, add Vary: Origin |
| Detect a preflight | OPTIONS with an Access-Control-Request-Method header |
| Answer a preflight | 204 with Allow-Origin, Allow-Methods, Allow-Headers, Max-Age |
| Allow cookies | Access-Control-Allow-Credentials: true, specific origin, client opts in |
| Let the page read a custom header | Access-Control-Expose-Headers: x-total-count |
| Cache preflights | Access-Control-Max-Age: 7200 |
| Middleware order in Shelf | CORS, then error handling, then authentication, then router |
| Quick setup | corsHeaders(originChecker: originOneOf([...])) from shelf_cors_headers |
| Send cookies from Dart web | BrowserClient()..withCredentials = true |
For more on writing Shelf servers see REST APIs, and for making requests see HTTP Request.