azure-static-web-apps by github/awesome-copilot
npx skills add https://github.com/github/awesome-copilot --skill azure-static-web-appsAzure Static Web Apps (SWA) 托管静态前端,并可选配无服务器 API 后端。SWA CLI (swa) 提供了本地开发模拟和部署功能。
主要特性:
配置文件:
swa-cli.config.json - CLI 设置,由 swa init 创建(切勿手动创建)staticwebapp.config.json - 运行时配置(路由、身份验证、标头、API 运行时)- 可以手动创建npm install -D @azure/static-web-apps-cli
验证: npx swa --version
广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
重要提示:始终使用 swa init 创建配置文件。切勿手动创建 swa-cli.config.json。
swa init - 必需的第一步 - 自动检测框架并创建 swa-cli.config.jsonswa start - 在 http://localhost:4280 运行本地模拟器swa login - 使用 Azure 进行身份验证swa deploy - 部署到 Azureswa-cli.config.json - 由 swa init 创建,请勿手动创建:
swa init 进行交互式设置并检测框架swa init --yes 接受自动检测的默认值生成的配置示例(仅供参考):
{
"$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(位于应用源代码或输出文件夹中)- 此文件可以手动创建以进行运行时配置:
{
"navigationFallback": {
"rewrite": "/index.html",
"exclude": ["/images/*", "/css/*"]
},
"routes": [
{ "route": "/api/*", "allowedRoles": ["authenticated"] }
],
"platform": {
"apiRuntime": "node:20"
}
}
使用 Azure 进行身份验证以便部署。
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
基于现有前端和(可选的)API 配置新的 SWA 项目。自动检测框架。
swa init # 交互式设置
swa init --yes # 接受默认值
构建前端和/或 API。
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 # 从 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.js | 3000 |
| Angular | 4200 |
| Vite | 5173 |
关键标志:
--port, -p - 模拟器端口(默认: 4280)--api-location, -i - API 文件夹路径--api-port, -j - API 端口(默认: 7071)--run, -r - 启动开发服务器的命令--open, -o - 自动打开浏览器--ssl, -s - 启用 HTTPS部署到 Azure Static Web Apps。
swa deploy # 使用配置部署
swa deploy ./dist # 部署特定文件夹
swa deploy --env production # 部署到生产环境
swa deploy --deployment-token <TOKEN> # 使用部署令牌
swa deploy --dry-run # 预览而不部署
获取部署令牌:
swa deploy --print-tokenSWA_CLI_DEPLOYMENT_TOKEN关键标志:
--env - 目标环境 (preview 或 production)--deployment-token, -d - 部署令牌--app-name, -n - Azure SWA 资源名称初始化数据库连接。
swa db init --database-type mssql
swa db init --database-type postgresql
swa db init --database-type cosmosdb_nosql
在运行 swa start 或 swa deploy 之前,始终先运行 swa init。切勿手动创建 swa-cli.config.json。
# 1. 安装 CLI
npm install -D @azure/static-web-apps-cli
# 2. 初始化 - 必需:使用自动检测的设置创建 swa-cli.config.json
npx swa init # 交互模式
# 或者
npx swa init --yes # 接受自动检测的默认值
# 3. 构建应用程序(如果需要)
npm run build
# 4. 本地测试(使用 swa-cli.config.json 中的设置)
npx swa start
# 5. 部署
npx swa login
npx swa deploy --env production
mkdir api && cd api
func init --worker-runtime node --model V4
func new --name message --template "HTTP trigger"
2. 示例函数 (api/src/functions/message.js):
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}!` } };
}
});
3. 在 staticwebapp.config.json 中设置 API 运行时:
{
"platform": { "apiRuntime": "node:20" }
}
4. 更新 swa-cli.config.json 中的 CLI 配置:
{
"configurations": {
"app": { "apiLocation": "api" }
}
}
5. 本地测试:
npx swa start ./dist --api-location ./api
# 在 http://localhost:4280/api/message 访问 API
支持的 API 运行时: node:18, node:20, node:22, dotnet:8.0, dotnet-isolated:8.0, python:3.10, python:3.11
.github/workflows/azure-static-web-apps.yml:
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
3. 添加密钥: 将部署令牌复制到仓库密钥 AZURE_STATIC_WEB_APPS_API_TOKEN
工作流设置:
app_location - 前端源代码路径api_location - API 源代码路径output_location - 构建输出文件夹skip_app_build: true - 如果已预构建则跳过app_build_command - 自定义构建命令| 问题 | 解决方案 |
|---|---|
| 客户端路由返回 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 门户 → Static Web App → 管理部署令牌 中重新生成 |
| 配置未应用 | 确保 staticwebapp.config.json 位于 app_location 或 output_location 中 |
| 本地 API 超时 | 默认 45 秒;优化函数或检查是否存在阻塞调用 |
调试命令:
swa start --verbose log # 详细输出
swa deploy --dry-run # 预览部署
swa --print-config # 显示已解析的配置
每周安装量
7.5K
代码仓库
GitHub 星标数
26.9K
首次出现
2026 年 1 月 20 日
安全审计
安装于
codex7.4K
gemini-cli7.4K
opencode7.3K
github-copilot7.3K
cursor7.3K
claude-code7.3K
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:
Config files:
swa-cli.config.json - CLI settings, created byswa init (never create manually)staticwebapp.config.json - Runtime config (routes, auth, headers, API runtime) - can be created manuallynpm install -D @azure/static-web-apps-cli
Verify: npx swa --version
IMPORTANT: Always useswa init to create configuration files. Never manually create swa-cli.config.json.
swa init - Required first step - auto-detects framework and creates swa-cli.config.jsonswa start - Run local emulator at http://localhost:4280swa login - Authenticate with Azureswa deploy - Deploy to Azureswa-cli.config.json - Created by swa init, do not create manually:
swa init for interactive setup with framework detectionswa init --yes to accept auto-detected defaultsExample of generated config (for reference only):
{
"$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:
{
"navigationFallback": {
"rewrite": "/index.html",
"exclude": ["/images/*", "/css/*"]
},
"routes": [
{ "route": "/api/*", "allowedRoles": ["authenticated"] }
],
"platform": {
"apiRuntime": "node:20"
}
}
Authenticate with Azure for deployment.
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
Configure a new SWA project based on an existing frontend and (optional) API. Detects frameworks automatically.
swa init # Interactive setup
swa init --yes # Accept defaults
Build frontend and/or API.
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
Start local development emulator.
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:
| Framework | Port |
|---|---|
| React/Vue/Next.js | 3000 |
| Angular | 4200 |
| Vite | 5173 |
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 HTTPSDeploy to Azure Static Web Apps.
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:
swa deploy --print-tokenSWA_CLI_DEPLOYMENT_TOKENKey flags:
--env - Target environment (preview or production)--deployment-token, -d - Deployment token--app-name, -n - Azure SWA resource nameInitialize database connections.
swa db init --database-type mssql
swa db init --database-type postgresql
swa db init --database-type cosmosdb_nosql
Always runswa init before swa start or swa deploy. Do not manually create swa-cli.config.json.
# 1. Install CLI
npm install -D @azure/static-web-apps-cli
# 2. Initialize - REQUIRED: creates swa-cli.config.json with auto-detected settings
npx swa init # Interactive mode
# OR
npx swa init --yes # Accept auto-detected defaults
# 3. Build application (if needed)
npm run build
# 4. Test locally (uses settings from swa-cli.config.json)
npx swa start
# 5. Deploy
npx swa login
npx swa deploy --env production
mkdir api && cd api
func init --worker-runtime node --model V4
func new --name message --template "HTTP trigger"
2. Example function (api/src/functions/message.js):
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}!` } };
}
});
3. Set API runtime in staticwebapp.config.json:
{
"platform": { "apiRuntime": "node:20" }
}
4. Update CLI config in swa-cli.config.json:
{
"configurations": {
"app": { "apiLocation": "api" }
}
}
5. Test locally:
npx swa start ./dist --api-location ./api
# Access API at http://localhost:4280/api/message
Supported API runtimes: node:18, node:20, node:22, dotnet:8.0, dotnet-isolated:8.0, python:3.10, python:3.11
.github/workflows/azure-static-web-apps.yml:
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
3. Add secret: Copy deployment token to repository secret AZURE_STATIC_WEB_APPS_API_TOKEN
Workflow settings:
app_location - Frontend source pathapi_location - API source pathoutput_location - Built output folderskip_app_build: true - Skip if pre-builtapp_build_command - Custom build command| Issue | Solution |
|---|---|
| 404 on client routes | Add navigationFallback with rewrite: "/index.html" to staticwebapp.config.json |
| API returns 404 | Verify api folder structure, ensure platform.apiRuntime is set, check function exports |
| Build output not found | Verify output_location matches actual build output directory |
| Auth not working locally | Use /.auth/login/<provider> to access auth emulator UI |
Debug commands:
swa start --verbose log # Verbose output
swa deploy --dry-run # Preview deployment
swa --print-config # Show resolved configuration
Weekly Installs
7.5K
Repository
GitHub Stars
26.9K
First Seen
Jan 20, 2026
Security Audits
Gen Agent Trust HubPassSocketPassSnykPass
Installed on
codex7.4K
gemini-cli7.4K
opencode7.3K
github-copilot7.3K
cursor7.3K
claude-code7.3K
React 组合模式指南:Vercel 组件架构最佳实践,提升代码可维护性
102,200 周安装
| CORS errors | APIs under /api/* are same-origin; external APIs need CORS headers |
| Deployment token expired | Regenerate in Azure Portal → Static Web App → Manage deployment token |
| Config not applied | Ensure staticwebapp.config.json is in app_location or output_location |
| Local API timeout | Default is 45 seconds; optimize function or check for blocking calls |