Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

NextJS Dynamic Routing with Firebase#4980

dennemark started this conversation inGeneral
Jun 4, 2021· 11 comments· 15 replies
Discussion options

Edit: Consider reading this comment first:#4980 (reply in thread)


Hi,

I just have to share another solution for using NextJS with firebase, that I haven't found on the web yet.

I have been usingnext export to create a static site and host it. However, this approach is missing dynamic routing, leading to 404 pages, when urls are shared.
An alternative I have seen, is using a cloud function with custom nextjs server and routing, however it breaks my workflow with cloud functions and is therefore, not preferred.

Dynamic routing can be made possible easily however, by using firebase hosting rewrites. And instead of writing them on your own, you can easily copy pase them from your build nextjs page. Just go to.next/routes-manifest.json and copy the dynamic routes section. I.e.:

"dynamicRoutes": [          {            "page": "/user/[id]",            "regex": "^/user/([^/]+?)(?:/)?$",            "routeKeys": {                "id": "id"            },            "namedRegex": "^/user/(?<id>[^/]+?)(?:/)?$"        }]

and paste it tofirebase.json rewrites and edit as follows:

"rewrites": [        {            "destination": "/user/[id].html",  // ADD .html !  and rename page to destination            "regex": "^/user/([^/]+?)(?:/)?$",        }]

done!

Hope it will help some people.

Edit 03.05.2022:
If above rewrite does not work, maybe it works to add/index to the destination. Thanks to aki matsumoto for the hint!

"rewrites": [        {            "destination": "/user/[id]/index.html",  // ADD .html !  and rename page to destination            "regex": "^/user/([^/]+?)(?:/)?$",        }]
You must be logged in to vote

Replies: 11 comments 15 replies

Comment options

Thank you! <3

You must be logged in to vote
0 replies
Comment options

Thank you ! I was searching for a solution since hours 🙏

You must be logged in to vote
5 replies
@silverit
Comment options

Can you show me exactly how you do it? I tried changing the file firebase.json, but it's not working!!!

"rewrites": [      {        "source": "**",        "destination": "/index.html"      },      {        "destination": "/post/[slug].html",        "regex": "^/post/([^/]+?)(?:/)?$"      },      {        "destination": "/tag/[slug].html",        "regex": "^/tag/([^/]+?)(?:/)?$"      }    ]
@JoppeMeijers
Comment options

@silverit did you find any solution? Because i have the same issue as you with exact the same firebase.json

@silverit
Comment options

@silverit did you find any solution? Because i have the same issue as you with exact the same firebase.json

In my case, I added this linetrailingSlash: true, to filenext.config.js. Let NextJS generate theindex.html file for each slug. So I didn't need to edit the filefirebase.json, I keep the filefirebase.json as the code below:

{  "hosting": {    "public": "out",    "ignore": ["firebase.json", "**/.*", "**/node_modules/**"],    "rewrites": [      {        "source": "**",        "destination": "/index.html"      }    ]  }}
@samuelrondot
Comment options

@silverit did you find any solution? Because i have the same issue as you with exact the same firebase.json

Do you use SSR ? If you do , then you should use Vercel instead of Firebase . SSR doesn’t work on Firebase

@hkropp
Comment options

@samuelrondot for SSR to work with firebase you also need to add a rewrite rule such as:

{    "source": "/nextjsFunc",    "function": "ssrPROJECTNAME"}

Replace PROJECTNAME with your firebase project name.

Comment options

Thanks for your help. I found a way to fix my issue. I just add thisline `trailingSlash: true` to file `next.config.js`. Let NextJS generate the index.html file foreach slug.
On Tue, May 3, 2022 at 8:42 PM aki matsumoto ***@***.***> wrote: I made the following changes and it works. {- "destination": "/post/[slug].html",+ "destination": "/post/[slug]/index.html", "regex": "^/post/([^/]+?)(?:/)?$" } — Reply to this email directly, view it on GitHub <#4980 (comment)>, or unsubscribe <https://github.com/notifications/unsubscribe-auth/AARY36G6ENVJQS2OMCHVI6TVIEULVANCNFSM46CP4O7Q> . You are receiving this because you were mentioned.Message ID: ***@***.*** com>
-- Thanks & B. Regards,Phuong VoMobile App Developerm:0976071270e:***@***.***
You must be logged in to vote
0 replies
Comment options

I have the same issue but this solution didn't work for me

You must be logged in to vote
9 replies
@ibussieres
Comment options

OMG. That was it.
Thanks for the (really fast) reply ! I should've tried that, but I saw people leaving it there in the previous responses. Turns out the correct way is without the catch all.

@dominicdev
Comment options

@ibussieres can you show me how you did it? im having the same issue in next 13

@jeff-r-skillrev
Comment options

@dominicdev try the gist / script above. If you let it fully generate your file, then it should work. That's what@ibussieres did.

@jeff-r-skillrev
Comment options

"I wrote a script [...]"

@haris-aqeel I am confused. Your gist is identical to mine:
https://gist.github.com/jeff-r-koyaltech/6195f546764443d0cc7c5efe48fbe896

I am glad my script was helpful to you, but please don't take credit for someone else's work. Did you mean to improve it in some way? If so, great. Please share that.

@haris-aqeel
Comment options

@jeff-r-koyaltech I actually improved it to pass the path dynamically through cmd as args instead of writing it in the file, but I realized it was not a significant contribution, so removed it. No issues.

Comment options

You're a legend!

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
1 reply
@jeff-r-skillrev
Comment options

"I wrote a script [...]"

I am confused. Your gist is identical to mine:
https://gist.github.com/jeff-r-koyaltech/6195f546764443d0cc7c5efe48fbe896

I am glad my script was helpful to you, but please don't take credit for someone else's work.

Comment options

I managed to solve this by doing the following:

  • Loop through all html files in the/out dir and update therewrites section in thefirebase.json file
  • Make sure/ (the root dir) is at the very end of the file

Here's the code.... all made by chat-gpt of course 😅

package.json

"scripts": {  "dev": "next dev",  "build": "next build && node updateFirebaseRewrites.js",  "deploy": "npm run build && firebase deploy",  "start": "next start",  "lint": "next lint"},

updateFirebaseRewrites.js

const fs = require('fs');const path = require('path');const outDirectory = path.join(__dirname, 'out'); // Adjust if your directory structure is differentconst firebaseConfigPath = path.join(__dirname, 'firebase.json');// Function to read all .html files from a directoryfunction readHtmlFiles(dir) {    const files = fs.readdirSync(dir);    let htmlFiles = [];    files.forEach(file => {        const filePath = path.join(dir, file);        const stat = fs.statSync(filePath);        if (stat.isDirectory()) {            // Recursively read nested directories            htmlFiles = [...htmlFiles, ...readHtmlFiles(filePath)];        } else if (file.endsWith('.html') && file !== 'index.html') {            // Remove the 'out' directory and '.html' extension from path            const relativePath = path.relative(outDirectory, filePath).replace(/\.html$/, '');            htmlFiles.push(`/${relativePath}`);        }    });    return htmlFiles;}const htmlFiles = readHtmlFiles(outDirectory);// Generate rewrite rules for each HTML filelet rewrites = htmlFiles.map(file => ({    source: `${file}{,/**}`,    destination: `${file}.html`}));// Add the root path rewrite at the endrewrites.push({    source: "/{,/**}",    destination: "/index.html"});// Read the existing firebase.json configurationconst firebaseConfig = JSON.parse(fs.readFileSync(firebaseConfigPath, 'utf8'));// Update the rewrites in firebase.jsonfirebaseConfig.hosting = firebaseConfig.hosting || {};firebaseConfig.hosting.rewrites = rewrites;// Write the updated configuration back to firebase.jsonfs.writeFileSync(firebaseConfigPath, JSON.stringify(firebaseConfig, null, 2));console.log('firebase.json has been updated with new rewrites.');
You must be logged in to vote
0 replies
Comment options

Perfect, thank you 🙌

You must be logged in to vote
0 replies
Comment options

thank you so much i just spent hours trying to figure this out!!!

You must be logged in to vote
0 replies
Comment options

This works! Thanks for sharing.

Important:

  • append.html
  • use full path/a/b/[c]/d.html

Simply copy what you find inroutes-manifest.json :)

You must be logged in to vote
0 replies
Comment options

Works for me - this thread/approach seems super under-rated. I actually don't understand why this is not integrated into next already by default for static output targets.

You must be logged in to vote
0 replies
Sign up for freeto join this conversation on GitHub. Already have an account?Sign in to comment
Category
General
Labels
None yet
16 participants
@dennemark@ibussieres@jvsteiner@onurays@silverit@Manoj-nathwani@ssh-randy@dominicdev@hkropp@jeff-r-skillrev@JoppeMeijers@stuartrobinson3007@haris-aqeel@samuelrondot@benjaminbialy@prs99

[8]ページ先頭

©2009-2025 Movatter.jp