Firebase Hosting Rewrites — Serving Dynamic Content and SPA Routing with Cloud Functions
In this tutorial, you will learn about Firebase Hosting Rewrites. We cover key concepts, practical examples, and best practices to help you master this topic.
Firebase Hosting rewrites allow you to serve dynamic content from Cloud Functions at specific URL paths, implement SPA fallback routing, and configure redirects and custom headers.
What You'll Learn
- Configuring rewrites to Cloud Functions
- SPA fallback routing with rewrites
- Setting custom headers and redirects
Why It Matters
Rewrites enable full-stack applications on Firebase without managing servers. SPA fallback routing is essential for client-side routing frameworks. DodaTech's dashboard application uses Hosting rewrites for API proxying and SPA routing.
Code Examples
// firebase.json with rewrites, redirects, and headers
{
"hosting": {
"public": "build",
"ignore": [
"firebase.json",
"**/.*",
"**/node_modules/**"
],
"rewrites": [
// SPA fallback - send all unknown paths to index.html
{
"source": "**",
"destination": "/index.html"
},
// API routes proxied to Cloud Functions
{
"source": "/api/**",
"function": "api"
},
// Specific function rewrites
{
"source": "/auth/**",
"function": "authHandler"
},
{
"source": "/webhooks/stripe",
"function": "stripeWebhook"
}
],
"redirects": [
{
"source": "/old-path",
"destination": "/new-path",
"type": 301
},
{
"source": "/blog/:post",
"destination": "/articles/:post",
"type": 302
}
],
"headers": [
{
"source": "/api/**",
"headers": [
{ "key": "Access-Control-Allow-Origin", "value": "https://app.example.com" },
{ "key": "Cache-Control", "value": "no-cache" }
]
},
{
"source": "**/*.@(jpg|png|svg|webp)",
"headers": [
{ "key": "Cache-Control", "value": "public, max-age=31536000, immutable" }
]
}
]
}
}
// Cloud Function called via rewrite
const functions = require('firebase-functions');
const express = require('express');
const cors = require('cors');
const app = express();
app.use(cors({ origin: true }));
app.use(express.json());
app.get('/api/users', async (req, res) => {
const users = await getUsers();
res.json(users);
});
app.post('/api/users', async (req, res) => {
const user = await createUser(req.body);
res.status(201).json(user);
});
// Export Express app as a Cloud Function
exports.api = functions.https.onRequest(app);
// SPA configuration with framework routing
// For React Router, Vue Router, or Angular
import { BrowserRouter, Routes, Route } from 'react-router-dom';
function App() {
return (
<BrowserRouter>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/dashboard" element={<Dashboard />} />
<Route path="/settings" element={<Settings />} />
</Routes>
</BrowserRouter>
);
}
# Deploy hosting
firebase deploy --only hosting
# Preview deployment
firebase hosting:channel:deploy preview-name
# List deployments
firebase hosting:channel:list
Common Mistakes
1. Not Adding SPA Fallback Rewrite
Without rewrite to index.html, direct URL navigation or refresh returns 404.
2. Ordering Rewrites Incorrectly
More specific rewrites should come before the catch-all SPA rewrite.
3. Mixing Rewrites and Redirects Wrongly
Rewrites serve content without changing the URL. Redirects change the URL in the browser.
4. Forgetting to Deploy Functions with Hosting
If a rewrite targets a function, the function must be deployed separately.
5. Not Setting Cache Headers for Static Assets
Missing cache headers reduces performance. Cache immutable assets aggressively.
Practice Questions
- What is the difference between a rewrite and a redirect?
- How do you configure SPA fallback routing?
- How do you proxy API requests to Cloud Functions?
- How do you set custom headers for specific file types?
- What order should rewrites be listed in?
Answers:
- Rewrites serve content at the same URL; redirects change the URL in the browser.
- Add a rewrite from ** to /index.html.
- Add a rewrite from /api/** to your Cloud Function name.
- Use the headers section in firebase.json with a glob pattern.
- Most specific patterns first, catch-all SPA rewrite last.
Challenge: Configure Firebase Hosting for a React SPA with Cloud Functions API backend. Set up rewrites for the API, SPA fallback routing, custom headers for Caching, and redirects for legacy URLs.
FAQ
Mini Project
Build a full-stack application with Firebase Hosting and Cloud Functions. Configure rewrites for the API backend, SPA fallback routing for React, custom headers for caching static assets, and redirects for legacy URL support. Deploy to preview channels.
What's Next
Explore Firebase Cloud Messaging for push notifications, then learn about Cloud Messaging topics for message targeting.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro