¿Qué es Firebase Hosting?
Firebase Hosting ofrece hosting rápido y seguro para tu app web, contenido estático y dinámico, y microservicios. El contenido se sirve por SSL desde el servidor edge más cercano en la CDN global de Google.
Con cero configuración, puedes desplegar apps web y servir contenido estático y dinámico en una CDN global con un solo comando. También puedes combinar Firebase Hosting con Cloud Functions para crear apps full‑stack.
🚀 Características clave
- 🔒 SSL gratis: Certificados SSL automáticos para dominios personalizados.
- 🌐 CDN global: Contenido servido desde edge servers en todo el mundo.
- ⚡ Despliegue con un comando: Despliega con un solo comando de la CLI.
- 🔄 Rollback instantáneo: Vuelve a versiones anteriores al instante.
- 🎯 URLs de vista previa: Comparte previews antes de publicar.
Configurar Firebase Hosting
Comienza con Firebase Hosting usando la CLI:
# Install Firebase CLI globally
npm install -g firebase-tools
# Login to Firebase
firebase login
# Initialize hosting in your project directory
firebase init hosting
Durante la inicialización se te pedirá:
- Seleccionar un proyecto de Firebase (o crear uno nuevo)
- Especificar tu carpeta pública (p. ej., "build", "dist", "public")
- Configurar como SPA (reescribir URLs a /index.html)
- Configurar builds automáticos con GitHub
Configuración de firebase.json
El archivo firebase.json configura tu hosting:
{
"hosting": {
"public": "build",
"ignore": [
"firebase.json",
"**/.*",
"**/node_modules/**"
],
"rewrites": [
{
"source": "**",
"destination": "/index.html"
}
]
}
}
Desplegar tu sitio
Despliega tu aplicación en Firebase Hosting:
# Build your app first (if needed)
npm run build
# Deploy to Firebase
firebase deploy --only hosting
# Deploy everything (hosting + functions + rules)
firebase deploy
$ firebase deploy --only hosting
=== Deploying to 'my-project'...
i deploying hosting
i hosting[my-project]: beginning deploy...
i hosting[my-project]: found 42 files in build
✓ hosting[my-project]: file upload complete
✓ Deploy complete!
Hosting URL: https://my-project.web.app
Configurar dominio personalizado
Conecta tu propio dominio a Firebase Hosting:
# Add custom domain via CLI
firebase hosting:channel:deploy --only hosting
# Or use the Firebase Console:
# 1. Go to Hosting in Firebase Console
# 2. Click "Add custom domain"
# 3. Enter your domain name
# 4. Verify ownership (TXT record)
# 5. Point your domain to Firebase (A records)
Registros DNS para dominio personalizado
# Add these A records to your DNS:
@ A 151.101.1.195
@ A 151.101.65.195
# For www subdomain, add a CNAME:
www CNAME your-project.web.app
Canales de vista previa
Crea URLs de preview para probar cambios antes de producción:
# Create a preview channel
firebase hosting:channel:deploy preview-name
# Example output:
# Channel URL: https://my-project--preview-name-abc123.web.app
# Preview channels expire after 7 days by default
# Set custom expiration:
firebase hosting:channel:deploy preview-name --expires 30d
# List all channels
firebase hosting:channel:list
# Delete a channel
firebase hosting:channel:delete preview-name
Reescrituras de URL
Configura rewrites para SPAs y rutas dinámicas:
{
"hosting": {
"rewrites": [
// Rewrite all requests to index.html (SPA)
{
"source": "**",
"destination": "/index.html"
},
// Rewrite to a Cloud Function
{
"source": "/api/**",
"function": "api"
},
// Rewrite to Cloud Run
{
"source": "/backend/**",
"run": {
"serviceId": "my-service",
"region": "us-central1"
}
}
]
}
}
Redirecciones
Configura redirecciones de URL:
{
"hosting": {
"redirects": [
// Simple redirect
{
"source": "/old-page",
"destination": "/new-page",
"type": 301
},
// Redirect with glob pattern
{
"source": "/blog/:post*",
"destination": "https://blog.example.com/:post",
"type": 302
},
// Redirect with regex
{
"source": "/users/:id(\\d+)",
"destination": "/profile/:id",
"type": 301
}
]
}
}
Encabezados personalizados
Configura headers para seguridad y caché:
{
"hosting": {
"headers": [
// Global security headers
{
"source": "**",
"headers": [
{
"key": "X-Frame-Options",
"value": "DENY"
},
{
"key": "X-Content-Type-Options",
"value": "nosniff"
},
{
"key": "X-XSS-Protection",
"value": "1; mode=block"
}
]
},
// Cache static assets
{
"source": "**/*.@(jpg|jpeg|gif|png|svg|webp|js|css|woff2)",
"headers": [
{
"key": "Cache-Control",
"value": "public, max-age=31536000, immutable"
}
]
},
// No cache for HTML
{
"source": "**/*.html",
"headers": [
{
"key": "Cache-Control",
"value": "no-cache, no-store, must-revalidate"
}
]
}
]
}
}
Desplegar apps Next.js
Despliega aplicaciones Next.js con Firebase Hosting y Cloud Functions:
# For static Next.js export
# next.config.js
module.exports = {
output: 'export',
distDir: 'out'
};
# Build and deploy
npm run build
firebase deploy --only hosting
# For SSR Next.js (with Cloud Functions)
# Install the Firebase Next.js adapter
npm install @firebase/experimental-nextjs
# firebase.json
{
"hosting": {
"source": ".",
"ignore": ["firebase.json", "**/.*", "**/node_modules/**"],
"frameworksBackend": {
"region": "us-central1"
}
}
}
# Deploy with frameworks support
firebase experiments:enable webframeworks
firebase deploy
GitHub Actions CI/CD
Configura despliegues automáticos con GitHub Actions:
# .github/workflows/firebase-hosting.yml
name: Deploy to Firebase Hosting
on:
push:
branches:
- main
pull_request:
branches:
- main
jobs:
build_and_deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Setup Node.js
uses: actions/setup-node@v3
with:
node-version: '18'
cache: 'npm'
- name: Install dependencies
run: npm ci
- name: Build
run: npm run build
- name: Deploy to Firebase (Preview)
if: github.event_name == 'pull_request'
uses: FirebaseExtended/action-hosting-deploy@v0
with:
repoToken: '${{ secrets.GITHUB_TOKEN }}'
firebaseServiceAccount: '${{ secrets.FIREBASE_SERVICE_ACCOUNT }}'
projectId: your-project-id
expires: 7d
- name: Deploy to Firebase (Production)
if: github.ref == 'refs/heads/main'
uses: FirebaseExtended/action-hosting-deploy@v0
with:
repoToken: '${{ secrets.GITHUB_TOKEN }}'
firebaseServiceAccount: '${{ secrets.FIREBASE_SERVICE_ACCOUNT }}'
projectId: your-project-id
channelId: live
Revertir despliegues
Vuelve a una versión anterior si es necesario:
# List recent deployments
firebase hosting:channel:list
# View deployment history in Firebase Console
# Go to Hosting > Release History
# Rollback using CLI
firebase hosting:clone SOURCE_SITE_ID:SOURCE_CHANNEL \
TARGET_SITE_ID:live
# Or use the Console:
# 1. Go to Hosting > Release History
# 2. Find the version you want
# 3. Click the menu (⋮) > Rollback
Múltiples sitios
Aloja múltiples sitios en un solo proyecto de Firebase:
# Add a new site
firebase hosting:sites:create my-second-site
# firebase.json with multiple sites
{
"hosting": [
{
"target": "main",
"public": "build",
"rewrites": [...]
},
{
"target": "admin",
"public": "admin-build",
"rewrites": [...]
}
]
}
# Set up deploy targets
firebase target:apply hosting main my-project
firebase target:apply hosting admin my-project-admin
# Deploy specific site
firebase deploy --only hosting:main
firebase deploy --only hosting:admin
💡 Puntos clave
- • Firebase Hosting sirve contenido desde una CDN global con SSL gratuito
- • Despliega con un solo comando: firebase deploy
- • Usa canales de preview para probar antes de publicar
- • Configura rewrites para SPAs y rutas de API
- • Configura CI/CD con GitHub Actions para despliegues automáticos
- • Vuelve a versiones anteriores al instante si es necesario
📚 Más recursos
-
Documentación de Firebase Hosting →
Guía completa de funciones de Firebase Hosting
-
Conectar un dominio personalizado →
Configuración paso a paso del dominio personalizado
-
Integración con GitHub →
Configura despliegues automáticos con GitHub Actions