CORS

suggest change

Browsers 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:

This article covers:

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:

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:

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:

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:

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:

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 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:

Ordering CORS with errors and authentication

Middleware order matters for CORS:

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):

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:

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:

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.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents