-
Notifications
You must be signed in to change notification settings - Fork 88
feat: Document how to use the HTTP client override parameter #530
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
marcelomendoncasoares
wants to merge
3
commits into
serverpod:main
Choose a base branch
from
marcelomendoncasoares:http-client-override
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
ca3cfa9
feat: Document how to use the HTTP client override parameter
marcelomendoncasoares 6e09214
fix: Move back the client setup to the "Working with endpoints"
marcelomendoncasoares 6bbaaa9
fix: Improve the "Security Configuration" with examples
marcelomendoncasoares File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
114 changes: 114 additions & 0 deletions
114
docs/06-concepts/01-working-with-endpoints/03-configure-http-calls.md
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,114 @@ | ||
| # Configure HTTP calls | ||
|
|
||
| The generated `Client` accepts an optional `httpClientOverride` parameter that controls the underlying HTTP transport used for API calls. Use it when you need to customize how requests are sent, such as enabling browser credentials or using platform-native HTTP stacks. | ||
|
|
||
| ## Include CORS credentials on web | ||
|
|
||
| By default, browser requests do not include cookies or HTTP authentication credentials in cross-origin requests. If your app relies on cookie-based sessions or similar mechanisms, pass a `BrowserClient` with `withCredentials` enabled: | ||
|
|
||
| ```dart | ||
| import 'package:http/browser_client.dart'; | ||
|
|
||
| final client = Client( | ||
| serverUrl, | ||
| httpClientOverride: BrowserClient()..withCredentials = true, | ||
| ); | ||
| ``` | ||
|
|
||
| On the server, Serverpod adds CORS headers to API responses by default through `httpResponseHeaders` and `httpOptionsResponseHeaders` on the `Serverpod` constructor. The defaults allow cross-origin `POST` requests from any origin (`Access-Control-Allow-Origin: *`) and permit common request headers such as `Authorization` on preflight `OPTIONS` requests. | ||
|
|
||
| Credential-aware requests require stricter headers: the browser rejects `Access-Control-Allow-Origin: *` when credentials are included, and the server must respond with `Access-Control-Allow-Credentials: true` and a specific origin. Override the defaults in your `lib/server.dart` (or wherever you construct `Serverpod`): | ||
|
|
||
| ```dart | ||
| import 'package:serverpod/serverpod.dart'; | ||
|
|
||
| import 'src/generated/protocol.dart'; | ||
| import 'src/generated/endpoints.dart'; | ||
|
|
||
| /// The starting point of the Serverpod server. | ||
| void run(List<String> args) async { | ||
| // Initialize Serverpod and connect it with your generated code. | ||
| final pod = Serverpod( | ||
| args, | ||
| Protocol(), | ||
| Endpoints(), | ||
| httpResponseHeaders: Headers.build((mh) { | ||
| mh.accessControlAllowOrigin = AccessControlAllowOriginHeader.origin( | ||
| origin: Uri.parse('http://localhost:49660'), // Your Flutter web app origin | ||
| ); | ||
| mh.accessControlAllowCredentials = true; | ||
| mh.accessControlAllowMethods = AccessControlAllowMethodsHeader.methods( | ||
| [Method.post], | ||
| ); | ||
| }), | ||
| httpOptionsResponseHeaders: Headers.build((mh) { | ||
| mh.accessControlAllowHeaders = AccessControlAllowHeadersHeader.headers([ | ||
| 'Content-Type', | ||
| 'Authorization', | ||
| 'Accept', | ||
| 'User-Agent', | ||
| 'X-Requested-With', | ||
| ]); | ||
| }), | ||
| ); | ||
|
|
||
| // Start the server | ||
| await pod.start(); | ||
| } | ||
| ``` | ||
|
|
||
| Set `origin` to the exact origin of your Flutter web app (scheme, host, and port). In production, list each allowed origin explicitly. | ||
|
|
||
| ## Use platform-native HTTP clients | ||
|
|
||
| You can also override the default HTTP client with a platform-native HTTP client. On iOS and macOS, you can use [cupertino_http](https://pub.dev/packages/cupertino_http) to route traffic through `NSURLSession`. On Android, you can use [cronet_http](https://pub.dev/packages/cronet_http) to use the Cronet network stack. | ||
|
|
||
| Below is an example of how to override the default HTTP client with platform-native HTTP clients. | ||
|
|
||
| ```dart | ||
| import 'dart:io'; | ||
|
|
||
| import 'package:cronet_http/cronet_http.dart'; | ||
| import 'package:cupertino_http/cupertino_http.dart'; | ||
| import 'package:http/http.dart' as http; | ||
|
|
||
| import 'package:my_project_client/my_project_client.dart'; | ||
|
|
||
| void main() async { | ||
| http.Client? httpClient; | ||
|
|
||
| if (Platform.isAndroid) { | ||
| final engine = CronetEngine.build( | ||
| cacheMode: CacheMode.memory, | ||
| cacheMaxSize: 2 * 1024 * 1024, | ||
| userAgent: 'Book Agent'); | ||
| httpClient = CronetClient.fromCronetEngine(engine, closeEngine: true); | ||
| } else if (Platform.isIOS || Platform.isMacOS) { | ||
| final config = URLSessionConfiguration.ephemeralSessionConfiguration() | ||
| ..cache = URLCache.withCapacity(memoryCapacity: 2 * 1024 * 1024) | ||
| ..httpAdditionalHeaders = {'User-Agent': 'Book Agent'}; | ||
| httpClient = CupertinoClient.fromSessionConfiguration(config); | ||
| } | ||
|
|
||
| final client = Client( | ||
| serverUrl, | ||
| httpClientOverride: httpClient, | ||
| ); | ||
| } | ||
| ``` | ||
|
|
||
| ### Support web with conditional imports | ||
|
|
||
| The above example does not work if your app also targets web, since `dart:io` is not available there. Put the platform-specific `http.Client` creation logic behind a conditional import instead: | ||
|
|
||
| ```dart | ||
| import 'src/http_client_stub.dart' | ||
| if (dart.library.io) 'src/http_client_io.dart'; | ||
|
|
||
| final client = Client( | ||
| serverUrl, | ||
| httpClientOverride: createHttpClient(), | ||
| ); | ||
| ``` | ||
|
|
||
| Add the corresponding package to your Flutter app's `pubspec.yaml` before using these clients. |
File renamed without changes.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.