Nextjs dynamic routing not working in firebase hosting

Viewed 813

I have a dynamic router job/[jobId] but it doesn't work after hosting. I don't know how to write the rewrites in firebase.json for this as well. Here's my rewrites.

Currently firebase throws 404 if I access a page such as job/2 page

Output structure

├── job
│   └── [jobId]
│       └── index.html

pages structure

.
├── _app.js
├── _document.js
├── careers
│   └── index.js
├── index.js
├── job
│   └── [jobId].js
└── privacy.js

Rewrites

"rewrites": [
      {
        "source": "job/**",
        "destination": "job/[jobId]/index.html"
      }
2 Answers
"rewrites": [
      {
        "source": "/job/**",
        "destination": "/job/[jobId]/index.html"
      }

Starting / was missing

While facing the same issue, I encountered a discussion here which was very helpful in understanding how Firebase and Next.js interact, and therefore what solution I would need to use.

https://github.com/firebase/firebase-js-sdk/discussions/4980

The summary of what helped me can be found on that link, but I'll include it here for completeness.

  • Add trailingSlash: true, to next.js.config
    • This lets all static routing work (i.e. routes without a "slug")
  • Add dynamic / "slug" routes to the rewrites section of firebase.json

Relevant excerpt from firebase.json:

{
  "hosting": {
    "target": "my-app",
    "public": "frontend/out",
    "rewrites": [
      {
        "destination": "/job/[jobId]/index.html",
        "regex": "^/job/([^/]+?)(?:/)?$"
      },
    ]
  },
}

Here is a gist of a utility script that can grab all of your dynamic slug routes from the .next folder, and place them in firebase.json automatically (mostly for CI related use cases).

https://gist.github.com/jeff-r-koyaltech/6195f546764443d0cc7c5efe48fbe896

Related