Skip to content

Commit 9a8f7e9

Browse files
erickzanardoScarlett Eliza
andauthored
docs: Adding docs about CORS (#867)
Co-authored-by: Scarlett Eliza <[email protected]>
1 parent 8bcf0c5 commit 9a8f7e9

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

docs/docs/advanced/cors.md

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
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).

0 commit comments

Comments
 (0)