Skip to content

fix(azure): prevent azure-swa runtime errors, and response body returning {} #4195

Open
Xiang-CH wants to merge 6 commits intonitrojs:mainfrom
Xiang-CH:fix/azure-swa
Open

fix(azure): prevent azure-swa runtime errors, and response body returning {} #4195
Xiang-CH wants to merge 6 commits intonitrojs:mainfrom
Xiang-CH:fix/azure-swa

Conversation

@Xiang-CH
Copy link
Copy Markdown

@Xiang-CH Xiang-CH commented Apr 9, 2026

🔗 Linked issue

#2590

❓ Type of change

  • 📖 Documentation (updates to the documentation, readme, or JSdoc annotations)
  • 🐞 Bug fix (a non-breaking change that fixes an issue)
  • 👌 Enhancement (improving an existing functionality like performance)
  • ✨ New feature (a non-breaking change that adds functionality)
  • 🧹 Chore (updates to the build process or auxiliary tools and libraries)
  • ⚠️ Breaking change (fix or feature that would cause existing functionality to change)

📚 Description

This PR improves the azure-swa preset so Nitro runs reliably on Azure Static Web Apps

What was failing

How it is fixed

  • Outgoing body: Replace passing response.body (a stream) with Buffer.from(await response.arrayBuffer()) when a body exists, so Azure Functions gets bytes instead of a stream object that could surface as {} or otherwise fail at runtime.
  • Incoming headers: Pass headers: new Headers(req.headers) so the Fetch Request receives the same headers as the Azure HTTP trigger
  • Request URL: Build the Request with an absolute URL via new URL(url, resolveBaseUrl(req)) instead of a relative URL string. resolveBaseUrl prefers x-forwarded-proto / x-forwarded-host (or host), then falls back to the origin from x-ms-original-url, then http://localhost.

📝 Checklist

  • I have linked an issue or discussion.
  • I have updated the documentation accordingly.

@Xiang-CH Xiang-CH requested a review from pi0 as a code owner April 9, 2026 07:31
@vercel
Copy link
Copy Markdown

vercel bot commented Apr 9, 2026

@Xiang-CH is attempting to deploy a commit to the Nitro Team on Vercel.

A member of the Team first needs to authorize it.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Apr 9, 2026

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Documentation switched examples to the azure-swa Nitro preset and updated Node runtime selection. Added resolveBaseUrl(req: HttpRequest) to derive an origin from forwarded headers, and updated the Azure SWA runtime to resolve targets against that base, forward headers, and normalize response bodies.

Changes

Cohort / File(s) Summary
Documentation
docs/2.deploy/20.providers/azure.md
Switched examples to the azure-swa preset and local preview command (NITRO_PRESET=azure-swa); changed condition for generating staticwebapp.config.json; updated platform.apiRuntime selection to prefer node:20/node:22 when supported, otherwise fall back to node:18; reformatted tables and removed trailing newline.
Azure Runtime Utilities
src/presets/azure/runtime/_utils.ts
Added type import HttpRequest and exported resolveBaseUrl(req: HttpRequest) which derives an origin from x-forwarded-proto + x-forwarded-host/host, then x-ms-original-url, with fallback "http://localhost".
Azure SWA Runtime
src/presets/azure/runtime/azure-swa.ts
Use resolveBaseUrl to resolve target URLs, forward incoming headers via new Headers(req.headers), and normalize responses by converting response.arrayBuffer() into a Buffer and setting body to undefined when no body is present.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

🚥 Pre-merge checks | ✅ 2 | ❌ 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 (2 passed)
Check name Status Explanation
Title check ✅ Passed The title follows conventional commits format (fix scope) and clearly describes the main changes: fixing azure-swa runtime errors and response body issues.
Description check ✅ Passed The description is well-related to the changeset, explaining what was failing and how it was fixed with specific technical details matching the code changes.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
docs/2.deploy/20.providers/azure.md (1)

30-40: ⚠️ Potential issue | 🟡 Minor

Align this section with the actual preset/runtime selection logic.

Line 32 still says this file is generated for the azure preset, but this page and src/presets/azure/preset.ts:1-27 are about azure-swa. Also, src/presets/azure/utils.ts:6-23 only consults process.versions.node when reading package.json fails; if engines.node exists but is anything other than the exact strings "20" or "22", the generated config stays on node:18.

Proposed fix
-Nitro automatically generates this configuration file whenever the application is built with the `azure` preset.
+Nitro automatically generates this configuration file whenever the application is built with the `azure-swa` preset.
@@
-| **[platform.apiRuntime](https://learn.microsoft.com/en-us/azure/static-web-apps/configuration#platform)**               | Uses `node:20` or `node:22` when `package.json` `engines.node` (or your current Node major version) matches those supported versions; otherwise falls back to `node:18`.                                                                                      | `node:18`     |
+| **[platform.apiRuntime](https://learn.microsoft.com/en-us/azure/static-web-apps/configuration#platform)**               | Uses `node:20` or `node:22` when `package.json` `engines.node` is exactly `20` or `22`. If Nitro cannot read that value, it falls back to your current Node major when it is `20` or `22`; otherwise it uses `node:18`.                                      | `node:18`     |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@docs/2.deploy/20.providers/azure.md` around lines 30 - 40, Update the docs
text to reflect the actual preset and runtime-selection logic: change the preset
name from `azure` to `azure-swa` (referencing src/presets/azure/preset.ts) and
clarify Node runtime selection behavior as implemented in
src/presets/azure/utils.ts — i.e., Nitro reads package.json.engines.node and
will select `node:20` or `node:22` only when the engines.node string exactly
equals "20" or "22", otherwise it falls back to `node:18`; also note that
process.versions.node is only consulted if reading package.json fails. Ensure
the table entry for platform.apiRuntime and any surrounding text reflect this
exact behavior.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@docs/2.deploy/20.providers/azure.md`:
- Line 9: The :read-more shortcode target is malformed; update the
:read-more{...} invocation (the line containing :read-more{title="Azure Static
Web Apps"
to="[https://azure.microsoft.com/en-us/products/app-service/static"}](https://azure.microsoft.com/en-us/products/app-service/static"})
to use a proper to="..." attribute without stray brackets or trailing link
syntax so the to value is exactly the Azure URL (i.e., fix the to attribute
inside the :read-more shortcode).

In `@src/presets/azure/runtime/_utils.ts`:
- Around line 35-48: The resolveBaseUrl function currently returns
`${forwardedProto || "http"}://${host}` directly from untrusted headers;
instead, construct that candidate URL from forwardedProto/host, attempt to parse
it with new URL(...) and only return candidate.origin if parsing succeeds; if
parsing fails, fall through to check x-ms-original-url (parse and return its
origin if valid) and finally return a safe default like "http://localhost";
update references in resolveBaseUrl and ensure headers "x-forwarded-proto",
"x-forwarded-host", and "host" are validated before returning to avoid passing a
malformed base to new URL in azure-swa.ts.

---

Outside diff comments:
In `@docs/2.deploy/20.providers/azure.md`:
- Around line 30-40: Update the docs text to reflect the actual preset and
runtime-selection logic: change the preset name from `azure` to `azure-swa`
(referencing src/presets/azure/preset.ts) and clarify Node runtime selection
behavior as implemented in src/presets/azure/utils.ts — i.e., Nitro reads
package.json.engines.node and will select `node:20` or `node:22` only when the
engines.node string exactly equals "20" or "22", otherwise it falls back to
`node:18`; also note that process.versions.node is only consulted if reading
package.json fails. Ensure the table entry for platform.apiRuntime and any
surrounding text reflect this exact behavior.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 0dfd57d8-e0cc-49e1-acde-3002e1923754

📥 Commits

Reviewing files that changed from the base of the PR and between a5a3389 and 8e53af3.

📒 Files selected for processing (3)
  • docs/2.deploy/20.providers/azure.md
  • src/presets/azure/runtime/_utils.ts
  • src/presets/azure/runtime/azure-swa.ts

Comment thread docs/2.deploy/20.providers/azure.md Outdated
Comment thread src/presets/azure/runtime/_utils.ts
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
docs/2.deploy/20.providers/azure.md (1)

40-40: Clarify that navigationFallback.rewrite is a default, not absolute.

The documentation states that navigationFallback.rewrite "Is always /api/server", but the implementation shows this is the generated default value that can be overridden via azure.config.navigationFallback (see context snippet 3). Consider rephrasing to "Defaults to /api/server" for accuracy.

📝 Suggested clarification
-| **[navigationFallback.rewrite](https://learn.microsoft.com/en-us/azure/static-web-apps/configuration#fallback-routes)** | Is always `/api/server`                                                                                                                                                                                                                                       | `/api/server` |
+| **[navigationFallback.rewrite](https://learn.microsoft.com/en-us/azure/static-web-apps/configuration#fallback-routes)** | Defaults to `/api/server`                                                                                                                                                                                                                                     | `/api/server` |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@docs/2.deploy/20.providers/azure.md` at line 40, Update the docs table entry
that currently reads "Is always `/api/server`" for navigationFallback.rewrite to
indicate it's a generated default (e.g., "Defaults to `/api/server`") and
mention that it can be overridden via azure.config.navigationFallback
(referencing the symbol navigationFallback.rewrite and
azure.config.navigationFallback to locate the text to edit).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@docs/2.deploy/20.providers/azure.md`:
- Line 32: Update the documentation text that says "azure preset" to use the
correct preset name "azure-swa": locate the sentence that reads "built with the
`azure` preset" and change the identifier to `azure-swa` so it matches the rest
of the file and the actual preset definition.

---

Nitpick comments:
In `@docs/2.deploy/20.providers/azure.md`:
- Line 40: Update the docs table entry that currently reads "Is always
`/api/server`" for navigationFallback.rewrite to indicate it's a generated
default (e.g., "Defaults to `/api/server`") and mention that it can be
overridden via azure.config.navigationFallback (referencing the symbol
navigationFallback.rewrite and azure.config.navigationFallback to locate the
text to edit).
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: c3144c67-2d97-45b2-81e4-1c9e48a03dc7

📥 Commits

Reviewing files that changed from the base of the PR and between 8e53af3 and 3f92994.

📒 Files selected for processing (1)
  • docs/2.deploy/20.providers/azure.md

Comment thread docs/2.deploy/20.providers/azure.md Outdated
Xiang-CH and others added 2 commits April 9, 2026 19:31
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/presets/azure/runtime/_utils.ts`:
- Around line 35-61: The resolveBaseUrl function has misplaced/extra braces
causing a syntax error and an unreachable/default return; fix the function body
(function resolveBaseUrl(req: HttpRequest)) by removing the stray closing
brace(s) so the entire logic is inside the function, ensure every conditional
path returns a string (use forwardedProto || "http" when building candidate,
keep the try/catch for new URL(candidate).origin and for new
URL(originalUrl).origin), and add a final return "http://localhost" at the end
of resolveBaseUrl so callers like new URL(url, resolveBaseUrl(req)) never
receive undefined.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: ead93783-8a95-4e76-81cc-4c71f18b410a

📥 Commits

Reviewing files that changed from the base of the PR and between c4884ed and 44b3b80.

📒 Files selected for processing (1)
  • src/presets/azure/runtime/_utils.ts

Comment thread src/presets/azure/runtime/_utils.ts
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

🧹 Nitpick comments (1)
src/presets/azure/runtime/_utils.ts (1)

54-56: Avoid silent fallback for invalid x-ms-original-url.

Line 54 currently swallows parse failures without a warning. Please log this recoverable invalid state (and remove the inline explanatory comment).

Proposed patch
   const originalUrl = req.headers["x-ms-original-url"];
   if (originalUrl) {
     try {
       return new URL(originalUrl).origin;
-    } catch {
-      // ignore invalid original URL
+    } catch (error) {
+      console.warn("[nitro] Invalid Azure SWA original URL", {
+        originalUrl,
+        error,
+      });
     }
   }

As per coding guidelines "Prefer explicit errors over silent failures; use warnings for recoverable situations and throw for invalid states".

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

In `@src/presets/azure/runtime/_utils.ts` around lines 54 - 56, The catch block
that swallows parse failures for the "x-ms-original-url" header in
src/presets/azure/runtime/_utils.ts should not be silent; replace the empty
catch with a warning log that includes the invalid header value and the caught
error (e.g., use the module's logger or console.warn to log `x-ms-original-url`
and error), then continue the fallback logic, and remove the inline explanatory
comment; ensure the log message is concise and clearly identifies the header and
parse failure so recoverable invalid states are visible during debugging.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@src/presets/azure/runtime/_utils.ts`:
- Around line 54-56: The catch block that swallows parse failures for the
"x-ms-original-url" header in src/presets/azure/runtime/_utils.ts should not be
silent; replace the empty catch with a warning log that includes the invalid
header value and the caught error (e.g., use the module's logger or console.warn
to log `x-ms-original-url` and error), then continue the fallback logic, and
remove the inline explanatory comment; ensure the log message is concise and
clearly identifies the header and parse failure so recoverable invalid states
are visible during debugging.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 0c5fb078-90de-43ce-b2a3-e1d7c580e142

📥 Commits

Reviewing files that changed from the base of the PR and between 44b3b80 and 1f93ba7.

📒 Files selected for processing (1)
  • src/presets/azure/runtime/_utils.ts

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.

1 participant