Skip to content

fix: send empty JSON body on POST requests without a body - #19

Merged
ouwargui merged 1 commit into
ouwargui:mainfrom
ilyagru:fix/empty-post-body
Mar 16, 2026
Merged

fix: send empty JSON body on POST requests without a body#19
ouwargui merged 1 commit into
ouwargui:mainfrom
ilyagru:fix/empty-post-body

Conversation

@ilyagru

@ilyagru ilyagru commented Mar 15, 2026

Copy link
Copy Markdown
Contributor

Problem

When BetterAuthSwift sends a POST request without an explicit body (e.g. signOut()), the request arrives at the better-auth server with an empty body. The server unconditionally calls JSON.parse() on the request body for POST endpoints, and JSON.parse("") throws a SyntaxError, resulting in a 500 Internal Server Error.

Fix

Send {} as the HTTP body for POST requests that have no explicit body set, matching the server's expectation of a valid JSON payload.

} else if self.method == "POST" {
    request.httpBody = Data("{}".utf8)
}

Testing

  • Call client.signOut() against a better-auth server — previously returned 500, now returns 200 with { "success": true }.

Fixes #18

Summary by CodeRabbit

Bug Fixes

  • Enhanced POST request reliability by automatically providing a valid JSON structure when no request body is specified, ensuring consistent JSON parsing across all request scenarios.

The better-auth server always calls JSON.parse() on the request body
for POST endpoints. When BetterAuthSwift sends a POST with no body
(e.g. sign-out), the server receives an empty string and
JSON.parse("") throws, causing a 500 Internal Server Error.

Send `{}` as the body for POST requests that have no explicit body,
matching the server's expectation of a valid JSON payload.

Fixes ouwargui#18
@coderabbitai

coderabbitai Bot commented Mar 15, 2026

Copy link
Copy Markdown

Walkthrough

Adds a fallback to HTTPRequestContext.buildUrlRequest that injects an empty JSON object ({}) as the request body for POST requests that lack a body, preventing server JSON parsing errors during requests like signOut.

Changes

Cohort / File(s) Summary
Middleware Fallback
Sources/Core/Plugins/Middleware.swift
Added POST request body fallback that injects empty JSON object when body is nil, resolving JSON parsing failures on server-side.

Estimated code review effort

🎯 1 (Trivial) | ⏱️ ~3 minutes

Poem

🐰 A POST without a body, such a lonely request—
Empty JSON whispers, "404—no rest!"
But now a {} arrives, like carrots on a plate,
The server parses happily—signOut works great! 🥕✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately and concisely describes the main change: adding empty JSON body handling for POST requests without a body.
Linked Issues check ✅ Passed The pull request directly addresses issue #18 by implementing the fix to send empty JSON body on POST requests, resolving the JSON.parse() error and 500 response.
Out of Scope Changes check ✅ Passed All changes are scoped to the specific problem: adding a fallback for POST requests without a body in HTTPRequestContext.buildUrlRequest.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
📝 Coding Plan
  • Generate coding plan for human review comments

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.

Tip

You can generate walkthrough in a markdown collapsible section to save space.

Enable the reviews.collapse_walkthrough setting to generate walkthrough in a markdown collapsible section.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🧹 Nitpick comments (1)
Sources/Core/Plugins/Middleware.swift (1)

59-63: LGTM! The fix correctly addresses the server JSON parsing issue.

The implementation properly injects an empty JSON object for POST requests without a body, which resolves the JSON.parse("") error on the server. The comment clearly explains the rationale.

One minor consideration: the method comparison is case-sensitive. While HTTP methods should be uppercase per RFC 7230, and your codebase consistently uses "POST", you could make this slightly more defensive:

💡 Optional: Case-insensitive comparison
-    } else if self.method == "POST" {
+    } else if self.method.uppercased() == "POST" {

This is optional since all your route definitions already use uppercase consistently.

,

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@Sources/Core/Plugins/Middleware.swift` around lines 59 - 63, The POST check
is case-sensitive (self.method == "POST"); make it defensive by comparing
case-insensitively (e.g., normalize self.method via uppercased()/lowercased() or
use a case-insensitive comparison) before setting request.httpBody to
Data("{}".utf8) in Middleware.swift so that the POST branch reliably triggers
regardless of method casing while preserving the existing behavior of injecting
an empty JSON body.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@Sources/Core/Plugins/Middleware.swift`:
- Around line 59-63: The POST check is case-sensitive (self.method == "POST");
make it defensive by comparing case-insensitively (e.g., normalize self.method
via uppercased()/lowercased() or use a case-insensitive comparison) before
setting request.httpBody to Data("{}".utf8) in Middleware.swift so that the POST
branch reliably triggers regardless of method casing while preserving the
existing behavior of injecting an empty JSON body.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 4b7ff8d5-0eca-4262-9d19-ca7bd6059734

📥 Commits

Reviewing files that changed from the base of the PR and between d7bbc6c and ed77ac7.

📒 Files selected for processing (1)
  • Sources/Core/Plugins/Middleware.swift

@ouwargui

Copy link
Copy Markdown
Owner

thx for the contribution

@ouwargui
ouwargui merged commit f2a4514 into ouwargui:main Mar 16, 2026
2 checks passed
@ilyagru
ilyagru deleted the fix/empty-post-body branch March 17, 2026 09:29
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

signOut() causes server error 500 – Unexpected end of JSON input

2 participants