azure-static-web-apps

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Overview

概述

Azure Static Web Apps (SWA) hosts static frontends with optional serverless API backends. The SWA CLI (
swa
) provides local development emulation and deployment capabilities.
Key features:
  • Local emulator with API proxy and auth simulation
  • Framework auto-detection and configuration
  • Direct deployment to Azure
  • Database connections support
Config files:
  • swa-cli.config.json
    - CLI settings, created by
    swa init
    (never create manually)
  • staticwebapp.config.json
    - Runtime config (routes, auth, headers, API runtime) - can be created manually
Azure Static Web Apps (SWA) 托管静态前端,并可搭配可选的无服务器API后端。SWA CLI(
swa
)提供本地开发模拟和部署功能。
主要特性:
  • 包含API代理和身份验证模拟的本地模拟器
  • 框架自动检测与配置
  • 直接部署到Azure
  • 支持数据库连接
配置文件:
  • swa-cli.config.json
    - CLI设置,通过
    swa init
    创建
    (切勿手动创建)
  • staticwebapp.config.json
    - 运行时配置(路由、身份验证、请求头、API运行时)- 可手动创建

General Instructions

通用说明

Installation

安装

bash
npm install -D @azure/static-web-apps-cli
Verify:
npx swa --version
bash
npm install -D @azure/static-web-apps-cli
验证:
npx swa --version

Quick Start Workflow

快速开始流程

IMPORTANT: Always use
swa init
to create configuration files. Never manually create
swa-cli.config.json
.
  1. swa init
    - Required first step - auto-detects framework and creates
    swa-cli.config.json
  2. swa start
    - Run local emulator at
    http://localhost:4280
  3. swa login
    - Authenticate with Azure
  4. swa deploy
    - Deploy to Azure
重要提示:始终使用
swa init
创建配置文件。切勿手动创建
swa-cli.config.json
  1. swa init
    - 必须执行的第一步 - 自动检测框架并创建
    swa-cli.config.json
  2. swa start
    - 在
    http://localhost:4280
    启动本地模拟器
  3. swa login
    - 登录Azure进行身份验证
  4. swa deploy
    - 部署到Azure

Configuration Files

配置文件

swa-cli.config.json - Created by
swa init
, do not create manually:
  • Run
    swa init
    for interactive setup with framework detection
  • Run
    swa init --yes
    to accept auto-detected defaults
  • Edit the generated file only to customize settings after initialization
Example of generated config (for reference only):
json
{
  "$schema": "https://aka.ms/azure/static-web-apps-cli/schema",
  "configurations": {
    "app": {
      "appLocation": ".",
      "apiLocation": "api",
      "outputLocation": "dist",
      "appBuildCommand": "npm run build",
      "run": "npm run dev",
      "appDevserverUrl": "http://localhost:3000"
    }
  }
}
staticwebapp.config.json (in app source or output folder) - This file CAN be created manually for runtime configuration:
json
{
  "navigationFallback": {
    "rewrite": "/index.html",
    "exclude": ["/images/*", "/css/*"]
  },
  "routes": [
    { "route": "/api/*", "allowedRoles": ["authenticated"] }
  ],
  "platform": {
    "apiRuntime": "node:20"
  }
}
swa-cli.config.json - 通过
swa init
创建,请勿手动创建:
  • 运行
    swa init
    进行交互式设置,自动检测框架
  • 运行
    swa init --yes
    接受自动检测的默认设置
  • 仅在初始化后可编辑生成的文件来自定义设置
生成的配置示例(仅供参考):
json
{
  "$schema": "https://aka.ms/azure/static-web-apps-cli/schema",
  "configurations": {
    "app": {
      "appLocation": ".",
      "apiLocation": "api",
      "outputLocation": "dist",
      "appBuildCommand": "npm run build",
      "run": "npm run dev",
      "appDevserverUrl": "http://localhost:3000"
    }
  }
}
staticwebapp.config.json(位于应用源码或输出文件夹中)- 此文件可手动创建用于运行时配置:
json
{
  "navigationFallback": {
    "rewrite": "/index.html",
    "exclude": ["/images/*", "/css/*"]
  },
  "routes": [
    { "route": "/api/*", "allowedRoles": ["authenticated"] }
  ],
  "platform": {
    "apiRuntime": "node:20"
  }
}

Command-line Reference

命令行参考

swa login

swa login

Authenticate with Azure for deployment.
bash
swa login                              # Interactive login
swa login --subscription-id <id>       # Specific subscription
swa login --clear-credentials          # Clear cached credentials
Flags:
--subscription-id, -S
|
--resource-group, -R
|
--tenant-id, -T
|
--client-id, -C
|
--client-secret, -CS
|
--app-name, -n
登录Azure以进行部署。
bash
swa login                              # 交互式登录
swa login --subscription-id <id>       # 指定订阅
swa login --clear-credentials          # 清除缓存的凭据
参数:
--subscription-id, -S
|
--resource-group, -R
|
--tenant-id, -T
|
--client-id, -C
|
--client-secret, -CS
|
--app-name, -n

swa init

swa init

Configure a new SWA project based on an existing frontend and (optional) API. Detects frameworks automatically.
bash
swa init                    # Interactive setup
swa init --yes              # Accept defaults
基于现有前端和(可选)API配置新的SWA项目。自动检测框架。
bash
swa init                    # 交互式设置
swa init --yes              # 接受默认设置

swa build

swa build

Build frontend and/or API.
bash
swa build                   # Build using config
swa build --auto            # Auto-detect and build
swa build myApp             # Build specific configuration
Flags:
--app-location, -a
|
--api-location, -i
|
--output-location, -O
|
--app-build-command, -A
|
--api-build-command, -I
构建前端和/或API。
bash
swa build                   # 使用配置文件构建
swa build --auto            # 自动检测并构建
swa build myApp             # 构建特定配置
参数:
--app-location, -a
|
--api-location, -i
|
--output-location, -O
|
--app-build-command, -A
|
--api-build-command, -I

swa start

swa start

Start local development emulator.
bash
swa start                                    # Serve from outputLocation
swa start ./dist                             # Serve specific folder
swa start http://localhost:3000              # Proxy to dev server
swa start ./dist --api-location ./api        # With API folder
swa start http://localhost:3000 --run "npm start"  # Auto-start dev server
Common framework ports:
FrameworkPort
React/Vue/Next.js3000
Angular4200
Vite5173
Key flags:
  • --port, -p
    - Emulator port (default: 4280)
  • --api-location, -i
    - API folder path
  • --api-port, -j
    - API port (default: 7071)
  • --run, -r
    - Command to start dev server
  • --open, -o
    - Open browser automatically
  • --ssl, -s
    - Enable HTTPS
启动本地开发模拟器。
bash
swa start                                    # 从outputLocation提供服务
swa start ./dist                             # 为特定文件夹提供服务
swa start http://localhost:3000              # 代理到开发服务器
swa start ./dist --api-location ./api        # 搭配API文件夹
swa start http://localhost:3000 --run "npm start"  # 自动启动开发服务器
常见框架端口:
框架端口
React/Vue/Next.js3000
Angular4200
Vite5173
主要参数:
  • --port, -p
    - 模拟器端口(默认:4280)
  • --api-location, -i
    - API文件夹路径
  • --api-port, -j
    - API端口(默认:7071)
  • --run, -r
    - 启动开发服务器的命令
  • --open, -o
    - 自动打开浏览器
  • --ssl, -s
    - 启用HTTPS

swa deploy

swa deploy

Deploy to Azure Static Web Apps.
bash
swa deploy                              # Deploy using config
swa deploy ./dist                       # Deploy specific folder
swa deploy --env production             # Deploy to production
swa deploy --deployment-token <TOKEN>   # Use deployment token
swa deploy --dry-run                    # Preview without deploying
Get deployment token:
  • Azure Portal: Static Web App → Overview → Manage deployment token
  • CLI:
    swa deploy --print-token
  • Environment variable:
    SWA_CLI_DEPLOYMENT_TOKEN
Key flags:
  • --env
    - Target environment (
    preview
    or
    production
    )
  • --deployment-token, -d
    - Deployment token
  • --app-name, -n
    - Azure SWA resource name
部署到Azure Static Web Apps。
bash
swa deploy                              # 使用配置文件部署
swa deploy ./dist                       # 部署特定文件夹
swa deploy --env production             # 部署到生产环境
swa deploy --deployment-token <TOKEN>   # 使用部署令牌
swa deploy --dry-run                    # 预览部署(不实际部署)
获取部署令牌:
  • Azure门户:静态Web应用 → 概述 → 管理部署令牌
  • CLI:
    swa deploy --print-token
  • 环境变量:
    SWA_CLI_DEPLOYMENT_TOKEN
主要参数:
  • --env
    - 目标环境(
    preview
    production
  • --deployment-token, -d
    - 部署令牌
  • --app-name, -n
    - Azure SWA资源名称

swa db

swa db

Initialize database connections.
bash
swa db init --database-type mssql
swa db init --database-type postgresql
swa db init --database-type cosmosdb_nosql
初始化数据库连接。
bash
swa db init --database-type mssql
swa db init --database-type postgresql
swa db init --database-type cosmosdb_nosql

Scenarios

场景示例

Create SWA from Existing Frontend and Backend

从现有前端和后端创建SWA

Always run
swa init
before
swa start
or
swa deploy
. Do not manually create
swa-cli.config.json
.
bash
undefined
在运行
swa start
swa deploy
之前,务必先运行
swa init
。切勿手动创建
swa-cli.config.json
bash
undefined

1. Install CLI

1. 安装CLI

npm install -D @azure/static-web-apps-cli
npm install -D @azure/static-web-apps-cli

2. Initialize - REQUIRED: creates swa-cli.config.json with auto-detected settings

2. 初始化 - 必须执行:创建包含自动检测设置的swa-cli.config.json

npx swa init # Interactive mode
npx swa init # 交互式模式

OR

npx swa init --yes # Accept auto-detected defaults
npx swa init --yes # 接受自动检测的默认设置

3. Build application (if needed)

3. 构建应用(如有需要)

npm run build
npm run build

4. Test locally (uses settings from swa-cli.config.json)

4. 本地测试(使用swa-cli.config.json中的设置)

npx swa start
npx swa start

5. Deploy

5. 部署

npx swa login npx swa deploy --env production
undefined
npx swa login npx swa deploy --env production
undefined

Add Azure Functions Backend

添加Azure Functions后端

  1. Create API folder:
bash
mkdir api && cd api
func init --worker-runtime node --model V4
func new --name message --template "HTTP trigger"
  1. Example function (
    api/src/functions/message.js
    ):
javascript
const { app } = require('@azure/functions');

app.http('message', {
    methods: ['GET', 'POST'],
    authLevel: 'anonymous',
    handler: async (request) => {
        const name = request.query.get('name') || 'World';
        return { jsonBody: { message: `Hello, ${name}!` } };
    }
});
  1. Set API runtime in
    staticwebapp.config.json
    :
json
{
  "platform": { "apiRuntime": "node:20" }
}
  1. Update CLI config in
    swa-cli.config.json
    :
json
{
  "configurations": {
    "app": { "apiLocation": "api" }
  }
}
  1. Test locally:
bash
npx swa start ./dist --api-location ./api
  1. 创建API文件夹:
bash
mkdir api && cd api
func init --worker-runtime node --model V4
func new --name message --template "HTTP trigger"
  1. 示例函数
    api/src/functions/message.js
    ):
javascript
const { app } = require('@azure/functions');

app.http('message', {
    methods: ['GET', 'POST'],
    authLevel: 'anonymous',
    handler: async (request) => {
        const name = request.query.get('name') || 'World';
        return { jsonBody: { message: `Hello, ${name}!` } };
    }
});
  1. staticwebapp.config.json
    中设置API运行时:
json
{
  "platform": { "apiRuntime": "node:20" }
}
  1. swa-cli.config.json
    中更新CLI配置:
json
{
  "configurations": {
    "app": { "apiLocation": "api" }
  }
}
  1. 本地测试:
bash
npx swa start ./dist --api-location ./api

**Supported API runtimes:** `node:18`, `node:20`, `node:22`, `dotnet:8.0`, `dotnet-isolated:8.0`, `python:3.10`, `python:3.11`

**支持的API运行时:** `node:18`, `node:20`, `node:22`, `dotnet:8.0`, `dotnet-isolated:8.0`, `python:3.10`, `python:3.11`

Set Up GitHub Actions Deployment

配置GitHub Actions部署

  1. Create SWA resource in Azure Portal or via Azure CLI
  2. Link GitHub repository - workflow auto-generated, or create manually:
.github/workflows/azure-static-web-apps.yml
:
yaml
name: Azure Static Web Apps CI/CD

on:
  push:
    branches: [main]
  pull_request:
    types: [opened, synchronize, reopened, closed]
    branches: [main]

jobs:
  build_and_deploy:
    if: github.event_name == 'push' || (github.event_name == 'pull_request' && github.event.action != 'closed')
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - name: Build And Deploy
        uses: Azure/static-web-apps-deploy@v1
        with:
          azure_static_web_apps_api_token: ${{ secrets.AZURE_STATIC_WEB_APPS_API_TOKEN }}
          repo_token: ${{ secrets.GITHUB_TOKEN }}
          action: upload
          app_location: /
          api_location: api
          output_location: dist

  close_pr:
    if: github.event_name == 'pull_request' && github.event.action == 'closed'
    runs-on: ubuntu-latest
    steps:
      - uses: Azure/static-web-apps-deploy@v1
        with:
          azure_static_web_apps_api_token: ${{ secrets.AZURE_STATIC_WEB_APPS_API_TOKEN }}
          action: close
  1. Add secret: Copy deployment token to repository secret
    AZURE_STATIC_WEB_APPS_API_TOKEN
Workflow settings:
  • app_location
    - Frontend source path
  • api_location
    - API source path
  • output_location
    - Built output folder
  • skip_app_build: true
    - Skip if pre-built
  • app_build_command
    - Custom build command
  1. 在Azure门户或通过Azure CLI创建SWA资源
  2. 关联GitHub仓库 - 工作流会自动生成,也可手动创建:
.github/workflows/azure-static-web-apps.yml
:
yaml
name: Azure Static Web Apps CI/CD

on:
  push:
    branches: [main]
  pull_request:
    types: [opened, synchronize, reopened, closed]
    branches: [main]

jobs:
  build_and_deploy:
    if: github.event_name == 'push' || (github.event_name == 'pull_request' && github.event.action != 'closed')
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - name: Build And Deploy
        uses: Azure/static-web-apps-deploy@v1
        with:
          azure_static_web_apps_api_token: ${{ secrets.AZURE_STATIC_WEB_APPS_API_TOKEN }}
          repo_token: ${{ secrets.GITHUB_TOKEN }}
          action: upload
          app_location: /
          api_location: api
          output_location: dist

  close_pr:
    if: github.event_name == 'pull_request' && github.event.action == 'closed'
    runs-on: ubuntu-latest
    steps:
      - uses: Azure/static-web-apps-deploy@v1
        with:
          azure_static_web_apps_api_token: ${{ secrets.AZURE_STATIC_WEB_APPS_API_TOKEN }}
          action: close
  1. 添加密钥: 将部署令牌复制到仓库密钥
    AZURE_STATIC_WEB_APPS_API_TOKEN
工作流设置:
  • app_location
    - 前端源码路径
  • api_location
    - API源码路径
  • output_location
    - 构建输出文件夹
  • skip_app_build: true
    - 若已预构建则跳过
  • app_build_command
    - 自定义构建命令

Troubleshooting

故障排除

IssueSolution
404 on client routesAdd
navigationFallback
with
rewrite: "/index.html"
to
staticwebapp.config.json
API returns 404Verify
api
folder structure, ensure
platform.apiRuntime
is set, check function exports
Build output not foundVerify
output_location
matches actual build output directory
Auth not working locallyUse
/.auth/login/<provider>
to access auth emulator UI
CORS errorsAPIs under
/api/*
are same-origin; external APIs need CORS headers
Deployment token expiredRegenerate in Azure Portal → Static Web App → Manage deployment token
Config not appliedEnsure
staticwebapp.config.json
is in
app_location
or
output_location
Local API timeoutDefault is 45 seconds; optimize function or check for blocking calls
Debug commands:
bash
swa start --verbose log        # Verbose output
swa deploy --dry-run           # Preview deployment
swa --print-config             # Show resolved configuration
问题解决方案
客户端路由返回404
staticwebapp.config.json
中添加
navigationFallback
并设置
rewrite: "/index.html"
API返回404验证
api
文件夹结构,确保已设置
platform.apiRuntime
,检查函数导出
找不到构建输出验证
output_location
与实际构建输出目录匹配
本地身份验证不工作使用
/.auth/login/<provider>
访问身份验证模拟器UI
CORS错误
/api/*
下的API为同源;外部API需要CORS请求头
部署令牌过期在Azure门户 → 静态Web应用 → 管理部署令牌中重新生成
配置未生效确保
staticwebapp.config.json
位于
app_location
output_location
本地API超时默认超时为45秒;优化函数或检查是否存在阻塞调用
调试命令:
bash
swa start --verbose log        # 详细输出
swa deploy --dry-run           # 预览部署
swa --print-config             # 显示解析后的配置