(+351) 21 24 10006  ·  info@bconcepts.pt
Carnaxide, Lisboa

Cómo crear un Azure Static Web App con API en Azure Functions

João Barros 25 de November de 2026 4 min de lectura

Este tutorial muestra cómo crear un Azure Static Web App integrado con una API en Azure Functions, útil para alojar un sitio estático con un backend serverless. Aprendes por qué la vinculación automática, cómo hacer el deploy con la CLI y resolver errores comunes durante el proceso.

Prerequisitos

  • Suscripción de Azure activa y permisos para crear recursos.
  • Instalado: Azure CLI, Git, Node.js (incluye npm) y VS Code (opcional).
  • Cuenta GitHub (o repositorio Git) para el workflow de despliegue automático.
  • Conocimientos básicos de HTML/JavaScript y de Azure Functions.

Paso 1: Preparar la aplicación estática y la API

Crea una carpeta con la aplicación frontend simple y una API en Azure Functions (JavaScript). La estructura mínima es: /app para el frontend y /api para las Functions.

mkdir my-static-webapp && cd my-static-webapp
mkdir app api
# frontend simple
cat > app/index.html <<EOF
<!doctype html>
<html><head><meta charset="utf-8"><title>Static Web App</title></head>
<body>
  <h1>Hola Azure Static Web Apps</h1>
  <div id="msg">Cargando...</div>
  <script>fetch('/api/hello').then(r => r.json()).then(j => document.getElementById('msg').textContent = j.message);</script>
</body>
</html>
EOF

# crear Azure Function simple (JavaScript)
npm init -y
npm i -D azure-functions-core-tools@4 || true
func init api --javascript --worker-runtime node --skip-templates
cd api && func new --name HttpExample --template "HTTP trigger" --authlevel "anonymous"
# ajustar para devolver JSON
sed -i "s/context.res = { status: 200, body: \"Hello\" }/context.res = { body: { message: 'Olá do backend' } }/" HttpExample/index.js || true
cd ..

Paso 2: Inicializar repositorio Git y subir a GitHub

Azure Static Web Apps hace el despliegue automático vía GitHub Actions. Inicializa un repositorio, haz commit y push a un repo remoto en GitHub.

git init
git add .
git commit -m "Initial Static Web App + Azure Functions"
# crea un repo en GitHub manualmente y luego:
git remote add origin git@github.com:SEU-USER/SEU-REPO.git
git branch -M main
git push -u origin main

Paso 3: Crear el Static Web App en Azure vía CLI

Usa la Azure CLI para crear el recurso Static Web App. La CLI crea el workflow GitHub Actions que se encarga del build y del despliegue automático.

# login y seleccionar suscripción (si es necesario)
az login
az account set --subscription "SEU-NOME-DA-SUBSCRIPCAO"

# crear el Static Web App (requiere GitHub para despliegue automático)
az staticwebapp create \
  --name myStaticAppExample \
  --resource-group myResourceGroup \
  --location westeurope \
  --source https://github.com/SEU-USER/SEU-REPO \
  --branch main \
  --app-location "app" \
  --api-location "api" \
  --output json

Paso 4: Entender el workflow y resolver errores comunes

Tras crear, verifica los GitHub Actions en el repositorio. El workflow compilará el frontend y la API. Errores comunes: rutas incorrectas en app-location/api-location, versión de Node incompatible o dependencias faltantes en la carpeta api.

# verificar el estado del workflow en GitHub Actions (ejemplo de comando local para ver logs ya después del push)
# o ver en el portal GitHub: Actions > workflow creado por Azure Static Web Apps

# si la Function falla por dependencias, instala en la carpeta api:
cd api
npm install
cd ..

Paso 5: Configurar autenticación y reglas simples (opcional)

Static Web Apps incluye soporte para autenticación (producción con GitHub, Microsoft, Google, etc.) vía la ruta /.auth/login. Para probar, crea un archivo staticwebapp.config.json para rutas y autorización simple.

cat > app/staticwebapp.config.json <<JSON
{
  "routes": [
    { "route": "/api/*", "allowedRoles": ["anonymous"] }
  ]
}
JSON

git add . && git commit -m "Add config" && git push

Verificar el resultado

Después de que el workflow de GitHub Actions complete, accede a la URL del Static Web App proporcionada por Azure. Deberías ver la página estática y el mensaje procedente de la API: "Olá do backend". Si aparece 404 en la llamada /api, confirma las rutas app-location y api-location en el workflow y que las Functions se hayan construido sin errores.

Conclusión

Ahora tienes un Azure Static Web App con una API en Azure Functions, despliegue automático vía GitHub Actions y configuración básica de rutas. Próximos pasos: añadir autenticación, usar Managed Identities para acceder a otros recursos de Azure, o cambiar el build para frameworks como React/Vue. Consejo: si el workflow falla, revisa los logs en GitHub Actions — son la fuente más clara de diagnóstico.