File tree Expand file tree Collapse file tree 1 file changed +43
-0
lines changed Expand file tree Collapse file tree 1 file changed +43
-0
lines changed Original file line number Diff line number Diff line change
1
+ ---
2
+ sidebar_position : 8
3
+ title : ⚔️ Handling Cross-Origin Resource Sharing (CORS)
4
+ ---
5
+
6
+ Cross-Origin Resource Sharing or CORS is a common thing that needs to be handled by backend servers.
7
+ This guide shows how the handling of CORS can be done in a Dart Frog project.
8
+
9
+ ::: warning
10
+ To learn more about what CORS is, check out this [ helpful documentation from MDN] ( https://developer.mozilla.org/docs/Web/HTTP/CORS ) .
11
+ :::
12
+
13
+ [ Shelf] ( https://pub.dev/packages/shelf ) already has a package in its ecosystem that handles CORS.
14
+ Since Dart Frog is built on top of shelf, we can use it in Dart Frog as well. First add ` shelf_cors_headers ` to your project:
15
+
16
+ ``` bash
17
+ dart pub add shelf_cors_headers
18
+ ```
19
+
20
+ Then, to allow CORS in routes, the following middleware can be created:
21
+
22
+ ``` dart
23
+ import 'dart:io';
24
+
25
+ import 'package:dart_frog/dart_frog.dart';
26
+ import 'package:shelf_cors_headers/shelf_cors_headers.dart' as shelf;
27
+
28
+ Handler middleware(Handler handler) {
29
+ return handler
30
+ .use(requestLogger())
31
+ .use(
32
+ fromShelfMiddleware(
33
+ shelf.corsHeaders(
34
+ headers: {
35
+ shelf.ACCESS_CONTROL_ALLOW_ORIGIN: 'https://myfrontendurl.com',
36
+ },
37
+ ),
38
+ ),
39
+ );
40
+ }
41
+ ```
42
+
43
+ For a full example of a Dart Frog server that handles CORS, check [ Very Good Hub] ( https://github.com/VeryGoodOpenSource/very_good_hub/tree/main/api ) .
You can’t perform that action at this time.
0 commit comments