Skip to content

fix(build,azure-swa): prefer index.mjs serverEntry; fix Azure SWA request URL and body#4352

Open
tonoizer wants to merge 3 commits into
nitrojs:mainfrom
tonoizer:fix/mf-server-entry-azure-swa
Open

fix(build,azure-swa): prefer index.mjs serverEntry; fix Azure SWA request URL and body#4352
tonoizer wants to merge 3 commits into
nitrojs:mainfrom
tonoizer:fix/mf-server-entry-azure-swa

Conversation

@tonoizer

@tonoizer tonoizer commented Jun 15, 2026

Copy link
Copy Markdown

Problem

Three bugs that compound when deploying a Nitro fullstack app with Vite Module Federation exposes (and when using the Azure Static Web Apps preset).

Reproduction demo

Demo repo: https://github.com/tonoizer/demo-nitro-vite-module-federation-serverEntry-bug

Minimal repro for the serverEntry / vite preview issue:

pnpm dlx create-nitro-app my-app
cd my-app
pnpm add -D @module-federation/vite
# add federation plugin + expose (see demo repo vite.config.ts / module-federation.config.ts)
pnpm build
pnpm check          # fails: serverEntry is server/_chunks/app.mjs
pnpm preview        # broken: 404 on / and /api/*
pnpm preview:workaround   # works: node .output/server/index.mjs

pnpm dev works — only production preview is broken because it relies on .output/nitro.json.


1. Wrong serverEntry in nitro.json

writeBuildInfo used .find() to pick the first isEntry chunk from Rollup output. Vite Module Federation marks expose chunks as entry points too, so when they appear before server/index.mjs in the output array, nitro.json points at e.g. server/_chunks/app.mjs instead of the server bundle. vite preview then loads a file with no fetch handler → 404 everywhere.

2. Azure SWA: relative URL passed to new Request()

azure-swa.ts constructed a relative path (/api/... or pathname + search) and passed it directly to new Request(url, ...). Node.js requires an absolute URL — this throws in production and breaks all /api/* routes.

3. Azure SWA: response body handling

context.res.body was set incorrectly for Azure Functions v3 (which expects string | Buffer). Text responses could be empty/wrong; binary responses were corrupted when unconditionally calling .text().

Fix

  • resolveNitroServerEntryFileName — when multiple isEntry chunks exist, prefer the one matching /(^|\/)index\.mjs$/ (Nitro's server entry convention) instead of taking array-first.
  • resolveAzureSwaRequestUrl — use x-ms-original-url as-is (it's already an absolute URL) or construct new URL(path, "http://nitro.local").href for direct /api/* calls.
  • azureResponseBody — inspect content-type and return UTF-8 string for text types or Buffer for binary (same pattern as AWS Lambda preset).
  • Unit tests for extracted helpers.

Test plan

  • pnpm vitest run test/unit/build-info.test.ts test/unit/azure-swa.test.ts
  • Demo repo: pnpm build && pnpm check passes; pnpm preview serves SPA + /api/hello
  • Azure SWA preset: /api/* routes return real JSON/HTML; binary routes return correct bytes

…RL and body

- extract resolveNitroServerEntryFileName: when multiple isEntry chunks exist
  (e.g. Module Federation expose chunks), prefer the one matching index.mjs
  instead of taking the first chunk arbitrarily
- resolveAzureSwaRequestUrl: use x-ms-original-url as-is (full absolute URL)
  or construct an absolute URL via new URL(..., "http://nitro.local") —
  new Request() requires an absolute URL in Node.js
- materialise response.body as text before assigning to context.res.body;
  Azure Functions v3 cannot serialise a ReadableStream
- add unit tests for both helpers
@tonoizer tonoizer requested a review from pi0 as a code owner June 15, 2026 18:47
@vercel

vercel Bot commented Jun 15, 2026

Copy link
Copy Markdown

@tonoizer is attempting to deploy a commit to the Nitro Team on Vercel.

A member of the Team first needs to authorize it.

@coderabbitai

coderabbitai Bot commented Jun 15, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: b30f506f-c550-4156-8131-b3c40acb250c

📥 Commits

Reviewing files that changed from the base of the PR and between 3352e10 and 48a014c.

📒 Files selected for processing (2)
  • src/presets/azure/runtime/_utils.ts
  • test/unit/azure-swa.test.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • test/unit/azure-swa.test.ts
  • src/presets/azure/runtime/_utils.ts

📝 Walkthrough

Walkthrough

Two independent helpers are extracted and exported with unit tests. resolveNitroServerEntryFileName selects the correct Rollup/Rolldown entry chunk filename, preferring index.mjs when multiple entries exist. In Azure SWA, resolveAzureSwaRequestUrl encapsulates URL computation using the x-ms-original-url header or params.url, and azureResponseBody serializes response bodies to text or binary.

Changes

Server Entry Filename Resolution

Layer / File(s) Summary
resolveNitroServerEntryFileName helper and writeBuildInfo wiring
src/build/info.ts, test/unit/build-info.test.ts
Defines a local OutputChunk type and the exported resolveNitroServerEntryFileName with single-entry, index.mjs-preference, and first-entry fallback logic. Updates writeBuildInfo to call it. Five test cases cover no-entry, sole-entry, multi-entry with index.mjs, multi-entry fallback, and non-entry chunk filtering.

Azure SWA URL Resolution and Body Serialization

Layer / File(s) Summary
resolveAzureSwaRequestUrl extraction and tests
src/presets/azure/runtime/azure-swa.ts, test/unit/azure-swa.test.ts
Imports updated by removing parseURL. resolveAzureSwaRequestUrl is exported to return x-ms-original-url when present or reconstruct an absolute /api/* URL from req.params.url. Three test cases cover header pass-through and URL construction for populated and empty params.url.
azureResponseBody helper and tests
src/presets/azure/runtime/_utils.ts, test/unit/azure-swa.test.ts
Exports azureResponseBody that converts a Response body stream into a Buffer, then conditionally returns a UTF-8 string or Buffer based on the content-type header. Tests verify undefined for no-body responses, text return for text content types, and Buffer return for binary types.
handle() integration of URL and body helpers
src/presets/azure/runtime/azure-swa.ts
Refactors handle() to build the Request with resolveAzureSwaRequestUrl(req) and convert the Nitro fetch() response body via azureResponseBody(response), then assign the converted body and status to context.res.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Possibly related PRs

  • nitrojs/nitro#3999: Modifies src/build/info.ts and writeBuildInfo to extend server entry derivation, overlapping directly with the resolveNitroServerEntryFileName changes in this PR.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 37.50% 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
Title check ✅ Passed The title follows conventional commits format with type 'fix' and scope covering the affected modules; it clearly summarizes the main changes across build info and Azure SWA preset.
Description check ✅ Passed The description is comprehensive and directly related to the changeset, detailing the three bugs being fixed and how the changes address each issue.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ 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.

@coderabbitai coderabbitai Bot 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.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/presets/azure/runtime/azure-swa.ts`:
- Around line 27-28: The response body conversion in azure-swa.ts is using
`.text()` which corrupts binary responses by assuming UTF-8 encoding. Instead of
unconditionally calling `.text()` on the Response object, inspect the
content-type header from the response to determine the correct handling: for
binary content types (images, PDFs, etc.), use `arrayBuffer()` and convert the
result to a Buffer that Azure Functions v3 expects, and for text content types
use `.text()`. Follow the same pattern already implemented in the AWS Lambda
preset to maintain consistency across presets.
🪄 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: 34ecfe6a-7c6d-44a2-9946-b082cf2dc6e0

📥 Commits

Reviewing files that changed from the base of the PR and between 7765bcb and a115713.

📒 Files selected for processing (4)
  • src/build/info.ts
  • src/presets/azure/runtime/azure-swa.ts
  • test/unit/azure-swa.test.ts
  • test/unit/build-info.test.ts

Comment thread src/presets/azure/runtime/azure-swa.ts Outdated

@coderabbitai coderabbitai Bot 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.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/presets/azure/runtime/_utils.ts`:
- Around line 68-70: The `isTextType` function's regex pattern only matches
media types with `/json`, `/xml`, and `/javascript` but misses the `+json` and
`+xml` suffixes commonly used in structured media types like
`application/problem+json`. Update the regex pattern in the `isTextType`
function on Line 69 to include both the slash variants `/(javascript|json|xml)`
and the plus variants `\+(json|xml)` so that types with either separator are
correctly identified as text and not returned as binary Buffer.
🪄 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: d7dbf344-fb20-4eec-8ce2-b8ce200b0e1a

📥 Commits

Reviewing files that changed from the base of the PR and between a115713 and 3352e10.

📒 Files selected for processing (3)
  • src/presets/azure/runtime/_utils.ts
  • src/presets/azure/runtime/azure-swa.ts
  • test/unit/azure-swa.test.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/presets/azure/runtime/azure-swa.ts

Comment thread src/presets/azure/runtime/_utils.ts
…on content types and add corresponding unit test
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