Overcoming Dynamic Route Handling in a Static Next.js + Firebase Hosting Project
In one of the recent projects we worked on the SEO of a full-featured e-commerce website using Next.js which was hosted on Firebase Hosting. While this stack offers excellent performance and scalability, it also posed some unique challenges—especially when it came to handling dynamic routes in a statically exported Next.js project.
Let me share one particularly interesting problem we solved: Enabling dynamic country-based brand pages (e.g., /pages/brands/india) while using static exports.
The Challenge
Next.js typically supports dynamic routing through its file-based system, where you can create pages like [slug].jsx. However, when using next export, all routes need to be known at build time since the project becomes a collection of static HTML files.
This limitation became obvious when we needed a page like:
/pages/brands/[country]
We didn't want to create a new file for every country. Instead, we wanted to use a single brands.jsx file that adapts based on the URL parameter, like:
/pages/brands/india
/pages/brands/pakistan
Unfortunately, accessing /pages/brands/india resulted in a 404 error, because static Next.js didn't know how to resolve it.
The Solution
We took a multi-pronged approach to solve this:
1. Firebase Hosting Rewrites
Firebase allowed us to use regex-based rewrites to direct requests like /pages/brands/india to a statically exported file:
firebase.json
Recommended by LinkedIn
{
"regex": "^/pages/brands/(india|pakistan|turkey|russia|canada)(?:/)?$",
"destination": "/pages/brands/index.html"
}
This made sure all those country-specific URLs pointed to the same static HTML file generated for /pages/brands.
2. Dynamic Rendering in React
Inside brands.jsx, we used useRouter() from Next.js to grab the current path:
import { useRouter } from 'next/router';
const router = useRouter();
const country = router.asPath.split("/").pop();
We then used a switch or conditional logic to load dynamic content based on the country:
switch (country) {
case 'india':
return <BrandsContentIndia />;
case 'pakistan':
return <BrandsContentPakistan />;
default:
return <BrandsContentNew />;
}
This approach allowed us to reuse a single component and change its content dynamically based on the URL—while still benefiting from static export.
3. Fallback 404 Handling
We also ensured a clean fallback using Firebase's default rewrite:
firebase.json
{
"source": "**",
"destination": "/404/index.html"
}
This served a custom 404 page for any unknown routes.
What Was Learned
This challenge taught us how to bridge the gap between Next.js's static nature and Firebase Hosting's flexibility using smart rewrites and client-side routing logic. It's a clean, scalable solution for SEO-friendly static websites that still need some degree of dynamic behavior.
If you're working with static hosting and need dynamic-feeling pages, this is a great pattern to follow.