azure-static-web-apps

작성자: github

정적 사이트와 서버리스 API를 Azure에 배포하며, 로컬 개발 에뮬레이션 및 CLI 자동화를 지원합니다. API 프록시, 인증 시뮬레이션, React, Vue, Angular, Next.js 등 프레임워크 자동 감지 기능을 갖춘 로컬 에뮬레이터(swa start)를 제공합니다. Node.js, Python, .NET 런타임을 사용하는 Azure Functions 백엔드를 지원하며, staticwebapp.config.json을 통해 경로, 인증 규칙, 헤더를 구성할 수 있습니다. 배포 워크플로우는 swa init(프레임워크 자동 감지), swa build, swa start... 순서로 진행됩니다.

npx skills add https://github.com/github/awesome-copilot --skill azure-static-web-apps

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

General Instructions

Installation

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

Verify: 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

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):

{
  "$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"
  }
}

Command-line Reference

swa login

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

swa init

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

swa build

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

swa start

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:

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

swa deploy

Deploy 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:

  • 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

swa db

Initialize database connections.

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

Always run swa 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

Add Azure Functions Backend

  1. Create API folder:
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):
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:
{
  "platform": { "apiRuntime": "node:20" }
}
  1. Update CLI config in swa-cli.config.json:
{
  "configurations": {
    "app": { "apiLocation": "api" }
  }
}
  1. 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

Set Up GitHub Actions Deployment

  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:

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

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:

swa start --verbose log        # Verbose output
swa deploy --dry-run           # Preview deployment
swa --print-config             # Show resolved configuration

github의 다른 스킬

console-rendering
github
Go에서 struct 태그 기반 콘솔 렌더링 시스템 사용 지침
official
acquire-codebase-knowledge
github
사용자가 기존 코드베이스에 대한 매핑, 문서화, 또는 온보딩을 명시적으로 요청할 때 이 스킬을 사용하세요. "이 코드베이스를 매핑해줘", "문서화해줘"와 같은 프롬프트에서 트리거됩니다.
official
acreadiness-assess
github
현재 리포
official
acreadiness-generate-instructions
github
AgentRC 명령어를 통해 맞춤형 AI 에이전트 지침 파일을 생성합니다. .github/copilot-instructions.md 파일을 생성합니다(기본값, VS Code의 Copilot에 권장됨).
official
acreadiness-policy
github
사용자가 AgentRC 정책을 선택, 작성 또는 적용할 수 있도록 지원합니다. 정책은 관련 없는 검사를 비활성화하고, 영향/수준을 재정의하며, 설정을 통해 준비 상태 점수를 사용자 지정합니다.
official
add-educational-comments
github
코드 파일에 교육용 주석을 추가하여 효과적인 학습 자료로 변환합니다. 설명의 깊이와 어조를 세 가지 설정 가능한 지식 수준(초급, 중급, 고급)에 맞게 조정합니다. 파일이 제공되지 않으면 자동으로 요청하며, 빠른 선택을 위해 번호 목록 매칭을 제공합니다. 교육용 주석만을 사용하여 파일을 최대 125%까지 확장합니다(엄격한 제한: 새 줄 400개, 1,000줄 초과 파일의 경우 300개). 파일 인코딩, 들여쓰기 스타일, 구문 정확성 등을 유지합니다.
official
adobe-illustrator-scripting
github
Adobe Illustrator 자동화 스크립트를 ExtendScript(JavaScript/JSX)로 작성, 디버깅 및 최적화합니다. 스크립트를 생성하거나 수정하여 조작할 때 사용합니다.
official
agent-governance
github
선언적 정책, 의도 분류, AI 에이전트 도구 접근 및 행동 제어를 위한 감사 추적. 구성 가능한 거버넌스 정책은 허용/차단된 도구, 콘텐츠 필터, 속도 제한, 승인 요구 사항을 정의하며, 코드가 아닌 구성으로 저장됨. 의미론적 의도 분류는 패턴 기반 신호를 사용하여 도구 실행 전에 위험한 프롬프트(데이터 유출, 권한 상승, 프롬프트 인젝션)를 탐지함. 도구 수준 거버넌스 데코레이터는 함수에서 정책을 적용함...
official