Skip to content

refactor!: Use Headers class instead of Map<String, String> when passing headers - #4175

Merged
nielsenko merged 1 commit into
serverpod:mainfrom
nielsenko:server-headers
Nov 10, 2025
Merged

nielsenko merged 1 commit into
serverpod:mainfrom
nielsenko:server-headers

Conversation

@nielsenko

@nielsenko nielsenko commented Nov 10, 2025 •

Copy link
Copy Markdown
Collaborator

Description

Refactors HTTP header handling to use relic's Headers type instead of Map<String, dynamic>.

Changes:

  • Updated httpResponseHeaders and httpOptionsResponseHeaders fields in Server and Serverpod classes from Map<String, dynamic> to Headers
  • Simplified _headers() handler to work directly with Headers instances using Headers.transform()
  • Converted default header constants to use Headers.build()

Fixes #4102

Pre-launch Checklist

  • I read the Contribute page and followed the process outlined there for submitting PRs.
  • This update contains only one single feature or bug fix and nothing else.
  • I read and followed the Dart Style Guide and formatted the code with dart format.
  • I listed at least one issue that this PR fixes in the description above.
  • I updated/added relevant documentation (doc comments with ///), and made sure that the documentation follows the same style as other Serverpod documentation. I checked spelling and grammar.
  • I added new tests to check the change I am making.
  • All existing and new tests are passing.
  • Any breaking changes are documented below.

Breaking changes

Users who directly instantiate Serverpod or Server with custom headers need to use Headers.build() instead of Map literals. Users relying on default headers are not affected.

Summary by CodeRabbit

  • Refactor
    • Enhanced type safety for HTTP header configuration with improved internal header management.

@coderabbitai

coderabbitai Bot commented Nov 10, 2025 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

HTTP response headers in the Server and Serverpod classes are refactored from Map<String, dynamic> to the strongly-typed Headers class. Default header definitions are converted to Headers.build() constructors, and the Serverpod constructor updated to accept optional Headers parameters with null-coalescing defaults.

Changes

Cohort / File(s) Summary
Server header type refactoring
packages/serverpod/lib/src/server/server.dart
Changed httpResponseHeaders and httpOptionsResponseHeaders from Map<String, dynamic> to Headers. Simplified _headers() method to use conditional logic that applies httpOptionsResponseHeaders for OPTIONS requests and httpResponseHeaders otherwise.
Serverpod header type refactoring and defaults
packages/serverpod/lib/src/server/serverpod.dart
Changed httpResponseHeaders and httpOptionsResponseHeaders field types from Map<String, dynamic> to Headers. Converted _defaultHttpResponseHeaders and _defaultHttpOptionsResponseHeaders from const maps to static final Headers.build() instances. Updated constructor to accept optional Headers? parameters and initialize headers via null-coalescing operator.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~15–30 minutes

  • Public API impact: Constructor signature changes and field type modifications to public classes require verification that all call sites handle the new Headers type correctly
  • Default initialization logic: Review the null-coalescing defaults in the Serverpod constructor initializer list and verify Headers.build() conversions preserve intended header values
  • Type conversion: Ensure the transition from Map<String, dynamic> to Headers does not introduce any unintended behavioral changes, particularly in header merging logic within _headers()

Possibly related PRs

Pre-merge checks and finishing touches

✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately describes the main refactoring: converting HTTP header types from Map<String, dynamic> to the Headers class.
Description check ✅ Passed The description includes a clear summary, lists the issue fixed (#4102), completes most pre-launch checklist items, and documents the breaking changes.
Linked Issues check ✅ Passed The PR fulfills the primary objectives from issue #4102: replacing Map-based headers with the Headers class, refactoring code to use Headers type, and updating related APIs with type safety improvements.
Out of Scope Changes check ✅ Passed All changes focus narrowly on converting HTTP header types from Map<String, dynamic> to Headers class as specified in issue #4102, with no unrelated modifications.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f232d1b and b4c3f4f.

📒 Files selected for processing (2)
  • packages/serverpod/lib/src/server/server.dart (2 hunks)
  • packages/serverpod/lib/src/server/serverpod.dart (2 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
**/*.dart

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

**/*.dart: Format all Dart code using dart format . before committing
Code must pass Dart analyzer in strict mode (util/run_tests_analyze or melos lint_strict)
Use descriptive variable and function names

Files:

  • packages/serverpod/lib/src/server/server.dart
  • packages/serverpod/lib/src/server/serverpod.dart
**/lib/**/*.dart

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Remove unnecessary comments from production code

Files:

  • packages/serverpod/lib/src/server/server.dart
  • packages/serverpod/lib/src/server/serverpod.dart
🧠 Learnings (5)
📓 Common learnings
Learnt from: nielsenko
Repo: serverpod/serverpod PR: 3980
File: packages/serverpod/lib/src/web_server/web_server.dart:102-115
Timestamp: 2025-09-17T16:09:20.868Z
Learning: In Serverpod's web server authentication handling (packages/serverpod/lib/src/web_server/web_server.dart), query parameter authentication fallback (`authenticationKey ??= queryParameters['auth']`) is intentionally maintained for legacy compatibility reasons, even though it has security implications regarding credential leakage.
📚 Learning: 2025-11-03T15:40:41.827Z
Learnt from: SandPod
Repo: serverpod/serverpod PR: 4144
File: modules/new_serverpod_auth/serverpod_auth_idp/serverpod_auth_idp_server/lib/src/providers/passkey/endpoints/passkey_idp_base_endpoint.dart:0-0
Timestamp: 2025-11-03T15:40:41.827Z
Learning: In Serverpod authentication IDP endpoint files (modules/new_serverpod_auth/serverpod_auth_idp/serverpod_auth_idp_server), endpoint base classes should import `serverpod_auth_idp_server/core.dart` to access the Session type, rather than importing `package:serverpod_auth_core_server/session.dart` directly. This pattern is consistently used in Apple, Email, and Google endpoint files.

Applied to files:

  • packages/serverpod/lib/src/server/server.dart
  • packages/serverpod/lib/src/server/serverpod.dart
📚 Learning: 2025-07-02T16:07:50.947Z
Learnt from: tp
Repo: serverpod/serverpod PR: 3747
File: modules/new_serverpod_auth/serverpod_auth_migration/serverpod_auth_migration_server/lib/src/business/migrating_email_endpoint_base.dart:4-4
Timestamp: 2025-07-02T16:07:50.947Z
Learning: In Serverpod, tp prefers importing the full package (e.g., 'package:serverpod_auth_migration_server/serverpod_auth_migration_server.dart') as a baseline rather than using smaller local imports, even within the same package where it might be considered a "self-import".

Applied to files:

  • packages/serverpod/lib/src/server/server.dart
  • packages/serverpod/lib/src/server/serverpod.dart
📚 Learning: 2025-09-17T16:09:20.868Z
Learnt from: nielsenko
Repo: serverpod/serverpod PR: 3980
File: packages/serverpod/lib/src/web_server/web_server.dart:102-115
Timestamp: 2025-09-17T16:09:20.868Z
Learning: In Serverpod's web server authentication handling (packages/serverpod/lib/src/web_server/web_server.dart), query parameter authentication fallback (`authenticationKey ??= queryParameters['auth']`) is intentionally maintained for legacy compatibility reasons, even though it has security implications regarding credential leakage.

Applied to files:

  • packages/serverpod/lib/src/server/server.dart
  • packages/serverpod/lib/src/server/serverpod.dart
📚 Learning: 2025-08-25T19:46:58.073Z
Learnt from: tp
Repo: serverpod/serverpod PR: 3917
File: modules/new_serverpod_auth/serverpod_auth_idp/serverpod_auth_idp_server/analysis_options.yaml:3-6
Timestamp: 2025-08-25T19:46:58.073Z
Learning: In Serverpod, test tool paths like `test/integration/test_tools/serverpod_test_tools.dart` are configured per project in the "generator.yaml" file and managed by a generator system, so they don't need to be updated manually across all files at once.

Applied to files:

  • packages/serverpod/lib/src/server/serverpod.dart
🔇 Additional comments (5)
packages/serverpod/lib/src/server/server.dart (2)

100-104: LGTM! Type safety improvement.

The refactoring from Map<String, dynamic> to Headers improves type safety and API consistency. The fields are properly declared as final and are required in the constructor.


248-274: Excellent refactoring of the headers handler.

The updated implementation correctly uses Headers.transform() to create modified copies. The logic is sound:

  • For OPTIONS requests: merges httpOptionsResponseHeaders into httpResponseHeaders (OPTIONS headers override base headers).
  • For non-OPTIONS requests: merges default headers into response headers using ??= (response-specific headers take precedence).

This maintains the expected CORS behavior while improving type safety.

packages/serverpod/lib/src/server/serverpod.dart (3)

326-330: LGTM! Consistent type refactoring.

The field type changes from Map<String, dynamic> to Headers are consistent with the refactoring in server.dart and improve type safety throughout the codebase.


332-348: Well-structured default headers configuration.

The default headers are properly constructed using Headers.build() with sensible CORS defaults:

  • Base headers allow wildcard origin and POST method
  • OPTIONS headers include standard request headers (Content-Type, Authorization, etc.)

The use of static final ensures these are instantiated once and reused efficiently.


377-385: Constructor properly handles optional Headers parameters.

The constructor correctly accepts optional Headers? parameters and uses null-coalescing to provide defaults. This maintains backward compatibility for users who don't provide custom headers while requiring users with custom headers to migrate to the new Headers.build() API.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@nielsenko nielsenko self-assigned this Nov 10, 2025
@nielsenko

Copy link
Copy Markdown
Collaborator Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Nov 10, 2025

Copy link
Copy Markdown
Contributor
✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@nielsenko
nielsenko marked this pull request as ready for review November 10, 2025 09:37
@nielsenko
nielsenko requested a review from a team November 10, 2025 09:37
@nielsenko

Copy link
Copy Markdown
Collaborator Author

To be honest I think setting default headers, etc. belong in the configure middleware realm. However we currently only support middleware on WebServer. This may change in the near future with #4126

@exaby73 exaby73 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Small discussion point but I think it might be overkill

@SandPod SandPod left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Changes looks good to me! 🚀

@nielsenko
nielsenko merged commit 6130083 into serverpod:main Nov 10, 2025
@github-actions github-actions Bot locked and limited conversation to collaborators Nov 10, 2025
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Refactor httpResponseHeaders to use Headers class from relic package

3 participants