Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion docs/2.deploy/20.providers/azure.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,14 @@ Integration with this provider is possible with [zero configuration](/deploy#zer

[Azure Static Web Apps](https://azure.microsoft.com/en-us/products/app-service/static) are designed to be deployed continuously in a [GitHub Actions workflow](https://docs.microsoft.com/en-us/azure/static-web-apps/github-actions-workflow). Nitro detects this deployment environment and enables the `azure_swa` preset automatically.

The server is deployed as a managed Azure Function using the [Node.js v4 programming model](https://learn.microsoft.com/en-us/azure/azure-functions/functions-reference-node?pivots=nodejs-model-v4). This requires `@azure/functions` v4 in your project dependencies (Nitro offers to install it if it is missing). It is traced into the build output, so it does not need to be installed again during deployment.

:pm-install{name="@azure/functions@^4"}

::note
If you have `@azure/functions` v3 installed, upgrade it to v4. Version 3 uses the legacy programming model (`function.json`) and is no longer supported by this preset.
::

### Local preview

To test locally, install [Azure Functions Core Tools](https://docs.microsoft.com/en-us/azure/azure-functions/functions-run-local), then build and start a local preview environment:
Expand All @@ -33,7 +41,7 @@ Nitro sets the following properties automatically:

| Property | Criteria | Default |
| --- | --- | --- |
| **[platform.apiRuntime](https://learn.microsoft.com/en-us/azure/static-web-apps/configuration#platform)** | Set to `node:20` or `node:22` based on the `engines.node` field in your `package.json`. | `node:20` |
| **[platform.apiRuntime](https://learn.microsoft.com/en-us/azure/static-web-apps/configuration#platform)** | Set to `node:20` or `node:22` based on the `engines.node` field in your `package.json`. | `node:22` |
| **[navigationFallback.rewrite](https://learn.microsoft.com/en-us/azure/static-web-apps/configuration#fallback-routes)** | Always `/api/server` | `/api/server` |
| **[routes](https://learn.microsoft.com/en-us/azure/static-web-apps/configuration#routes)** | All prerendered routes are added. Additionally, if you do not have an `index.html` file, an empty one is created for compatibility purposes, and requests to `/index.html` are redirected to the root directory (handled by `/api/server`). | `[]` |

Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@
},
"devDependencies": {
"@apphosting/common": "^0.0.9",
"@azure/functions": "^3.6.0",
"@azure/functions": "^4.16.5",
"@azure/static-web-apps-cli": "^2.0.10",
"@cloudflare/workers-types": "^5.20260930.2",
"@cloudflare/workers-utils": "^0.45.1",
Expand Down
35 changes: 14 additions & 21 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 5 additions & 1 deletion src/presets/azure/preset.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
import { defineNitroPreset } from "../_utils/preset.ts";
import type { Nitro } from "nitro/types";
import { writeSWARoutes } from "./utils.ts";
import { ensureAzureFunctions, writeSWARoutes } from "./utils.ts";

export type { AzureOptions as PresetOptions } from "./types.ts";

const azureSWA = defineNitroPreset(
{
entry: "./azure/runtime/azure-swa",
traceDeps: ["@azure/functions"],
output: {
serverDir: "{{ output.dir }}/server/functions",
publicDir: "{{ output.dir }}/public/{{ baseURL }}",
Expand All @@ -15,6 +16,9 @@ const azureSWA = defineNitroPreset(
preview: "npx @azure/static-web-apps-cli start ./public --api-location ./server",
},
hooks: {
async "build:before"(nitro: Nitro) {
await ensureAzureFunctions(nitro);
},
async compiled(ctx: Nitro) {
await writeSWARoutes(ctx);
},
Expand Down
12 changes: 6 additions & 6 deletions src/presets/azure/runtime/_utils.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { Cookie, HttpRequest } from "@azure/functions";
import type { Cookie } from "@azure/functions";
import { parse } from "cookie-es";

export function getAzureParsedCookiesFromHeaders(headers: Headers): Cookie[] {
Expand Down Expand Up @@ -32,10 +32,10 @@ export function getAzureParsedCookiesFromHeaders(headers: Headers): Cookie[] {
return azureCookies;
}

export function resolveBaseUrl(req: HttpRequest) {
const forwardedProto = req.headers["x-forwarded-proto"];
const forwardedHost = req.headers["x-forwarded-host"];
const host = forwardedHost || req.headers["host"];
export function resolveBaseUrl(headers: Headers) {
const forwardedProto = headers.get("x-forwarded-proto");
const forwardedHost = headers.get("x-forwarded-host");
const host = forwardedHost || headers.get("host");
if (host) {
const candidate = `${forwardedProto || "http"}://${host}`;
try {
Expand All @@ -47,7 +47,7 @@ export function resolveBaseUrl(req: HttpRequest) {
});
}
}
const originalUrl = req.headers["x-ms-original-url"];
const originalUrl = headers.get("x-ms-original-url");
if (originalUrl) {
try {
return new URL(originalUrl).origin;
Expand Down
43 changes: 20 additions & 23 deletions src/presets/azure/runtime/azure-swa.ts
Original file line number Diff line number Diff line change
@@ -1,42 +1,39 @@
import "#nitro/virtual/polyfills";
import { app } from "@azure/functions";
import { parseURL } from "ufo";
import { useNitroApp } from "nitro/app";
import { getAzureParsedCookiesFromHeaders, resolveBaseUrl } from "./_utils.ts";

import type { HttpRequest, HttpResponse, HttpResponseSimple } from "@azure/functions";
import type { HttpRequest, HttpResponseInit } from "@azure/functions";

const nitroApp = useNitroApp();

export async function handle(context: { res: HttpResponse }, req: HttpRequest) {
let url: string;
if (req.headers["x-ms-original-url"]) {
// This URL has been proxied as there was no static file matching it.
const parsedURL = parseURL(req.headers["x-ms-original-url"]);
url = parsedURL.pathname + parsedURL.search;
} else {
// Because Azure SWA handles /api/* calls differently they
// never hit the proxy and we have to reconstitute the URL.
url = "/api/" + (req.params.url || "");
}
// https://learn.microsoft.com/en-us/azure/azure-functions/functions-reference-node?pivots=nodejs-model-v4
app.http("server", {
route: "{*url}",
methods: ["DELETE", "GET", "HEAD", "OPTIONS", "PATCH", "POST", "PUT"],
authLevel: "anonymous",
handler: handle,
});

const request = new Request(new URL(url, resolveBaseUrl(req)), {
method: req.method || undefined,
headers: new Headers(req.headers),
// https://github.com/Azure/azure-functions-nodejs-worker/issues/294
// https://github.com/Azure/azure-functions-host/issues/293
body: req.bufferBody ?? req.rawBody,
async function handle(req: HttpRequest): Promise<HttpResponseInit> {
// Proxied requests (no matching static file) carry the original URL in `x-ms-original-url`
const { pathname, search } = parseURL(req.headers.get("x-ms-original-url") || req.url);

const request = new Request(new URL(pathname + search, resolveBaseUrl(req.headers)), {
method: req.method,
headers: req.headers,
body: req.body ? await req.arrayBuffer() : undefined,
});

const response = await nitroApp.fetch(request);

// (v3 - current) https://learn.microsoft.com/en-us/azure/azure-functions/functions-reference-node?tabs=typescript%2Cwindows%2Cazure-cli&pivots=nodejs-model-v3#http-response
// (v4) https://learn.microsoft.com/en-us/azure/azure-functions/functions-reference-node?tabs=typescript%2Cwindows%2Cazure-cli&pivots=nodejs-model-v4#http-response
context.res = {
return {
status: response.status,
body: response.body ? Buffer.from(await response.arrayBuffer()) : undefined,
body: response.body,
cookies: getAzureParsedCookiesFromHeaders(response.headers),
headers: Object.fromEntries(
[...response.headers.entries()].filter(([key]) => key !== "set-cookie")
),
} satisfies HttpResponseSimple;
};
}
67 changes: 41 additions & 26 deletions src/presets/azure/utils.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,46 @@
import fsp from "node:fs/promises";
import { resolveModulePath } from "exsolve";
import { writeFile } from "../_utils/fs.ts";
import { ensureDep } from "../../utils/dep.ts";
import type { Nitro } from "nitro/types";
import { join, resolve } from "pathe";

export async function ensureAzureFunctions(nitro: Nitro) {
const reason = "the `azure-swa` preset";
const resolved = await ensureDep({
id: "@azure/functions",
dir: nitro.options.rootDir,
reason,
dev: false,
projectOnly: true,
});
if (!resolved) {
throw new Error(
`\`@azure/functions@^4\` is not installed. Please add it to your dependencies for ${reason}.`
);
}
const pkgPath = resolveModulePath("@azure/functions/package.json", {
from: nitro.options.rootDir,
try: true,
});
const version: string | undefined = pkgPath
? JSON.parse(await fsp.readFile(pkgPath, "utf8")).version
: undefined;
if (version && Number.parseInt(version, 10) < 4) {
throw new Error(
`\`@azure/functions@${version}\` is installed, but ${reason} requires \`@azure/functions@^4\` (Node.js v4 programming model). Please update it in your dependencies.`
);
}
}

export async function writeSWARoutes(nitro: Nitro) {
const host = {
version: "2.0",
};

// https://learn.microsoft.com/en-us/azure/azure-functions/functions-reference-node?tabs=typescript%2Cwindows%2Cazure-cli&pivots=nodejs-model-v4#supported-versions
const supportedNodeVersions = new Set(["20", "22"]);
let nodeVersion = "18";
let nodeVersion = "22";
try {
const currentNodeVersion = JSON.parse(
await fsp.readFile(join(nitro.options.rootDir, "package.json"), "utf8")
Expand Down Expand Up @@ -106,35 +136,20 @@ export async function writeSWARoutes(nitro: Nitro) {
}
}

const functionDefinition = {
entryPoint: "handle",
bindings: [
{
authLevel: "anonymous",
type: "httpTrigger",
direction: "in",
name: "req",
route: "{*url}",
methods: ["delete", "get", "head", "options", "patch", "post", "put"],
},
{
type: "http",
direction: "out",
name: "res",
},
],
};

await writeFile(
resolve(nitro.options.output.serverDir, "function.json"),
JSON.stringify(functionDefinition, null, 2)
);
await writeFile(
resolve(nitro.options.output.serverDir, "../host.json"),
JSON.stringify(host, null, 2)
);
const stubPackageJson = resolve(nitro.options.output.serverDir, "../package.json");
await writeFile(stubPackageJson, JSON.stringify({ private: true }));
const serverPackageJson = resolve(nitro.options.output.serverDir, "../package.json");
await writeFile(
serverPackageJson,
JSON.stringify({ private: true, type: "module", main: "functions/index.mjs" }, null, 2)
);
// Used by Azure Functions Core Tools (`func` / `swa start`) for local preview
await writeFile(
resolve(nitro.options.output.serverDir, "../local.settings.json"),
JSON.stringify({ IsEncrypted: false, Values: { FUNCTIONS_WORKER_RUNTIME: "node" } }, null, 2)
);
await writeFile(
resolve(nitro.options.rootDir, "staticwebapp.config.json"),
JSON.stringify(config, null, 2)
Expand Down
2 changes: 1 addition & 1 deletion test/unit/azure.utils.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ describe("getAzureParsedCookiesFromHeaders", () => {
});

describe("resolveBaseUrl", () => {
const req = (headers: Record<string, string>) => ({ headers }) as any;
const req = (headers: Record<string, string>) => new Headers(headers);

it("uses the forwarded proto and host", () => {
expect(
Expand Down
Loading