Deploy Next.js to Firebase Hosting

When building a React project with Next.js, the common deployment option is Vercel. However, Firebase now provides a new service for deploying static or dynamic sites using Firebase Hosting. With Firebase Hosting, you can easily deploy your Next.js project. This means you have an alternative to Vercel for deployment that may better fit your needs.

In this article, we will explore the process of deploying a Next.js project to Firebase Hosting.

Firebase CLI

First let's install firebase cli we will use this tool to upload our next.js project to firebase hosting.

To install firebase cli automatically you can run this shell command in your terminal.

curl -sL https://firebase.tools | bash

It will download firebase cli binary and then set it into your binary path. To check if the cli already installed correctly you can runt his command.

firebase --version

You should see the cli version, as I am writing this article the firebase cli version is 12.0.0.

And then the last thing before we can start using the cli is setup the authentication by runing this command. It will automatically open authentication page in your browser. Or you can click the link that printed in your terminal. Then choose your account.

firebase login

To verify that you are already login you can run this command.

firebase projects:list

Firebase Hosting

Now let's use firebase hosting in our project. This time we will use this example next-blog project to deploy in firebase hosting.

Clone the project in your machine.

git clone https://github.com/ahmadrosid/next-blog.git

As of right now the firebase hosting cli still in experiment, so you need to enable it first by runing this command.

firebase experiments:enable webframeworks

Then select or create new firebase project by runing this command.

firebase init hosting

Here's example to use firebase init hosting in you project.

images/firebase-init-hosting.png

This will generate firebase.json config like this.

{
  "hosting": {
    "source": ".",
    "ignore": ["firebase.json", "**/.*", "**/node_modules/**"],
    "frameworksBackend": {
      "region": "us-central1"
    }
  }
}

Now you can use this command to run the project locally at http://localhost:5000/.

firebase serve --only hosting

Deploy

We have everything setup and we are ready to deploy. To deploy with firebase hosting cli run this command.

firebase deploy

This command will build your next.js project locally at .firebase folder and then upload it to firebase hosting. Make sure to ignore this folder in your gitignore.

images/firebase-deploy.png

You can see the example of this firebase hosting static site here. https://the-remotelane.web.app/

One thing you should keep in mind you need to enable billing for your account if you are using cloudfunction, this is will be used for SSR and api route of your next.js project.