How to Configure Rewrites in Firebase Hosting
To configure rewrites in
firebase.json, add a rewrites array inside the hosting section. Each rewrite maps a URL pattern to a destination like a static file or a Cloud Function, enabling clean URL routing without changing the browser address.Syntax
The rewrites property is an array inside the hosting section of firebase.json. Each item has a source pattern and a destination or function to route requests.
- source: URL pattern to match (supports wildcards like
**). - destination: Path to a static file to serve (e.g.,
/index.html). - function: Name of a Cloud Function to handle the request.
json
{
"hosting": {
"rewrites": [
{
"source": "/some/path/**",
"destination": "/index.html"
},
{
"source": "/api/**",
"function": "apiHandler"
}
]
}
}Example
This example shows how to rewrite all URLs under /app/** to serve index.html, and all URLs under /api/** to a Cloud Function named api. This setup is common for single-page apps with backend APIs.
json
{
"hosting": {
"public": "public",
"rewrites": [
{
"source": "/app/**",
"destination": "/index.html"
},
{
"source": "/api/**",
"function": "api"
}
]
}
}Output
When visiting /app/home, Firebase serves public/index.html.
When visiting /api/users, Firebase routes request to Cloud Function 'api'.
Common Pitfalls
Common mistakes include:
- Not placing
rewritesinside thehostingsection. - Using
redirectsinstead ofrewriteswhen you want to keep the URL in the browser. - Forgetting to deploy Cloud Functions before referencing them in rewrites.
- Incorrect
sourcepatterns that do not match the intended URLs.
json
{
"hosting": {
"rewrites": [
{
"source": "/app/**",
"redirect": "/index.html"
}
]
}
}
// Correct way:
{
"hosting": {
"rewrites": [
{
"source": "/app/**",
"destination": "/index.html"
}
]
}
}Quick Reference
| Field | Description | Example |
|---|---|---|
| source | URL pattern to match (supports wildcards) | "/app/**" |
| destination | Static file path to serve | "/index.html" |
| function | Cloud Function name to handle request | "api" |
| hosting | Top-level section for hosting config | Contains rewrites array |
Key Takeaways
Add rewrites inside the hosting section of firebase.json to route URLs.
Use source patterns with wildcards to match multiple URLs.
Rewrite to static files with destination or to Cloud Functions with function.
Deploy Cloud Functions before referencing them in rewrites.
Rewrites keep the browser URL unchanged, unlike redirects.