Search code examples
firebasenext.jsfirebase-hostingdynamic-routing

nextJS api routes not working with Firebase Hosting


I am having an issue with using Next.js API routes when deploying my website to Firebase Hosting. Here is the api call: enter image description here

And here is the set up in the pages directory: enter image description here Here is the function used in email.js: enter image description here I changed the variables as to not give away my email address.

The call works when I use local host. However, when I build and deploy to firebase. I have tried to use the firebase url to make the api call, but I get a 404 page not found. I am not sure how to fix this. I would really appreciate any help.


Solution

  • Firebase hosting only hosts static files which is why your api routes don't work there. If you had a fully static Next site, you could host it on Firebase hosting. But if you want to use the api routes in Next, you need a server. One way to do this (albeit complicated) is to set up Firebase Functions with your api code and then rewrite requests in Firebase Hosting to that Firebase Function. It's complicated because it would require a fairly complex deploy process.

    If the rest of your site is static, you can use Firebase Hosting for that and then consider ditching the api routes and instead setting up a Firebase Function to act as your api completely separate from Next.

    Or if you want to keep it all in Next, consider something like Vercel for your site + api via Next.